// @ฉ 2011-03-02 15:20

var asThaiMonth = new Array('ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.','ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.');
var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyz';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var thchar = 'กะขัฃาคำฅิฆีงึจืฉุชูซฌ็ญ่ฎ้ฏ๊ฐ๋ฑ์ฒํณดเตแถโทใธไนๅบๆปผฝพฟภมยรฤลฦวศษสหฬอฮฯ๐๑๒๓๔๕๖๗๘๙';
var spc = '\@\.\-\_';

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
//var asAvailableScreen = getAvailableScreenSize();

function isValid(parm,val) {
	for(var i=0,iLen=parm.length; i<iLen; i++) {
		if(val.indexOf(parm.charAt(i),0) == -1) return false;
	}
	
	return true;
}

function isNum(parm) {return isValid(parm,numb);}
function isLower(parm) {return isValid(parm,lwr);}
function isUpper(parm) {return isValid(parm,upr);}
function isAlpha(parm) {return isValid(parm,lwr+upr);}
function isAlphanum(parm) {return isValid(parm,lwr+upr+numb);}

function urlEncode(inputString, encodeAllCharacter) {
	var outputString = '';
	
	if(inputString != null){
		for(var i=0,iLen=inputString.length; i<iLen; i++ ) {
			var charCode = inputString.charCodeAt(i);
			var tempText = "";
			
			if(charCode < 128) {
				if(encodeAllCharacter) {
					var hexVal = charCode.toString(16);
					outputString += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();  
				} else {
					outputString += String.fromCharCode(charCode);
				}
			} else if((charCode > 127) && (charCode < 2048)) {
				tempText += String.fromCharCode((charCode >> 6) | 192);
				tempText += String.fromCharCode((charCode & 63) | 128);
				outputString += escape(tempText);
			} else {
				tempText += String.fromCharCode((charCode >> 12) | 224);
				tempText += String.fromCharCode(((charCode >> 6) & 63) | 128);
				tempText += String.fromCharCode((charCode & 63) | 128);
				outputString += escape(tempText);
			}
		}
	}
	
	return outputString;
}

function detectValidUser(obj) {
	var w = '';
	var v = lwr + upr + numb + spc;
	
	for(var i=0,iLen=obj.value.length; i<iLen; i++) {
		var x = obj.value.charAt(i);
		if(v.indexOf(x,0) != -1) w += x;
	}
	
	obj.value = w;
}

function detectValidDisplayName(obj) {
	var w = '';
	var v = lwr + upr + numb + thchar + spc;
	
	for(var i=0,iLen=obj.value.length; i<iLen; i++) {
		var x = obj.value.charAt(i);
		if(v.indexOf(x,0) != -1) w += x;
	}
	
	obj.value = w;
}

function getRelativePos(obj) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	var pos = {offsetLeft:0,offsetTop:0};
	
	while(obj!=null){
		pos.offsetLeft += obj.offsetLeft;
		pos.offsetTop += obj.offsetTop;
		obj = isIE ? obj.parentElement : obj.offsetParent;
	}
	return pos;
}

function res(t,v) {
	var w = '';
	for(var i=0,iLen=t.value.length; i<iLen; i++) {
		var x = t.value.charAt(i);
		if(v.indexOf(x,0) != -1) w += x;
	}
	
	t.value = w;
}
	
function checkValidFormat(format, val) {
	for(var i=0,iLen=val.length; i<iLen; i++) {
		if(format.indexOf(val.charAt(i)) == -1) return false;
	}
	
	return true;
}

function _g(namex){   
	if(document.getElementById) {
		return document.getElementById(namex);
	} else if(document.all) {
		return document.all[namex];   
	} else {
		return null;
	}
}

function detectClientBrowser() {
	var nAgt = navigator.userAgent;
	var sBrowserName  = navigator.appName;
	var sFullVersion  = ''+parseFloat(navigator.appVersion); 
	
	if((verOffset = nAgt.indexOf("MSIE"))!=-1) {
		sBrowserName = "IE";
		sFullVersion = nAgt.substring(verOffset+5);
	} else if((verOffset = nAgt.indexOf("Opera"))!=-1) {
		sBrowserName = "Opera";
		sFullVersion = nAgt.substring(verOffset+6);
	} else if((verOffset = nAgt.indexOf("Chrome"))!=-1) {
		sBrowserName = "Chrome";
		sFullVersion = nAgt.substring(verOffset+7);
	} else if((verOffset = nAgt.indexOf("Safari"))!=-1) {
		sBrowserName = "Safari";
		sFullVersion = nAgt.substring(verOffset+7);
	} else if((verOffset = nAgt.indexOf("Firefox"))!=-1) {
		sBrowserName = "Firefox";
		sFullVersion = nAgt.substring(verOffset+8);
	} else if((nameOffset = nAgt.lastIndexOf(' ')+1) < (verOffset = nAgt.lastIndexOf('/'))) {
		sBrowserName = nAgt.substring(nameOffset,verOffset);
		sFullVersion = nAgt.substring(verOffset+1);
		
		if(sBrowserName.toLowerCase() == sBrowserName.toUpperCase()) {
			sBrowserName = navigator.appName;
		}
	}
	
	return [sBrowserName, sFullVersion];
}

// Event
function addLoadEvent(func) {
	var oldonload = window.onload;
	
	if(typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if(oldonload) {
				oldonload();
			}
			
			func();
		}
	}
}

// Check uudefined
function isDefined(variable) {return eval("(typeof(" + variable + ") != \"undefined\");");}

// JS trim
function JSTrim(str) {return str.replace(/^\s+|\s+$/g, '');}

// JS Alert message
function JSAlert(msg) {alert(msg);}

// Add Commas
function addCommas(number) {
	number = number.toString();
	
	if(number.length <= 3) return number;
	
	var mod = number.length % 3;
	var output = (mod > 0 ? (number.substring(0,mod)) : '');
	
	for(var i=0,iLen=Math.floor(number.length / 3); i<iLen; i++) {
		if((mod == 0) && (i == 0)) {
			output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
		} else {
			output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
		}
	}
	
	return (output);
}

// Valid password character
function checkValidPasswordCharacter(pass) {
	var sPattern = /[a-zA-Z0-9\!\@\#\$\%\^\&\*\(\)\{\}\[\]]/;
	
	for(var i=0,iLen=pass.length; i<iLen; i++) {
		if(!sPattern.test(pass.charAt(i))) return false;
	}
	
	return true;
}

function checkValidEmailFormat(str){
	var exclude = /[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
	var check = /@[\w\-]+\./;
	var checkend = /\.[a-zA-Z]{2,3}$/;

	// Check email format
	if(!(!exclude.test(str) && check.test(str) && checkend.test(str))) {
		return false;
	} else {
		return true;
	}
}

function checkValidDisplayNameFormat(str) {
	var sPattern = eval("/[a-zA-Z0-9"+thchar+spc+"]/");
	
	for(var i=0,iLen=str.length; i<iLen; i++) {
		if(!sPattern.test(str.charAt(i))) return false;
	}
	
	return true;
}

function detectTripleCharacter(str) {
	for(i=0,len=(str.length-2); i<len; i++) {
		var sChar1 = str.charAt(i);
		var sChar2 = str.charAt((i+1));
		var sChar3 = str.charAt((i+2));
		
		if(sChar1 == sChar2 && sChar1 == sChar3) return true;
	}
	
	return false;
}

// Textbox focus
function ToggleTextDefault(obj, mode) {
	var sValue = obj.value.replace(/^\s+|\s+$/g, '');
	var sDefaultValue = obj.defaultValue;
	
	if(obj.type == 'text') {
		if(sValue == '' || sValue == sDefaultValue) {
			obj.value = (mode == 1) ? '' : sDefaultValue;
		}
	} else if(obj.type == 'textarea' && obj.readOnly == false) {
		if(sValue == '' || sValue.indexOf(sDefaultValue) > -1) {
			obj.value = (mode == 1) ? '' : sDefaultValue;
		}
	}
}

// Textarea limit
function limitChars(obj, limit) {
	var text = obj.value;	
	var textlength = text.length;

	if(textlength > limit) {
		obj.value = text.substr(0,limit);
		return false;
	} else {
		return true;
	}
}

// Random string
function randomString(len) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	var string_length = (typeof(len) !== "undefined") ? len : 10;
	
	var randomstring = '';
	for(var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	
	return randomstring;
}

// Change url
function replaceURL(url) {window.location.replace(url);}

// Get querystring
function getQuerystring(key, default_) {
	if(default_ == null) default_ = "";
	
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
	var qs = regex.exec(window.location.href);
	
	return (qs == null) ? default_ : qs[1];
}

// Row over image
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.01
  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 && d.getElementById) x=d.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];}
}

// Open new window
var newwindow = '';
function MM_openBrWindow(theURL,winName,width,height,other_features) { //v2.0
	if(!newwindow.closed && newwindow.location) {
		newwindow.location.href = theURL;
	} else {
		var features = '';
		
		if(width != '' && height != '') {
			var winl = (screen.width - width) / 2;
			var wint = (screen.height - height) / 2;
			features += 'width=' + width + ',height=' + height + ',top=' + wint + ',left=' + winl;
		}
		
		if(other_features != '') {
			 if(features != '') {
				 features += ',' + other_features;
			 } else {
				 features += other_features;
			 }
		}
		
		if(features != '') {
			newwindow = window.open(theURL,winName,features);
		} else {
			newwindow = window.open(theURL,winName);
		}
	}
	
	if(window.focus) {newwindow.focus()}
}

function PM_openWindow(url, name, width, height, param, center) {
	var bCenter = (center != '') ? center : true;
	var sFeature = 'width=' + width + ',height=' + height;
	
	if(bCenter) {
		var iLeft = (screen.width - width) / 2;
		var iTop = (screen.height - height) / 2;
		iTop = iTop - 50;
		
		sFeature += ',left=' + iLeft + ',top=' + iTop;
	}
	
	if(param != '') {
		sFeature += ',' + param;
	}
	
	newWin = window.open(url, name, sFeature);

	if(window.focus) { newWin.focus(); }
}

// Resize window (fit pic)
function fitPic() {
	var asBuffer = getAvailableScreenSize();
	
	iWidth = document.images[0].width - asBuffer[0];
	iHeight = document.images[0].height - asBuffer[1];
	
	window.resizeBy(iWidth, iHeight-1); /* with status bar */
	self.focus();
};

function ResizeW(w, h) {
	if(navigator.appName == "Microsoft Internet Explorer"){
		window.resizeTo(w+10,h+38)
	} else {
		window.innerWidth=w
		window.innerHeight=h
	}
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [scrOfX, scrOfY];
}
/*
function getAvailableScreenSize() {
	var viewportwidth;
	var viewportheight;
	
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if(typeof window.innerWidth != 'undefined') 
	{
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	}
	
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if((typeof document.documentElement != 'undefined') && (typeof document.documentElement.clientWidth != 'undefined') && (document.documentElement.clientWidth != 0))
	{
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	}
	
	// older versions of IE
	else{
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
	
	return [viewportwidth, viewportheight];
}
*/

function getScreenSize() {
	var width = screen.width;
	var height = screen.height;
	
	if(typeof(screen.deviceXDPI) == 'number') {
		width *= screen.deviceXDPI/screen.logicalXDPI;
		height *= screen.deviceYDPI/screen.logicalYDPI;
	}
	
	return [width,height];
}

function getViewPort() {
	var viewportwidth;
	var viewportheight;
	
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if(typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	}
	
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if(typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	}
	
	// older versions of IE
	else {
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
	
	return [viewportwidth, viewportheight];
}

// Open window full size
function openWindowMax(sURL, sWinName) {
	var wOpen;
	var sOptions;
	
	sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes,location=yes,directories=yes';
	sOptions = sOptions + ',width=' + (screen.availWidth - 10).toString();
	sOptions = sOptions + ',height=' + (screen.availHeight - 122).toString();
	sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';
	
	wOpen = window.open('', sWinName, sOptions);
	wOpen.location = sURL;
	wOpen.focus();
	wOpen.moveTo(0,0);
	wOpen.resizeTo(screen.availWidth, screen.availHeight);
	return wOpen;
}

// New line
function nl2br(text) {
	var NS = (navigator.appName=="Netscape")?true:false;
	return (NS) ? text.replace(/\n/g, "<br />\n") : text.replace(/\r\n/g, "<br />\n");
}

function findPos(obj) {
	var curleft = curtop = 0;
	if(obj.offsetParent) {
		do {curleft += obj.offsetLeft;curtop += obj.offsetTop;} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function ToHomePage() {
	window.location.replace(BASE_URL);
}

// Checkbox
function CheckAllManager(form_name, check_all_name, check_items_name) {
	this.oForm = document.forms[form_name];
	this.oCheckAll = this.oForm.elements[check_all_name];
	this.oCheckItems = this.oForm.elements[check_items_name];
	this.iTotalItems = 0;
	this.iChecked = 0;
	
	this.setTotalItems = function() {
		if(typeof this.oCheckItems != "undefined") {
			this.iTotalItems = (typeof this.oCheckItems.length != "undefined")?this.oCheckItems.length:1;
		}
	}
	
	this.getTotalItems = function() {
		return this.iTotalItems;
	}
	
	this.getCheckedItems = function() {
		return this.iChecked;
	}
	
	this.checkAll = function(obj) {
		if(this.iTotalItems == 0) return;
		
		if(obj.checked) {
			this.doCheck(true);
			this.iChecked = this.iTotalItems;
		} else {
			this.doCheck(false);
			this.iChecked = 0;
		}
	}
	
	this.checkItems = function(obj) {
		if(obj.checked) {
			this.iChecked++;
			
			if(this.iChecked == this.iTotalItems) {
				this.oCheckAll.checked = true;
			}
		} else {
			this.iChecked--;
			
			if(!this.oCheckAll.checked) {
				return;
			} else {
				this.oCheckAll.checked = false;
			}
		}
	}
	
	this.doCheck = function(bul) {
		if(this.iTotalItems > 1) {
			var iCount = 0;
			for(var i=0; i<this.iTotalItems; i++) {
				if(this.oCheckItems[i].disabled == false) {
					this.oCheckItems[i].checked = bul;
					iCount++;
				}
			}
			
			this.iChecked = iCount;
		} else {
			if(this.oCheckItems.disabled == false) {
				this.oCheckItems.checked = bul;
				this.iChecked = 1;
			}
		}
	}
	
	this.setTotalItems();
}

function insertDynamicJavascript(where, src) {        
	var oScript = document.createElement('script');
	oScript.type = 'text/javascript';
	oScript.src = src;
	
	document.getElementsByTagName(where)[0].appendChild(oScript); 
}

function resetFileField(span) {
	var oSpan = _g(span);
	if(oSpan) {
		var sField = oSpan.innerHTML;
		oSpan.innerHTML = sField;
	}
}

function compareSQLDate(d1,d2) {
	var asMatches = d1.match(/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})$/);
	var iY = parseInt(asMatches[1]);
	var iM = parseInt(asMatches[2])-1;
	var iD = parseInt(asMatches[3]);
	var iDate1 = new Date(iY,iM,iD).getTime();
	
	var asMatches = d2.match(/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})$/);
	var iY = parseInt(asMatches[1]);
	var iM = parseInt(asMatches[2])-1;
	var iD = parseInt(asMatches[3]);
	var iDate2 = new Date(iY,iM,iD).getTime();
	
	if(iDate1 == iDate2) {
		return 0;
	} else if(iDate1 > iDate2) {
		return 1;
	} else {
		return 2;
	}
}

// Login popup
function showLoginBox(mode) {
	var oLoginBox = _g('login_box');
	var oLoginPopupBox = _g('login_popupbox');
	
	if(oLoginPopupBox.style.visibility == 'visible') {
		//hideLoginBox();
		return;
	}
	
	var oPos = findPos(oLoginBox);
	var iTop = parseInt(oPos[1]);
	
	oLoginPopupBox.style.cssText = 'top:' + (iTop+36) + 'px;';
	oLoginPopupBox.style.visibility = 'visible';
	
	if(typeof(mode) !== "undefined" && mode == 'login') {
		oLoginPopupBox.innerHTML = '<div class="login_popupbox_header"><strong>Pantipmarket Member</strong>  <a href="javascript:hideLoginBox();">[x]</a></div>' + 
			'<div class="margin5">' + 
			'<ul>' + 
			'<li><a href="/member/my/" target="_blank">My PantipMarket</a></li>' + 
			'<li><a href="http://www.pantipmarket.com/mall/center/BackOffice/" target="_blank">เปิดหน้าจัดการร้านค้า</a></li>' + 
			'<li><a href="http://www.pantipmarket.com/mall/center/index.php?node=products" target="_blank">ไปหน้ารวมสินค้า (Product List)</a></li>' + 
			'<li><a href="/member/logout.php" target="_parent">ล็อกเอ้าท์ออกจากระบบ</a></li>' + 
			'</ul>' + 
			'</div>' + 
			'</div>';
	} else {
		var gr = urlEncode(window.parent.location.toString());
		
		oLoginPopupBox.innerHTML = '<div class="login_popupbox_header"><strong>Pantipmarket Login</strong> <a href="javascript:void(0);" onclick="hideLoginBox();">[x]</a></div>' + 
			'<div class="margin5">' + 
			'<div class="margin_T10">' + 
			'<form name="frm_login_popup" id="frm_login_popup" action="/member/login.php" method="post" onsubmit="return checkLoginPopup(this);">' + 
			'<div>' + 
			'<div class="float_left user_pass_box">Username:</div>' + 
			'<div class="float_left"><input type="text" name="username" id="username" value="" size="20" maxlength="50" class="input_box" onkeyup="detectValidUser(this);" onblur="detectValidUser(this);" /></div>' + 
			'<br class="clear" />' + 
			'</div>' + 
			'<div class="margin_T3">' + 
			'<div class="float_left user_pass_box">Password:</div>' + 
			'<div class="float_left"><input type="password" name="password" id="password" size="20" maxlength="50" class="input_box" /></div>' + 
			'<br class="clear" />' + 
			'</div>' + 
			'<div class="margin_T2">' + 
			'<div class="float_left user_pass_box">&nbsp;</div>' + 
			'<div class="float_left">' + 
			'<input type="submit" name="btn_login_submit" id="btn_login_submit" value="เข้าสู่ระบบ" class="btn1" />' + 
			'<input type="hidden" name="act" id="act" value="login" />' + 
			'<input name="url" type="hidden" id="url" value="' + window.location + '" />' + 
			'</div>' + 
			'<br class="clear" />' + 
			'</div>' + 
			'</form>' + 
			'</div>' + 
			'<div class="margin_T5">&bull; ลืม<a href="/member/forgot_user.php" target="_blank">ชื่อ</a>และ<a href="/member/forgot_pass.php" target="_blank">รหัสผ่าน</a><br />' + 
			'<a href="http://members.pantip.com/pantipmarket/signupnew.php?gr=' + gr + '" target="_blank" style="display:block;padding-top:7px;color:#F30;">สมาชิก Pantip.com ที่สมัครโดยวิธี ตรวจสอบ เลขที่บัตรประชาชน ใช้งานได้ทันทีที่นี่</a>' + 
			'</div>' + 
			'</div>';
	}
	
	if(_g('region')) {
		_g('region').style.visibility = 'hidden';
	}
}

function hideLoginBox() {
	if(_g('login_popupbox')) {
		_g('login_popupbox').style.visibility = 'hidden';
	}
	
	if(_g('region')) {
		_g('region').style.visibility = 'visible';
	}
}

function checkLoginPopup(form) {
	if(form.elements['username'].value == '') {
		alert('กรุณากรอก "User Name" ด้วยค่ะ');
		form.elements['username'].focus();
		return false;
	} else if(form.elements['password'].value == '') {
		alert('กรุณากรอก "Password" ด้วยค่ะ');
		form.elements['password'].focus();
		return false;
	} else {
		return true;
	}
	
	return false;
}

// Member login
function checkLogin(form) {
	var sMsg1 = (LANG == 'th') ? 'กรุณากรอก "Username"' : 'Please fill "Username"';
	var sMsg2 = (LANG == 'th') ? 'กรุณากรอก "Password"' : 'Please fill "Password"';
	
	if(form.elements['username'].length > 0 && form.elements['password'].length > 0) return true;
	
	if(form.elements['username'].length == 0) {
		alert(sMsg1);
		form.elements['username'].focus();
	} else if(form.elements['password'].length == 0) {
		alert(sMsg2);
		form.elements['password'].focus();
	}
	
	return false;
}

// ID Search
function checkIDSearch(obj) {
	var sMsg = (LANG == 'th') ? 'ใส่หมายเลขประกาศด้วยค่ะ' : ' Please fill ID';
	var sTextDefault = obj.parentNode.elements['id'].defaultValue;
	var sID = obj.parentNode.elements['id'].value;
	
	if(sID == sTextDefault || sID.length <= 0 || !checkValidFormat(numb, sID)) {
		alert(sMsg);
		obj.parentNode.elements['id'].focus();
	} else {
		window.open(BASE_URL + 'idsearch.php?id=' + sID, 'idsearch');
	}
}

// Your Suggestion form
function checkComments(form) {
	var oMessage = form.elements['message'];
	var oEmail = form.elements['email'];
	var oVerify = form.elements['pmverify'];
	var oBtn = form.elements['btn_suggestion'];
	
	if(oMessage.value == oMessage.defaultValue || oMessage.value.length < 10) {
		alert('กรุณาใส่ข้อความอย่างน้อย 10 ตัวอักษรค่ะ');
		oMessage.focus();
		return false;
	}
	
	if(oEmail.value == oEmail.defaultValue || oEmail.value.length <= 0) {
		alert('กรุณาใส่ E-mail ของคุณด้วยค่ะ');
		oEmail.focus();
		return false;
	} else {
		if(oEmail.value.indexOf(',') >= 0) {
			var asEmail = oEmail.value.split(',');
			
			if(asEmail.length > 5) {
				alert('ขออภัย ใส่ Email ได้สูงสุด 5 Email ค่ะ');
				oEmail.focus();
				return false;
			}
			
			for(var i=0,iLen=asEmail.length; i<iLen; i++) {
				var sBuff = asEmail[i].replace(/^\s+|\s+$/g, '');
				if(!checkValidEmailFormat(sBuff)) {
					alert('E-mail "' + sBuff + '" ไม่ใช่รูปแบบของ E-mail ที่ถูกต้อง กรุณาแก้ไขด้วยค่ะ');
					oEmail.focus();
					return false;
				}
			}
		} else {
			if(!checkValidEmailFormat(oEmail.value)) {
				alert('E-mail "' + oEmail.value + '" ไม่ใช่รูปแบบของ E-mail ที่ถูกต้อง กรุณาแก้ไขด้วยค่ะ');
				oEmail.focus();
				return false;
			}
		}
	}
	
	if(oVerify.value == oVerify.defaultValue || oVerify.value.length <= 0) {
		alert('กรุณาระบุ Comfirm Code/รหัสยืนยันการส่ง ให้ถูกต้องด้วยค่ะ');
		oVerify.focus();
		return false;
	}
	
	oBtn.disabled = true;
	
	_g('your_suggestion_form').style.display = 'none';
	
	_g('your_suggestion_message').innerHTML = (LANG == 'th') ? 'กำลังประมวลผล...' : 'Processing...';
	_g('your_suggestion_message').style.display = '';
	
	return true;
}

function showCommentsResult(mode, msg) {
	var oMessage = document.forms['frm_comments'].elements['message'];
	var oEmail = document.forms['frm_comments'].elements['email'];
	var oVerify = document.forms['frm_comments'].elements['pmverify'];
	var oBtn = document.forms['frm_comments'].elements['btn_suggestion'];
	
	if(mode == 1) {
		oMessage.value = oMessage.defaultValue;
		oEmail.value = oEmail.defaultValue;
		oVerify.value = oVerify.defaultValue;
		oBtn.disabled = false;
	}
	
	_g('your_suggestion_form').style.display = '';
	_g('your_suggestion_message').innerHTML = ' ';
	_g('your_suggestion_message').style.display = 'none';
	oBtn.disabled = false;
	
	alert(msg);
}

// Mail to
var mailtowin = '';
function openMailToWindow(id, email, ads_id) {
	if(typeof(ads_id) != "undefined") {
		var sUrl = BASE_URL + 'form.php?mode=mailto&ads_id=' + ads_id + '&id=' + id + '&email=' + email;
	} else {
		var sUrl = BASE_URL + 'form.php?mode=mailto&id=' + id + '&email=' + email;
	}
	
	if(!mailtowin.closed && mailtowin.location) {   
        mailtowin.location.href = sUrl;
    } else {   
        mailtowin = window.open(sUrl, 'mailto', 'width=650,height=410,status=yes,scrollbars=yes,resizable=yes');    
    }
	
    if(window.focus) mailtowin.focus();
}

// Member My
var mypagewin = '';
function openMyPageWin(board_id) {
	var sUrl = BASE_URL + 'member/my';
	
	if(!mypagewin.closed && mypagewin.location) {   
        mypagewin.location.href = sUrl;
    } else {   
        mypagewin = window.open(sUrl, 'MyPageWin', 'width=' + (screen.width*0.75) + 'px,height=' + (screen.height*0.65) + 'px,menubar=0,location=0,status=1,scrollbars=1,resizable=1,scrolling=1');
    }
	
    if(window.focus) {
		mypagewin.focus();
	}
}

// News scroll
function showIframeNewsScroller(mode, group) {
	var sUrl = BASE_PATH + 'news/iframe_news_scroll.php?mode=' + mode;
	sUrl += (typeof(group) != "undefined") ? '&group=' + group : '';
	
	document.write('<table style="width:100%;background-color:#FFF" border="0" cellspacing="0" cellpadding="0"><tbody><tr>');
	document.write('<td style="width:5px">&nbsp;</td><td style="width:90px"><a href="javascript:openNewsWindow();">ดูข่าวทั้งหมด</a></td>');
	document.write('<td style="width:auto"><div id="news_scroll_container" align="center"><iframe name="frame_news_scroll" id="frame_news_scroll" style="width:100%;height:25px" src="' + sUrl + '" frameborder="0" allowtransparency="1" scrolling="no"></iframe></div></td>');
	document.write('<td style="width:5px">&nbsp;</td></tr></tbody></table>');
}

var newswin = '';
function openNewsWindow() {
	var sUrl = BASE_URL + 'news/';
	
	if(!newswin.closed && newswin.location) {   
        newswin.location.href = sUrl;
    } else {   
        newswin = window.open(sUrl, 'NewsWin', 'width=' + (screen.width*0.75) + ',height=' + (screen.height*0.65) + ',menubar=0,location=0,status=1,scrollbars=1,resizable=1,scrolling=1');
    }
	
    if(window.focus) {
		newswin.focus();
	}
}

function SelectBoxPage(val) {
	var sLoc = window.location;
	sLoc = sLoc.toString();
	sLoc = sLoc.replace(/\#$/, '');
	
	if(sLoc.search(/^(.+)p\=[0-9]+(\&(.+))?$/) > -1) {
		window.location.replace(sLoc.replace(/(p\=[0-9]+)/, 'p=' + val));
	} else if(sLoc.search(/^(.+)\?(.+)$/) > -1) {
		window.location.replace(sLoc + '&p=' + val);
	} else {
		window.location.replace(sLoc + '?p=' + val);
	}
}

function toggleBrowseByProvinceBox(obj) {
	var sSelected = obj.options[obj.selectedIndex].value;
	
	for(var i=0,iLen=obj.length; i<iLen; i++) {
		var sValue = obj.options[i].value;
		
		var oProvinceBox = _g('province_box' + sValue);
		oProvinceBox.style.display = (sSelected == sValue) ? '' : 'none';
	}
}

function BrowseByProvinceLink(obj) {
	var oProvRelate = _g('prov_relate');
	var sUrl = obj.href;
	
	if(oProvRelate.checked == true) {
		obj.href = sUrl + '&prov_relate=1';
	}
	
	return false;
}

// Comment (tip)
function checkCommentForm(form) {
	var sMessage = JSTrim(form.elements['message'].value);
	var sEmail = JSTrim(form.elements['email'].value);
	
	if(sMessage.length < 10) {
		alert('PLease fill "Your Comment"');
		form.elements['message'].focus();
		return false;
	} else if(!checkValidEmailFormat(sEmail)) {
		alert('PLease fill valid "Your E-mail"');
		form.elements['email'].focus();
		return false;
	} else {
		form.elements['operating_system'].value = navigator.platform;
      	form.elements['referring_page'].value = document.referrer;
		
		return true;
	}
}

function alertCommentFormResult(msg, mode) {
	alert(msg);
	
	if(typeof(mode) != "undefined") {
		window.location.replace(window.location);
	}
}

// Track & Trace
function checkTrackTraceForm(form) {
	if(form.elements['TextBarcode'].value == "") {
		alert("กรุณาป้อนหมายเลขพัสดุด้วยค่ะ !!!"); 
		form.elements['TextBarcode'].focus();
		return false;
	} else if(form.TextBarcode.value.length < 13) {
		alert("กรุณาป้อนหมายเลขพัสดุให้ครบ 13 หลักด้วยค่ะ !!!");   
		form.elements['TextBarcode'].focus();
		return false;
	}
	
	return true;
}

var tracktracewin = '';
function openTrackTraceWindow() {
	if(!tracktracewin.closed && tracktracewin.location) {
        tracktracewin.location.href = "http://track.thailandpost.co.th/trackinternet/Image/receipt.gif";
    } else {
		tracktracewin = window.open("http://track.thailandpost.co.th/trackinternet/Image/receipt.gif", "tracktracewin", "width=250,height=300,top=200,left=250,status=1,resizable=0")
	}
	
	if(window.focus) {
		tracktracewin.focus();
	}
}

// Show Ads sub tab menu in english page
function showAdsSubTabMenu() {
	if(LANG == 'th') return;
	
	_g('main_tab_menu_ads').className = 'current_tab_menu';
	_g('main_tab_menu_classifieds').className = '';
	_g('sub_tab_menu_box').innerHTML = '<div class="sub_tab_menu3"><div class="padding_TB3"><a href="http://www.pantip.com/members/helpdesk/market_en.php" target="_blank">Please contact us click...</a></div></div>';
}

// Login form
function checkMarketLoginForm(form) {
	var sUsername = JSTrim(form.elements['username'].value);
	if(sUsername.length == 0) {
		alert('กรุณากรอก "User Name"');
		form.elements['username'].focus();
		return false;
	}
	
	var sPassword = JSTrim(form.elements['Password'].value);
	if(sPassword.length == 0) {
		alert('กรุณากรอก "Password"');
		form.elements['Password'].focus();
		return false;
	}
	
	return true;	
}

// ID Search form
function checkIDSearchForm(form) {
	var axTextConfig = {
		'th':'กรุณาใส่ ID ประกาศด้วยค่ะ',
		'en':'PLease fill valid ID'
	}
	
	if(!isNum(form.elements['id'].value)) {
		alert(axTextConfig[LANG]);
		form.elements['id'].focus();
		return false;
	}
	
	form.submit();
	return false;
}

// Search bar form
function checkSelectGroupSearch(form) {
	var asTextConfig = {
		'th':['เลือกหมวดสินค้าที่ต้องการค้นหาด้วยค่ะ!','ใส่ keyword ที่ต้องการค้นหาด้วยค่ะ!'],
		'en':['Please browse category!','Please fill keyword!']
	};
	
	/*if(form.elements['grp'].options[0].selected) {
		alert(asTextConfig[LANG][0]);
		form.elements['grp'].focus();
		return false;
	}*/
	
	var sKeyword = JSTrim(form.elements['q'].value);
	if(sKeyword == '') {
		alert(asTextConfig[LANG][1]);
		form.elements['q'].focus();
		return false;
	}
	
	form.submit();
	return false;
}

// เปิดหน้า My ตอน login
var membermywin = '';

function openMemberMyWindow(ref) {
	var sUrl = BASE_URL + 'member/my';
	
	if(!membermywin.closed && membermywin.location) {   
		membermywin.location.href = sUrl;
	} else {
		var asScreenSize = getScreenSize();
		membermywin = window.open(sUrl, 'membermy', 'width=' + asScreenSize[0] + 'px,height=' + asScreenSize[1] + 'px,menubar=1,location=1,status=1,scrollbars=1,resizable=1,scrolling=1');
	}
	
	if(window.focus) {
		membermywin.focus();
	}
	
	window.location.replace(ref);
}

// Items link
function ItemsLink(obj) {
	var sUrl = obj.href;
	
	if(_GROUP) {
		obj.href = sUrl + '?grp='+_GROUP;
	} else if(_LOC) {
		obj.href = sUrl + '?loc='+_LOC;
	}
	
	return false;
}

function getBoardIDSet() {
	return (typeof sBoardIDSet != 'undefined') ? sBoardIDSet : '';
}

function submitFilterForm(form) {
	form.submit();
	return false;
}

function submitFormGet(form) {
	form.submit();
	return false;
}

// Detect user screen
document.cookie = 'pmk_user_screen='+ screen.width + '|' + screen.height + '; path=/';

