// JavaScript Document
function domID(id){
	return ( document.getElementById ? document.getElementById(id) : false );
}
function block() {
	$.blockUI({ message: loading_img});
}

function get_qs(){	/*return array query string*/
	var fullURL = document.URL;
	var qs = (fullURL.indexOf('?') == -1 ? null : fullURL.split('?').pop());
	if ( ! qs) return qs;
	qs = qs.split('&');
	var arr_ret = [];
	arr_ret["url"] = fullURL.split('?').shift();
	for (var i in qs){
		var tmp = qs[i].split('=');
		arr_ret[tmp[0]] = tmp[1];
	}
	return arr_ret;
}

function set_qs(arr_qs){	/*return URL*/
	var fullURL = document.URL;
	if (typeof arr_qs == 'undefined') return fullURL;
	var qs = (fullURL.indexOf('?') == -1 ? '' : fullURL.split('?').pop());	
	qs = qs.split('&');
	var arr_new = new Array();
	for (var i in qs){
		var tmp = qs[i].split('=');
		var found = false;
		for (var j in arr_qs){
			var tmp2 = arr_qs[j].split('=');
			if (tmp[0] == tmp2[0]){
				arr_new.push(tmp[0]+'='+tmp2[1]);
				arr_qs.splice(j, 1);
				found = true;
				break;
			}
		}
		if ( ! found) arr_new.push(tmp[0]+'='+tmp[1]);
	}
	for (var i in arr_qs) arr_new.push(arr_qs[i]);
	return (fullURL.split('?').shift()+'?'+arr_new.join('&'));
}

function call_get(topic, action, qsAppend, func){
	var url = PREFIX_FF+topic+'_process.php?action='+action+(typeof qsAppend != 'undefined' && qsAppend != null ? qsAppend : '');
	$.get(url, {}, function(msg){
		//---remove error section	
		$('#error_section').remove();								
		if (typeof func != 'undefined'){
			if (typeof func == 'function'){
				func(msg);
			} else {
				if (msg.search(/^.+\..{3}.*$/ig) != -1)
					goto(msg);
				else 
					$(func).html(msg);
			}
		}
	});
}

function call_getProc(obj, func, isJson){
	//---process	
	if (typeof isJson == 'undefined') isJson = false;
	if (isJson){
		$.getJSON('proc_ajax_center.php', obj, function(msg){
			//---remove error section	
			$('#error_section').remove();														
			if (typeof func == 'function'){
				func(msg);
			} else if ( msg.content ){
				if (msg.content.search(/^.+\..{3}.*$/ig) != -1)
					goto(msg.content);
				else
					$(func).html(msg.content);				
			}
		});		
	} else {
		$.get('proc_ajax_center.php', obj, function(msg){
			//---remove error section	
			$('#error_section').remove();													
			if (typeof func == 'function'){
				func(msg);
			} else if ( msg ){
				if (msg.search(/^.+\..{3}.*$/ig) != -1)
					goto(msg);
				else
					$(func).html(msg);
			}
		});
	}	
}

function call_submit(url, func, isJson, bfSubmit, clsFrm){
	//---process	
	if (typeof clsFrm == 'undefined') clsFrm = false;
	if (typeof bfSubmit == 'undefined') bfSubmit = block;	
	if (typeof isJson == 'undefined') isJson = false;
	$('#myform').ajaxSubmit({
		url: url,
		dataType: (isJson ? 'json' : null),
		clearForm: clsFrm,
		beforeSubmit: bfSubmit,
		success: function(msg){
			//---remove error section	
			$('#error_section').remove();
			if (typeof func != 'undefined'){
				if (typeof func == 'function'){
					func(msg);
				} else {
					if ( isJson ) msg = msg.content;
					if (msg.search(/^.+\..{3}.*$/ig) != -1)
						goto(msg);
					else 
						$(func).html(msg);
				}
			}
		}
	});
}

function call_submitValidate(url, func, isJson, bfSubmit, clsFrm){
	//---process
	$.metadata.setType('attr', 'rule');
	validator();
	$('#myform').validate({
		meta: 'validate',
		errorPlacement: function(error,element){
			return true; 
		},		
		submitHandler: function(form){
			if (typeof clsFrm == 'undefined') clsFrm = false;
			if (typeof bfSubmit == 'undefined') bfSubmit = block;			
			if (typeof isJson == 'undefined') isJson = false;
			$('#myform').ajaxSubmit({
				url: url,
				clearForm: clsFrm,
				dataType: (isJson ? 'json' : null),
				beforeSubmit: bfSubmit,
				success: function(msg){
					//---remove error section	
					$('#error_section').remove();					
					if (typeof func != 'undefined'){
						if (typeof func == 'function'){
							func(msg);
						} else {
							if ( isJson ) msg = msg.content;
							if (msg.search(/^.+\..{3}.*$/ig) != -1)
								goto(msg);							
							else
								$(func).html(msg);				
						}
					}
				}
			});
		}
	});
}

function goto(url){
//	block();
	window.location = url;
}

function confirm_goto(url, msg){
	var ans = confirm(msg);
	if (ans) goto(url);
}

function dlg_confirm(msg, strFunc){
	var ans = confirm(msg);
	if (ans) eval(strFunc);
}

function countDown(elemDisplayId, amount, callFunc){	
	$('#'+elemDisplayId).text(amount);
	if ( ! amount){
		eval(callFunc);
	} else {
		--amount;		
		timeOut = setTimeout("countDown(\""+elemDisplayId+"\", "+amount+", \""+callFunc+"\")", 1000);
	}		
}

function cv2num(str){
	return (str.toString().replace(/,/ig, '') * 1);
}

function goToByScroll(id, duration){
	if (typeof duration == 'undefined') duration = 500;
	$('html, body').animate({ scrollTop: $("#"+id).offset().top }, duration);
}

function currency_format($number, $digit){
	if (typeof $digit == 'undefined') $digit = 0;
	return number_format($number, $digit, '.', ',');
}

function check_char_type(char_sender){
	var char_asc = char_sender.substring(0, 1).charCodeAt(0);
	switch (true){
		case (char_asc == 8 || char_asc == 127): return 'del';
		case (char_asc == 32): return 'space';
		case ((char_asc >= 0 && char_asc <= 47) 
			|| (char_asc >= 58 && char_asc <= 64)
			|| (char_asc >= 91 && char_asc <= 96)
			|| (char_asc >= 123 && char_asc <= 126)): return 'special';
		case (char_asc >= 48 && char_asc <= 57): return 'number';
		case ((char_asc >= 65 && char_asc <= 90)
			|| (char_asc >= 97 && char_asc <= 122)): return 'en';
		default: return 'etc';
	}
}

function check_char(str_sender, has_num, has_en, has_th, has_special, except_char){
	var str_len = str_sender.length;
	var arr_except = [];
	if (typeof except_char != 'undefined' && except_char){
		var str_len_except = except_char.length;
		for (var i = 0; i < str_len_except; i++) arr_except.push(except_char.substring(i, ( i + 1 )));
	}
	for (var i = 0; i < str_len; i++){
		var char = str_sender.substring(i, ( i + 1 ));
		if ( in_array(char, arr_except) ) continue;
		if ( ! has_num && check_char_type(char) == 'number' ) return false;
		if ( ! has_en && check_char_type(char) == 'en' ) return false;
		if ( ! has_th && check_char_type(char) == 'etc' ) return false;
		if ( ! has_special && check_char_type(char) == 'special' ) return false;
	}
	return true;
}

function popup_window(_fPath, _wid, _hei, _scr, _res, _type, _argu, _noFeature){	
	/*
	0=new window always
	1=check window already
	2=open modal dialog
	3=open modeless dialog
	*/
	if (typeof _scr == 'undefined' || ! _scr) _scr = 'yes';
	if (typeof _res == 'undefined' || ! _res) _res = 'yes';
	if (typeof _type == 'undefined' || !_type) _type = 0;	
	if (typeof _noFeature == 'undefined') _noFeature = false ;
	var _scaleTop = (screen.height - _hei - 50) / 2;
	var _scaleLeft = (screen.width - _wid - (_scr == 'yes' ? 30 : 0)) / 2;
	_wid += 19;	
	var _strOptional1 = "width=" + _wid + ",height=" + _hei + ",left=" + _scaleLeft + ",top=" + _scaleTop + ","
		+ "location=no,menubar=no,resizable=" + _res + ",toolbar=no,status=no,scrollbars=" + _scr;			
	var _strOptional2 = "dialogWidth:" + _wid + "px;dialogHeight:" + _hei + "px;dialogLeft:" + _scaleLeft + "px;dialogTop:" + _scaleTop + "px;"
		+ "center:yes;status:no;resizable:" + _res + ";scroll:" + _scr + ";";
	switch (_type){
		case 0:
			if ( ! _noFeature )
				_winPop0 = window.open(_fPath, "_blank", _strOptional1);
			else
				_winPop0 = window.open(_fPath, "_blank");
			_winPop0.focus();
			break;
		case 1:
			if (typeof _winPop1 == "undefined" || _winPop1.closed || !_winPop1.open){
				if ( ! _noFeature )
					_winPop1 = window.open(_fPath, "_blank", _strOptional1);
				else
					_winPop1 = window.open(_fPath, "_blank");
			} else {
				_winPop1.location = _fPath;
				_winPop1.focus();
			}
			break;
		case 2:
			if (typeof _argu == 'undefined' || !_argu) _argu = ""; 
			if ( ! _noFeature )
				_winPop2 = showModalDialog(_fPath, _argu, _strOptional2);
			else
				_winPop2 = showModalDialog(_fPath, _argu);	
		 	break;
		case 3:
			if (typeof _argu == 'undefined' || !_argu) _argu = ""; 
			if (typeof _winPop3 == "undefined" || _winPop3.closed || !_winPop3.open){
				if ( ! _noFeature )
					_winPop3 = showModelessDialog(_fPath, _argu,_strOptional2);
				else
					_winPop3 = showModelessDialog(_fPath, _argu);
			} else {
				_winPop3.focus();
			}
			break;
	}
}

function keynum(e, obj, idFocus){
	var key = ( e.keyCode ? e.keyCode : e.which );
	if ( key < 48 || key > 57 ){
		if ( key == 13 && $(obj).is('.key13blur') ){
			if ( typeof idFocus != 'undefined' ) $('#'+idFocus).focus();
		}
	}
	return ( ( key >= 48 && key <= 57 ) || key == 8 || key == 46 );
}

//*******************
//*****SPECIFIED*****
//*******************
function add_to_cart(product_id, section, objErr, mode, modeAwId, secondary_product_id){
	//---main process	
	if (typeof objErr == 'undefined' || ! objErr) objErr = { sec: section, pos: 'top' };
	var go_url = PREFIX_FF+'cart_add.php?product_id='+product_id+
		(typeof mode != 'undefined' && mode ? ('&mode='+mode) : '')+
		(typeof modeAwId != 'undefined' && modeAwId ? ('&modeawid='+modeAwId) : '');
	if ( typeof mode != 'undefined' && mode == 'specialdc' ) $('#hdn_sender_cart_add').val( secondary_product_id );
	call_submit(go_url, function(msg){
		if ( ! msg.status){
			switch (objErr.pos){
				case 'top':			$('#'+objErr.sec).prepend(msg.content);	break;
				case 'bottom':	$('#'+objErr.sec).append(msg.content);	break;
			}
			goToByScroll(objErr.sec);
			return false;
		}
		switch (mode){
			case 'birthday':
			case 'act':
			case 'specialdc':				
				$("img[id^='addtocart_'], .img_each_del, #img_empty").removeAttr('onclick');				
				goto(msg.content);	
				return;
			case 'premium':
				window.location.reload();
//				$('#'+section).html(msg.content[0]);
//				$('#div_premium').html(msg.content[1]);	
//				return;
			default:
				$('#'+section).html(msg.content);
				break;
		}
		goToByScroll(section);
	}, true);								 
}

function add_to_cart_sub(product_id){	//product_id=main id choose
	var go_url = PREFIX_FF+'cart_add_sub.php?product_id='+$('#hdn_choose_id_'+product_id).val()+'&quantity='+$('#sub_order_quantity_'+product_id).val();
	call_submit(go_url, function(msg){
		if ( ! cv2num(msg.status) ){
			$('#div_error_section').html(msg.content);
		} else {
			$('#div_cart_sub').html(msg.content);
			if ( msg.status == 2 ){	//goto actual cart			
				add_to_cart($('#main_product_reward').val(), 'div_error_section', null, 'specialdc', $('#awid').val());
			}
		}
	}, true);
}

function add_to_cart_redeem(product_id, parent_id, section, objErr){
	//---main process	
	if (typeof objErr == 'undefined' || ! objErr) objErr = { sec: section, pos: 'top' };
	var go_url = PREFIX_FF+'exchange_point_cart_add.php?product_id='+product_id+'&parent_id='+parent_id;
	var qty = $('#get_order_quantity_'+parent_id).val();
	if ( cv2num($('#txt_point_'+parent_id).val()) > ( cv2num($('#hdn_maxpoint_'+parent_id).val()) * qty ) ){
		$('#txt_point_'+parent_id).val(( cv2num($('#hdn_maxpoint_'+parent_id).val()) * qty ));
	}
	call_submit(go_url, function(msg){
		if ( msg.status <= 0 ){
			if ( msg.status == -1 ){
				$('#txt_point_'+parent_id).val($('#hdn_minpoint_'+parent_id).val() * $('#get_order_quantity_'+parent_id).val());
				domID('txt_point_'+parent_id).select();
			}
			switch (objErr.pos){
				case 'top':			$('#'+objErr.sec).prepend(msg.content);	break;
				case 'bottom':	$('#'+objErr.sec).append(msg.content);	break;
			}
			goToByScroll(objErr.sec);
			return false;
		}
		$('#'+section).html(msg.content);
		goToByScroll(section);
	}, true);								 
}

function manage_cart(url, isOrder){	
	var fullUrl = PREFIX_FF+url+(typeof isOrder != 'undefined' && isOrder == true ? ('?steporder=1') : '');
	call_submit(fullUrl, function(msg){
		if ( ! msg.status){
			$('#div_cart').html(msg.content); 
			return false; 
		} else {
			if (typeof isOrder != 'undefined' && isOrder == true){
				window.location.reload();
//				$('#div_cart').html(msg.content[0]);
//				$('#div_premium').html(msg.content[1]);
				return true;
			} else {
				$('#div_cart').html(msg.content);		
			}
		}
	}, true);
}

function delete_to_cart_sub(action){
	var url = PREFIX_FF+'cart_delete_sub.php?action='+action;
	call_submit(url, '#div_cart_sub', true);
}

//-------------------------
//---prepare adjust---//
//------------------------- 
function global_orders_switch_address(objVal){
/*	if (objVal == 'NM'){ 		
		$('#div_normal_address').css('display', 'block');
		$('#div_pod_address').css('display', 'none');
		$('#div_pay_method').css('display', 'block');
		$('#div_pod_method').css('display', 'none');
		$('#div_pay_remark').css('display', 'block');
		$('#div_pay_remark02').css('display', 'block');
		$('.cls_ocp_pod').css('display', 'none');
		$('.cls_ocp_pod :checkbox').attr('checked', false);
	} else {
		$('#div_normal_address').css('display', 'none');
		$('#div_pod_address').css('display', 'block');
		$('#div_pay_method').css('display', 'none');
		$('#div_pod_method').css('display', 'block');
		$('#div_pay_remark').css('display', 'none');
		$('#div_pay_remark02').css('display', 'none');
		$('.cls_ocp_pod').css('display', 'block');
	}	*/
	global_calculate_orders(true);
}

function cal_point_external_plus(domObj, pointPlus){
	var section = $('#div_point span:eq(0)');
	if ( domObj ){
		var val_plus = pointPlus * ($(domObj).attr('checked') ? 1 : -1);
		section.text(currency_format(cv2num(section.text()) + val_plus));
	} else {
		section.text(currency_format(pointPlus));
	}
	if ( cv2num(section.text()) > 1 ){
		$('#div_point span:eq(1)').css('display', 'none');
		$('#div_point span:eq(2)').css('display', 'inline');
	} else {
		$('#div_point span:eq(1)').css('display', 'inline');
		$('#div_point span:eq(2)').css('display', 'none');
	}
}

function global_select_relation(objAction, url, objClear01, objClear02, objClear03){
	var urls = url;	
	if(objClear01 != '') $("#"+objClear01).html('<option value="">' +$("#"+objClear01).attr("real")+ '</option>');
	if(objClear02 != '') $("#"+objClear02).html('<option value="">' +$("#"+objClear02).attr("real")+ '</option>');
	if(objClear03 != '') $("#"+objClear03).html('<option value="">' +$("#"+objClear03).attr("real")+ '</option>');
	$.getJSON(urls, function(j){
		if(objClear01 != '') $("#"+objClear01).html('<option value="">' +$("#"+objClear01).attr("real")+ '</option>');
		if(objClear02 != '') $("#"+objClear02).html('<option value="">' +$("#"+objClear02).attr("real")+ '</option>');
		if(objClear03 != '') $("#"+objClear03).html('<option value="">' +$("#"+objClear03).attr("real")+ '</option>');
		var options = '';
		for (var i = 0; i < j.length; i++){
			if(j[i].optionValue == 0){
				options_value = '';
			} else {
				options_value = j[i].optionValue;
			}
			options += '<option value="'+options_value+'"  '+j[i].optionSelect+'>' + j[i].optionDisplay + '</option>';
		}		
		$("#"+objAction).html(options);
	})
}

function global_clear_postal_code(objEmpty){
	if (objEmpty){
		document.getElementById(objEmpty).value = '';
	}
}

function global_check_sample_select(objChange){
	var product_sample_qty_check = $('#product_sample_qty_check').val();
	var product_sample_id_check = $('#product_sample_id_check').val();	
	var check_val = 0;
	var my_split = new Array();	
	my_split = product_sample_id_check.split(',');
	for (var x in my_split){
		value_obj = $('#product_sample_qty_'+my_split[x]).val();
		if(value_obj != '') check_val = check_val + (value_obj*1);
	}	
	if(check_val > product_sample_qty_check){
		alert('คุณเลือกสินค้าตัวอย่างเกินกำหนด ('+product_sample_qty_check+' รายการ) กรุณาตรวจสอบใหม่อีกครั้งค่ะ');	
		$(objChange).val(0) ;
	}
}

function add_voucher(){
	if ($('tr.voucher').length == $("select[name='orders_voucher_code[]']:first option").length - 1){
		alert("ขออภัย ไม่สามารถเพิ่มรายการคูปองได้อีก\nเนื่องจากเกินจำนวนคูปองที่มีอยู่ค่ะ");
		return false;
	}
	var last_voucher = $('tr.voucher:last');
	var new_voucher = last_voucher.clone(true);
	new_voucher.insertAfter(last_voucher);
	//***get last inx
	var inx = parseInt(last_voucher.find('select').attr('id').substring(last_voucher.find('select').attr('id').lastIndexOf('_') + 1)) + 1;	
	last_voucher.find("img[name='btnaddrow']").css('visibility', 'hidden');
	//***clean new
	new_voucher.find('select').attr('id', 'orders_voucher_code_'+inx).val(0);
	new_voucher.find("input[name='orders_voucher_value[]']").attr('id', 'orders_voucher_value_'+inx).val(currency_format(0, 2));	
	var opt_inx = last_voucher.find('select').attr('selectedIndex');
	if (opt_inx) new_voucher.find('select option:eq('+opt_inx+')').attr('disabled', true);	
}

function global_calculate_orders(ddObj, url){	
	/*
	ddObj has 2 value [object , boolean]
	*/	
	var isDD = Boolean(typeof ddObj == 'object');
	if (isDD){	/*check voucher amount over the before_cal_voucher*/
		var jObjSel = $("select[name='orders_voucher_code[]']");
		var sumVoucherValue = 0;
		var chkDup = false;
		jObjSel.each(function(i, domObj){
			sumVoucherValue += cv2num($.trim($(this).children('option:selected').text().split(' [').shift().split(' ').pop()));	
			//check duplicate
			var selfId = cv2num($(ddObj).attr('id').split('_').pop());
			if (cv2num($(ddObj).val()) && $(ddObj).val() == $(domObj).val() && selfId != i) chkDup = true; 
		});
		if (chkDup){
			alert('คูปองใบนี้ถูกเลือกแล้วค่ะ');
			$(ddObj).val(0);					
		} else {
			sumVoucherValue -= cv2num($.trim($(ddObj).children('option:selected').text().split(' [').shift().split(' ').pop()));
			if (sumVoucherValue > cv2num($('#div_grand_total_before_cal_voucher').text()) && ! cv2num($('#div_grand_total').text())){
				alert('จำนวนเงินเพียงพอสำหรับยอดที่ต้องชำระแล้วค่ะ');
				$(ddObj).val(0);		
			}
		}
	}
	//---toggle disable submit
	$('#bt_confirm_order').attr('disabled', true);
	//---
	if ( typeof url == 'undefined' ) url = 'orders_process.php';
	var url_goto = PREFIX_FF+url+'?action='+(ddObj == true ? 'load_form' : 'load_cart');
	call_submit(url_goto, function(msg){ 
		var section = (ddObj == true ? $('#div_cart') : $('#td_cart_list'));
		section.html(msg);
		section.unblock();			
		//check value before display payment method		
		check_payment_method();
		if ( $('#txt_point_used').exists() ){
			var txt = $('#txt_point_used');
			var point = Math.floor( ( txt.metadata().total_cal_point - $('#txt_point_used_value').val() ) / txt.metadata().point_rate );
			cal_point_external_plus(null, point);
		}
		//---toggle disable submit
		$('#bt_confirm_order').attr('disabled', false);
		//---
	}, false, function(){
		if (ddObj == true){
			block();
		} else {
			block();
			//$('#td_cart_list').block({ message: loading_img });
		}
	});	
}

function check_payment_method(){
	var cv2bool =  ! Boolean(parseFloat($('#div_grand_total').text()));
	if ($('#orders_payment_method:visible').length) $('#orders_payment_method').attr('disabled', cv2bool);
	if ($('#orders_pod_method:visible').length) $('#orders_pod_method').attr('disabled', cv2bool);			
}

function global_orders_success_save(isRedeem){
	var isRedeem = (typeof isRedeem != 'undefined' && isRedeem == 'redeem');
	var url_goto = PREFIX_FF+( ! isRedeem ? 'orders_process.php' : 'exchange_point_orders_process.php');
//	$('#bt_confirm_order').parent().block(emergency_block);		//no click again
	call_submitValidate(url_goto, function(msg){
//		$('#bt_confirm_order').parent().unblock();				
		var grand_total = parseFloat($('#div_grand_total').text());
		var orders_send_address01 = ( $('#orders_send_address01:checked').exists() || isRedeem );
		var orders_payment_method = '';										   
		if (msg.status == 1){
			$('#bt_confirm_order').parent().block(emergency_block);		//no click again
			if ( ! grand_total){
				if ( ! isRedeem)
					orders_payment_method = 'members_orders_history.php';
				else
					orders_payment_method = 'exchange_point_orders_thank.php';
			} else {
				if (orders_send_address01){
					$('#div_orders_check').html(msg.content);
					switch ($('#orders_payment_method').val()){
						case 'bkkb_ipay':
							$('#bt_ipay_submit').click();
							return false;
						case 'paysbuy':
							$('#bt_orders_submit').click();
							return false;
						case 'atm':
							orders_payment_method = 'orders_atm.php';
							break;
						case 'bank':
							orders_payment_method = 'orders_bank_counter.php';
							break;
						case 'internetbank':
							orders_payment_method = 'orders_internet_banking.php';
							break;
					}
				} else {						
					orders_payment_method = 'orders_pod_thank.php';
				}		
			}
			goto(PREFIX_FF+orders_payment_method);
		} else {
			$('#div_orders_check').html(msg.content);
			goToByScroll('div_orders_check');
			if (msg.status == -1) setTimeout("goto('index.php');", 20000);		/*status = -1 is session expired*/
		}		
	}, true, function(){		//---before submit confirm order again 
		var ans = confirm($('#span_msgcfsm').text());
		if ( ans ) block();
		return Boolean(ans);
	});
}

/***from order view***/
function global_payment_save(orders_web_type){
	var url_goto = PREFIX_FF+(orders_web_type != 2 ? 'orders_process.php' : 'exchange_point_orders_process.php');
	var orders_payment_method = $('#orders_payment_method').val();
	call_submit(url_goto, function(msg){
		var orders_id = $('#orders_id').val();
		var grand_total = parseFloat($('#grand_total').val());
		if ( cv2num(msg.status) ){
			$('#bt_confirm_order').parent().block(emergency_block);		//no click again
			if ( ! grand_total){
				if ( orders_web_type != 2 )
					orders_payment_method = 'members_orders_history.php';
				else
					orders_payment_method = 'exchange_point_orders_thank.php';
			} else {
				$('#div_orders_check').html(msg.content);
				switch ($('#orders_payment_method').val()){
					case 'bkkb_ipay':
						$('#bt_ipay_submit').click();
						return false;
					case 'paysbuy':
						$('#bt_orders_submit').click();
						return false;
					case 'atm':
						orders_payment_method = 'orders_atm.php';
						break;
					case 'bank':
						orders_payment_method = 'orders_bank_counter.php';
						break;
					case 'internetbank':
						orders_payment_method = 'orders_internet_banking.php';
						break;
				}
			}
			goto(PREFIX_FF+orders_payment_method+( orders_id ? ( '?orders_id='+orders_id ) : '' ));
		}
	}, true);
}

function global_members_login(){
	$('#div_members_login').html('');
	var url_goto = PREFIX_FF+'members_login.php';	
	$('#frm_login').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		dataType: 'json',
		success: function(msg){
			if ( cv2num(msg.status) ){
				goto(msg.content);
				return;
			}
			$('#div_members_login').html(msg.content);
		}
	});
}

function global_members_login_order(gotoUrl){	
	var url = PREFIX_FF+'members_login.php';	
	call_submitValidate(url, function(msg){
		if ( ! cv2num(msg.status) ){
			$('#div_members_login_form').html(msg.content);
			return;
		}		
		var obj = $('#hdnchkcv2sales');
		if ( obj.length ){
			url = 'cart_calculate_preorder.php'+( obj.val() ? ( '?'+obj.val() ) : '' );
			$.get(url, {mode:'process'}, function(msg){
				goto(gotoUrl);
			});			
		} else {
			goto(gotoUrl);
		}
	}, true);
}

function display_out_of_stock(obj, mainId, expressQty){
	var selfInx = obj.selectedIndex;
	obj = $(obj);
	$('#hdn_choose_id_'+mainId).val(obj.val());
	if ( typeof expressQty != 'undefined' && expressQty ) $('#get_order_quantity_'+mainId).attr('name', 'get_order_quantity_'+obj.val());
	var qty = cv2num(obj.children('option:selected').metadata().qty);
	var reserve = obj.children('option:selected').metadata().reserve;
	if ( typeof reserve == 'undefined' ) reserve = false;
	if (qty > 0 || reserve){
		$('#tr_'+mainId+' td:last').children('img:first').css('display', 'block');
		$('#tr_'+mainId+' td:last').children('img:last').css('display', 'none');
		$('#tr_'+mainId+' div.selqty').children('select').val(1);
		$('#tr_'+mainId+' div.selqty').css('display', 'block');
	} else {
		$('#tr_'+mainId+' td:last').children('img:first').css('display', 'none');
		$('#tr_'+mainId+' td:last').children('img:last').css('display', 'block');			
		$('#tr_'+mainId+' div.selqty').css('display', 'none');		
	}
}

function global_products_search(action){
	var url_goto = 'proc_ajax_center.php?action='+action;
	$('#searchform').ajaxSubmit({
		url : url_goto,
		success: function(msg){
			goto(PREFIX_FF+'products_search.php');
		}
	});	
}

function global_product_comment_em(em){	
	document.getElementById('procom_comment').value = document.getElementById('procom_comment').value+em;
}

function global_product_comment_save(act, act_2){
	var url = 'proc_ajax_center.php?action='+escape(act);
	call_submitValidate(url, function(msg){
		$('#div_product_comment').html(msg);
		call_getProc({ action: act_2, mode: 'list' }, '#div_comment_list');
	});
}

function global_product_comment_advise_del(obj){
	var alert_msg = $('#procom_advise_del_alert'+obj.procom_id).val();
	call_getProc(obj, function(msg){
		alert(alert_msg);
	});
}

function global_product_comment_star(objVal){
	var arr = ['', 'one', 'two', 'three', 'four', 'five'];
	$('.starvote').hide();
	$('#div_start_'+arr[objVal]).show();
}

function global_members_introduce(qWord, validateMode){
	var url = PREFIX_FF+'members_introduce_process.php?action='+qWord;
	var submitMode = ( typeof validateMode == 'undefined' || ! validateMode ? call_submit : call_submitValidate );
	submitMode(url, function(msg){
		var div_section = ( msg.status == 0 ? 'div_error' : 'div_introduce' );
		$('#'+div_section).html(msg.content);
		goToByScroll(div_section);
	}, true);	
}

function global_reject_orders(orders_id){	
	if ( ! confirm("คุณยืนยันที่จะยกเลิกใบสั่งซื้อนี้ใช่หรือไม่ ?") ) return;
	call_get('orders', 'reject', ( '&orders_id='+orders_id ), null);
}

/***************************************************/
/***************************************************/
/***************************************************/

// Start >>>>>>>>>>>>>> members_privilege.php 
// แลกมะกอก
$(function(){
	//OlEx
	$('a img#OlExchange').click(function(){
			$.fancybox({
					href:'members_ol_ex.php',
					type:'ajax',
					autoScale:false,
					centerOnScroll:true,
					margin:100,
					onComplete:function(){
						$("#progressbar").progressbar({ value: 0 });
						var intervalID = setInterval(updateProgress, 250);
						var myjson=$.parseJSON($('#OlExJson').val());
						if(myjson!=null){
							if(myjson.length==1){
								$('#nav_left').hide();
								$('#TbNavL').remove();
								$('#nav_right').hide();
								$('#TbNavR').remove();
								$('#TbContent').removeAttr('width');
								$('#TbOlEx').attr('width','100%');
							}
							$.get('members_ol_ex_process.php',{prem_id:myjson[0],action:'ExShow'},function(html){
								$('#OlExPre').html(html);
								$('table.box_sbdetail').attr('width','100%');
								$("#progressbar").progressbar({'value':100});
								clearInterval(intervalID);
								$("#progressbar").fadeOut(500);//$("#progressbar").fadeOut(500,function(){$(this).remove()});
							});
						};
					},
					onStart:function(){document.body.style.overflow='hidden';document.getElementsByTagName("html")[0].style.overflow = "hidden";},
					onClosed:function(){document.body.style.overflow='auto';document.getElementsByTagName("html")[0].style.overflow = "auto";}
			});
		}
		
	);
	
	function updateProgress(){
		var value = $("#progressbar").progressbar("option", "value");
		if (value < 100) {
			$("#progressbar").progressbar("value", value + 1);               
		}
	}
	
	jQuery.extend({
		nav_left:function(){
				$("#progressbar").show();
				$("#progressbar").progressbar({ value: 0 });
				var intervalID = setInterval(updateProgress, 250);
				$('#OlExPre').empty();
				var myjson=$.parseJSON($('#OlExJson').val());
				var corrent=parseInt($('#OlExCurrent').val());
				var key=corrent-1;
				if(key<=0){
					$('#nav_left').hide();
					$('#nav_right').show();
				}else{
					$('#nav_left').show();
					$('#nav_right').show();
				}
				$('#OlExCurrent').val(key)
				$.get('members_ol_ex_process.php',{prem_id:myjson[key],action:'ExShow'},function(html){
					$('#OlExPre').html(html);
					$('table.box_sbdetail').attr('width','100%');
					$("#progressbar").progressbar({'value':100});
					$("#progressbar").fadeOut(500);
				});
			},
		nav_right:function(){
				$("#progressbar").show();
				$("#progressbar").progressbar({ value: 0 });
				var intervalID = setInterval(updateProgress, 250);
				$('#OlExPre').empty();
				var myjson=$.parseJSON($('#OlExJson').val());
				var corrent=parseInt($('#OlExCurrent').val());
				var key=corrent+1;
				if(key>=(myjson.length-1)){
					$('#nav_right').hide();
					$('#nav_left').show();
				}else{
					$('#nav_right').show();
					$('#nav_left').show();
				}
				$('#OlExCurrent').val(key)
				$.get('members_ol_ex_process.php',{prem_id:myjson[key],action:'ExShow'},function(html){
					$('#OlExPre').html(html);
					$('table.box_sbdetail').attr('width','100%');
					$("#progressbar").progressbar({'value':100});
					$("#progressbar").fadeOut(500);
				});
			}
	});
	//OlEx
})
// End >>>>>>>>>>>>>> members_privilege.php
























































function global_ajax_submit(saveForm,url1,url2){
	$('#'+saveForm).ajaxSubmit({
		url : url1,
		beforeSubmit: block,
		clearForm: true,
		success: function(msg){
			if(url2){
				window.location = url2;
			}
		}
	});
}


function global_ajax_submit_noneblock_magazine(saveForm,url1,url2,blank){
	$('#'+saveForm).ajaxSubmit({
		url : url1,
		clearForm: true,
		success: function(msg){
			if(url2 && !blank){
				window.location = url2 ;
			}else{
				if(typeof chk == 'undefined' || chk.closed || !chk.open){
					chk = window.open(url2,'_blank') ;
				}else{
					chk.location= url2 ;
					chk.focus() ;	
				}
			}
		}
	});
}

function global_ajax_submit_noneblock(saveForm,url1,url2, noOpenUrl2){
	$('#'+saveForm).ajaxSubmit({
		url : url1,
		clearForm: true,
		success: function(msg){
			if(url2){
				if(typeof chk == 'undefined' || chk.closed || !chk.open){
					if ( typeof noOpenUrl2 == 'undefined' || ! noOpenUrl2 ) chk = window.open(url2,'_blank') ;
				}else{
					chk.location= url2 ;
					chk.focus() ;	
				}
				/*window.location = url2;*/
			}
		}
	});
}


function global_ajax_submit_validate(saveForm,url1,url2){	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#"+saveForm).validate({
    	    meta: "validate",
            submitHandler: function(form) {	
			
				$('#'+saveForm).ajaxSubmit({
					url : url1,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						
						if(url2){
							window.location = url2;
						}
						
					}
				});
				
            }
       });	
}


function global_icon_input_em(obj_name, em){	
	document.getElementById(obj_name).value = document.getElementById(obj_name).value+em;
}


function getUrl(url_go,members_mkt_update) {
	if(members_mkt_update=='N'){
		if(confirm("ขออภัยค่ะ คุณไม่สามารถสั่งซื้อสินค้าได้ค่ะ เนื่องจากคุณยังไม่ได้สมัครสมาชิกทางเว็บไซต์ \nหากต้องการสมัคร กดปุ่ม OK ค่ะ")==true){
			window.location = 'members_register.php' ;
			return false ;
		}
		return false;
	}
	block();
	window.location = url_go;
}

function global_submit_msg(submit_form, url_goto, div_msg, clear_form){
	$('#'+submit_form).ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: clear_form,
		success: function(msg){
			$('#'+div_msg).html(msg);			
		}
	});
}

function check_email_format(check_email){
	var apos = check_email.indexOf("@");
	var dotpos = check_email.lastIndexOf(".");
	if((apos < 1) || (dotpos-apos<2)){
		return 0;
	}else{
		return 1;
	}
}

function global_members_switch(objForm,objDiv,objVal){
	
	if(objVal){
		url_goto = 'members_register_switch.php?members_dhc='+objVal+'&objdiv='+objDiv;
	}else{
		url_goto = 'members_register_switch.php?objdiv='+objDiv;
	}
	$('#'+objForm).ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			
			$('#'+objDiv).html(msg);
			ttip();
		}
	});
}

function check_username(object_value){
	$('#myform').ajaxSubmit({
		url : 'members_check_username.php?members_username='+object_value,
		clearForm: false,
		success: function(msg){
			$('#username_div').html(msg);
		}
	});
}

// --------------------------- BEGIN : แสดงขื่อ-นามสกุลที่ Billing Name ------------------
function global_name_show_billing(){
	//document.getElementById('members_billing_name').value = document.getElementById('members_name_th').value;
	$('#members_billing_name').val($('#members_name_th').val());
}

function global_surname_show_billing(){
	var members_name_th = document.getElementById('members_name_th');
	var members_surname_th = document.getElementById('members_surname_th');
	if(members_name_th.value == ''){
		alert('กรุณากรอก ชื่อ(ภาษาไทย) ก่อนค่ะ [Please input Name(Thai) before input this point.]');
		members_surname_th.value = '';
		members_name_th.focus();
		return false;
	}else{
		//document.getElementById('members_billing_name').value = document.getElementById('members_name_th').value+'  '+document.getElementById('members_surname_th').value;
		$('#mmembers_billing_name').val($('#mmembers_name_th').val+'  '+$('#mmembers_surname_th').val());
	}
}
// --------------------------- END : แสดงชื่อ-นามสกุลที่ Billing Name --------------------


// --------------------------- BEGIN : Fix members colde ----------------------------

function global_members_code_key(){
	var members_code = document.getElementById("members_code").value;
	if(members_code == ""){
		jQuery(function($){
			$("#members_code").mask("999999999");
		});
	}
}

// --------------------------- END : Fix members colde ------------------------------

// --------------------------- BEGIN : Fix members ID Card --------------------------

function global_members_id_card_key(){
	var members_id_no = document.getElementById("members_id_no").value;
	if(members_id_no == ""){
		jQuery(function($){
			$("#members_id_no").mask("9999999999999");
		});
	}
}

// --------------------------- END : Fix members ID Card ----------------------------

function global_members_register(objForm,objUrl1,objUrl2,objDiv){
	jQuery.validator.messages.required = "";
	jQuery.validator.messages.minlength = "";
	jQuery.validator.messages.maxlength = "";
	jQuery.validator.messages.email = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#"+objForm).validate({
			/*rules: {
				members_username: { required: true, minlength: 4, username: true  },
				members_password: { required: true, minlength: 4 },
				members_name_th: { 
					required: true, 
					thai_only: function(){ 
						return Boolean($('#members_id_type01:checked').length); 
					}
				},
				members_surname_th: { 
					required: true, 
					thai_only: function(){ 
						return Boolean($('#members_id_type01:checked').length); 
					}
				},
				
				members_name_eng: { required: true, eng_only: true },
				members_surname_eng: { required: true, eng_only: true },
				members_shipping_no: 'required',
				members_shipping_road: 'required',
				members_shipping_zipcode: 'required',
				members_shipping_mobile: { required: true, num_only:true, minlength:10 },
				members_shipping_email: 'required',
				members_billing_name: 'required',
				members_billing_no: 'required',
				members_billing_road: 'required',
				members_billing_zipcode: 'required',
				members_billing_mobile: { required: true, num_only:true, minlength:10 },
				members_permanent_no: 'required',
				members_permanent_road: 'required',
				members_permanent_zipcode: 'required',
				members_permanent_tel: 'required'		
			},*/	
	    	meta: "validate",
            submitHandler: function(form) {
				var members_shipping_email = document.getElementById('members_shipping_email').value;
				if(check_email_format(members_shipping_email) == 0){
					document.getElementById('members_check_email').value = 'INCORRECT';
				}else{
					document.getElementById('members_check_email').value = '';
				}
				$('#'+objForm).ajaxSubmit({
					url : objUrl1,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						if(objUrl2){
							$('#div_members_check').html(msg);
							if(document.getElementById('check_success').value == 'success'){
								/*window.location = objUrl2;*/
							}else{
								if(document.getElementById('check_success').value == 'exist_center_members'){
									document.getElementById('div_button_signup').style.display = 'none';
									document.getElementById('div_button_sigup_confirm').style.display = '';
								}else{
									document.getElementById('div_button_signup').style.display = '';
									document.getElementById('div_button_sigup_confirm').style.display = 'none';
								}
								//$('#div_members_email_incorrect').html(msg);
								$('#dialog_err').remove();
								$('<div>',{
										id:'dialog_err',
										title:'ผิดพลาด!',
										html:msg
									}).dialog({
										draggable:false,
										resizable:false,
										modal:true,
										width:650/*,
										'open':function(){$('body,html').css('overflow','hidden');},
										'close':function(){$('body,html').css('overflow','auto');}*/
									});
							}
							
						}else{
							$('#div_members_check').html(msg);
							if($('#check_success').val() == 'success'){
								$('#div_dhcContent').html(msg);
								//top.location = '#';
							/*	timer = setTimeout('global_after_members_register()',10000);*/
							}else{
								if($('#check_success').val() == 'exist_center_members'){
									$('#div_button_signup').css('display','none');
									$('#div_button_sigup_confirm').css('display','');
								}else{
									$('#div_button_signup').css('display','');
									$('#div_button_sigup_confirm').css('display','none');
								}
								//$('#div_members_email_incorrect').html(msg);
								$('#dialog_err').remove();
								$('<div>',{
										id:'dialog_err',
										title:'ผิดพลาด!',
										html:msg
									}).dialog({
										'open':function(){$('body,html').css('overflow','hidden');},
										'close':function(){$('body,html').css('overflow','auto');},
										draggable:false,
										resizable:false,
										modal:true,
										width:650,
										dialogClass:'memFixed',
										buttons:{
												'ติดต่อเว็บมาสเตอร์':function(){window.location='contact_us.php';},
												'ปิด':function(){$(this).dialog('close');}
										}
									});
									//return;
							}
							
							
						}
					}
				});
				
				
            }
        });
}








function global_members_register_after_check(objForm,objUrl1,objUrl2,objDiv){
	
	/*
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#"+objForm).validate({
    	    meta: "validate",
            submitHandler: function(form) {
	*/
				
				
				var members_shipping_email = document.getElementById('members_shipping_email').value;
				if(check_email_format(members_shipping_email) == 0){
					document.getElementById('members_check_email').value = 'INCORRECT';
				}else{
					document.getElementById('members_check_email').value = '';
				}
				
				$('#'+objForm).ajaxSubmit({
					url : objUrl1,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						
						
						if(objUrl2){
							$('#div_members_check').html(msg);
							if(document.getElementById('check_success').value == 'success'){
								/*window.location = objUrl2;*/
							}else{
								$('#div_members_email_incorrect').html(msg);
							}
						}else{
							$('#div_members_check').html(msg);
							
							
							if(document.getElementById('check_success').value == 'success'){
								$('#div_dhcContent').html(msg);
								top.location = '#';
								/*timer = setTimeout('global_after_members_register()',10000);*/
							}else{
								$('#div_members_email_incorrect').html(msg);
							}
							
							
						}
						
					}
				});
				
		
	
	/*
				
            }
        });
	*/
		
}






function global_after_members_register() {
	window.location = 'index.php'
}


function id_pass_onload(){
	document.getElementById('members_id_no').style.display = '';
	document.getElementById('members_id_no_02').style.display = 'none';
	document.getElementById('personal_id').style.display = '';
	document.getElementById('passport_id').style.display = 'none';
}
function id_passport(obj){
	if(obj.value == 'ID'){
		id_pass_onload();	
	}else{
		document.getElementById('members_id_no').style.display = 'none';
		document.getElementById('members_id_no_02').style.display = '';
		document.getElementById('personal_id').style.display = 'none';
		document.getElementById('passport_id').style.display = '';
	}
}

function members_call_calendar() {
	
	jQuery(function($){
		$("#members_birthday").attachDatepicker();
	});
}

function ShippingTobilling(obj){
	if(obj.checked == true){
		var province = document.getElementById('members_shipping_province').value;
		var amphur = document.getElementById('members_shipping_amphur').value;
		var district = document.getElementById('members_shipping_district').value;
		
		global_select_relation('members_billing_amphur','location_relation_process.php?action=amphur&province_id='+province+'&amphur_id='+amphur,'members_billing_amphur','','');
		global_select_relation('members_billing_district','location_relation_process.php?action=district&amphur_id='+amphur+'&district_id='+district,'members_billing_district','','');
		
		document.getElementById('members_billing_province').value = province;
		document.getElementById('members_billing_company').value = document.getElementById('members_shipping_company').value;
		document.getElementById('members_billing_no').value = document.getElementById('members_shipping_no').value;
		document.getElementById('members_billing_moo').value = document.getElementById('members_shipping_moo').value;
		document.getElementById('members_billing_placement').value = document.getElementById('members_shipping_placement').value;
		document.getElementById('members_billing_mooban').value = document.getElementById('members_shipping_mooban').value;
		document.getElementById('members_billing_soi').value = document.getElementById('members_shipping_soi').value;
		document.getElementById('members_billing_road').value = document.getElementById('members_shipping_road').value;
		document.getElementById('members_billing_zipcode').value = document.getElementById('members_shipping_zipcode').value;
		document.getElementById('members_billing_tel').value = document.getElementById('members_shipping_tel').value;
		document.getElementById('members_billing_mobile').value = document.getElementById('members_shipping_mobile').value;
		document.getElementById('members_billing_fax').value = document.getElementById('members_shipping_fax').value;
		
	}else{
		
		$("#members_billing_amphur").html('<option value="">' +$("#members_billing_amphur").attr("real")+ '</option>');
		$("#members_billing_district").html('<option value="">' +$("#members_billing_district").attr("real")+ '</option>');
		document.getElementById('members_billing_province').value = '';
		document.getElementById('members_billing_company').value = '';
		document.getElementById('members_billing_no').value = '';
		document.getElementById('members_billing_moo').value = '';
		document.getElementById('members_billing_placement').value = '0';
		document.getElementById('members_billing_mooban').value = '';
		document.getElementById('members_billing_soi').value = '';
		document.getElementById('members_billing_road').value = '';
		document.getElementById('members_billing_zipcode').value = '';
		document.getElementById('members_billing_tel').value = '';
		document.getElementById('members_billing_mobile').value = '';
		document.getElementById('members_billing_fax').value = '';
	}
}

function ShippingToPermanent(obj){
	if(obj.checked == true){
		var province = document.getElementById('members_shipping_province').value;
		var amphur = document.getElementById('members_shipping_amphur').value;
		var district = document.getElementById('members_shipping_district').value;
		
		global_select_relation('members_permanent_amphur','location_relation_process.php?action=amphur&province_id='+province+'&amphur_id='+amphur,'members_permanent_amphur','','');
		global_select_relation('members_permanent_district','location_relation_process.php?action=district&amphur_id='+amphur+'&district_id='+district,'members_permanent_district','','');
		
		document.getElementById('members_permanent_province').value = province;
		document.getElementById('members_permanent_no').value = document.getElementById('members_shipping_no').value;
		document.getElementById('members_permanent_moo').value = document.getElementById('members_shipping_moo').value;
		document.getElementById('members_permanent_soi').value = document.getElementById('members_shipping_soi').value;
		document.getElementById('members_permanent_road').value = document.getElementById('members_shipping_road').value;
		document.getElementById('members_permanent_zipcode').value = document.getElementById('members_shipping_zipcode').value;
		document.getElementById('members_permanent_tel').value = document.getElementById('members_shipping_tel').value;
		
	}else{
		
		$("#members_permanent_amphur").html('<option value="">' +$("#members_permanent_amphur").attr("real")+ '</option>');
		$("#members_permanent_district").html('<option value="">' +$("#members_permanent_district").attr("real")+ '</option>');
		document.getElementById('members_permanent_province').value = '';
		document.getElementById('members_permanent_no').value = '';
		document.getElementById('members_permanent_moo').value = '';
		document.getElementById('members_permanent_soi').value = '';
		document.getElementById('members_permanent_road').value = '';
		document.getElementById('members_permanent_zipcode').value = '';
		document.getElementById('members_permanent_tel').value = '';
	}
}

function global_zipcode(obj,div_obj,url_goto){
	$('#myform').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){
			$('#'+div_obj).html(msg);
			document.getElementById(obj).value = document.getElementById(div_obj).innerHTML;
		}
	});
}


function global_sub_promotion(product_id, obj, url){
	
	var x;
	var check_val = 0;
	var my_split = new Array();
	var spro_id_check = $('#spro_id_check').val();
	
	my_split = spro_id_check.split(',');
	
	for (x=0;x<my_split.length;x++){
		
		if(document.getElementById('sub_product_code_'+my_split[x]).value == ''){
			check_val = 1;
		}
	}
	
	
	if(check_val == 1){
		$('#myform').ajaxSubmit({
			url : 'cart_promotion_check.php?action_check=promotion',
			beforeSubmit: block,
			clearForm: false,
			success: function(msg){
				$('#div_promotion_check').html(msg);
			}
		});
	
	}else{
		$('#div_promotion_check').html('');
		add_to_cart(product_id, obj, url);
	}
}







// --------------------- DHC Supplement Activity promotion 25 ก.ค. - 10 ก.ย. 2552 หลังจากนี้ให้ลบทิ้ง ------------------------
function global_dhc_supplement_activiti_alert_before_add(product_id, obj, url, discount_percent){
	alert('ทางบริษัท ดีเอชซี (ประเทศไทย) จำกัด ได้จัดโปรโมชั่น Healthy in Style "ช้อปสินค้าถูกใจตามสไตล์คุณ" ในกลุ่มสินค้า DHC Supplement\nตั้งแต่วันที่ 25 กรกฎาคม ถึง 10 กันยายน 2552\n\n\t*** เพียงซื้อผลิตภัณฑ์อาหารเสริม DHC Supplement ใดๆ 3 ชิ้น (ซ้ำกันได้ 2 ชิ้น) รับส่วนลดทันที '+discount_percent+'% จากราคาปกติ (1 สิทธิ์ต่อ 1 ใบสั่งซื้อ)\n\t*** การคำนวณส่วนลด '+discount_percent+'% จากราคาปกติทางเว็บไซต์นั้น จะให้ความสำคัญกับสำดับการเก็บสินค้าใส่ในตะกร้า กล่าวคือ จะนำสินค้า DHC Supplement ลำดับแรกไปคำนวณส่วนลดก่อนจากนั้นจึงนำสินค้าลำดับถัดไปมาคำนวณส่วนลดตามลำดับไป นะคะ');
	add_to_cart(product_id, obj, url);
}
// --------------------- DHC Supplement Activity promotion 25 ก.ค. - 10 ก.ย. 2552 หลังจากนี้ให้ลบทิ้ง ------------------------


// -------------------- DHC Tisco promotion discount 15% and 20% หลังจากโปรโมชั่นลบทิ้งได้เลย ----------------------------------
function add_to_cart_tisco(product_id, obj, url){
	var go_url = url+'&product_id='+product_id+'&quantity='+document.getElementById(obj).value;
	$('#myform').ajaxSubmit({
		url : go_url,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_cart').html(msg);
			document.getElementById(obj).value = 1;
		}
	});
}
// -------------------- DHC Tisco promotion discount 15% and 20% หลังจากโปรโมชั่นลบทิ้งได้เลย ----------------------------------




function delete_to_cart(url){

	$('#myform').ajaxSubmit({
		url : url,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
		
			$('#div_cart').html(msg);
			//***for birthday
			if ($('#hdnhasbd').length){
				$('.div_bd:first').show();
				$('.div_bd:last').hide();
			}			
			//***
			//***for web game special dc [2010-03-10]
			var obj_spdc = $('#hdnhasspdc');
			if (obj_spdc.length){
				var avail = $('#hdnhasspdc').val().split(',');
				if (avail[0] != ''){
					$('.div_spdc:even').hide();
					$('.div_spdc:odd').show();
					$.each(avail, function(i, val){
						$('.div_spdc:eq('+(val * 2)+')').show().next().hide();
					});
				}			
			}
			//***			
			/***for exchange_point module (shared function)***/
			if ($('.orcpoint').length){
				$('#div_section_point span:first').text($('.orcpoint:first').val());
				$('#div_section_point span:last').text($('.orcpoint:last').val());			
			}
/*			if(document.getElementById('check_files_8716').value == 'products_8716_oc02.php'){

			}
*/			
		}
	});
}

function global_top_view(product_id){
	
	var url_goto = 'products_view_count.php?product_id='+product_id;
	$('#header_form').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){			
		}
	});
}


function global_goto_comment(product_id){
	
	var url_goto = 'products_proccess.php?cond_action=set_session&product_id='+product_id;
	$('#myform').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){
			window.location = 'products_comment.php';
		}
	});
	
}


function global_product_comment(product_id){
	var url_goto = 'products_proccess.php?cond_action=add_comment&product_id='+product_id;
	$('#myform').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){		
			$('#div_product_comment').html(msg);
		}
	});
}

function global_product_comment_refresh(){
	$('#myform').ajaxSubmit({
		url : 'products_proccess.php?cond_action=refresh',
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_comment_list').html(msg);
		}
	});
}


function global_product_comment_cancel(){
	
	var url_goto = 'products_proccess.php?cond_action=cancel';
	$('#myform').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){		
			$('#div_product_comment').html(msg);
		}
	});
	
}

function global_forgot_password(){
	var members_email = document.getElementById('members_email').value;
	if(check_email_format(members_email) == 0){
		url_goto = 'forgot_password_process.php?check_email=FALSE';
	}else{
		url_goto = 'forgot_password_process.php';
	}
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#messagebox').html(msg);
			if(document.getElementById('check_return').value == 'success'){
				document.getElementById('members_email').value = '';
			}
		}
	});
}



// ------------------------------------ BEGIN : Order Step --------------------------------------------------------

function global_voucher_code_key(){
	var orders_gift_voucher_code = document.getElementById("orders_gift_voucher_code").value;
	if(orders_gift_voucher_code == ""){
		jQuery(function($){
			$("#orders_gift_voucher_code").mask("9999999");
		});
	}
}

function global_calculate_orders_sample(total_sample_value){
	var url_goto = 'orders_process.php?action_calculate=total_sample&total_sample_value='+total_sample_value;
	
	$('#myform').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){
			
			$('#div_orders_products_sample').html(msg);
			
		}
	});
	
}

function global_orders_finish(){
	var url_goto = 'orders_process.php?action_finish=TRUE';
	$('#myform').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){
			window.location = 'members_orders_history.php';
		}
	});
}

// ------------------------------------ END : Order Step --------------------------------------------------------

function global_add_qa_topics(qacat2_id){
	$('#myform').ajaxSubmit({
		url : 'qa_process.php?action=add_topics&qacat2_id='+qacat2_id,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_add_topics').html(msg);
		}
	});
}

function global_qa_input_em(em){	
	document.getElementById('qa_detail').value = document.getElementById('qa_detail').value+em;
}


function global_qa_clear(qacat2_id){	
	document.getElementById('action').value = 'topic_cancel';	
	$('#myform').ajaxSubmit({
		url : 'qa_process.php?qacat2_id='+qacat2_id,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_add_topics').html(msg);
		}
	});
	
}

function private_refresh_topics_list(qacat2_id){
	$('#myform').ajaxSubmit({
		url : 'qa_process.php?action=refresh_topics&qacat2_id='+qacat2_id,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_topics_list').html(msg);
		}
	});
}

function global_qa_save(){
	//var qacat2_id = document.getElementById('qacat2_id').value;
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : 'qa_process.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_add_topics').html(msg);
						//private_refresh_topics_list(qacat2_id);
					}
				});
				
            }
        });
}


function global_add_question(qacat2_id, qa_id){
	$('#myform').ajaxSubmit({
		url : 'qa_process.php?action=add_question&qacat2_id='+qacat2_id+'&qa_id='+qa_id,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_add_question').html(msg);
		}
	});
}

function global_question_clear(qacat2_id, qa_id){
	//document.getElementById('qa_detail').value = '';
	document.getElementById('action').value = 'question_cancel';	
	$('#myform').ajaxSubmit({
		url : 'qa_process.php?qacat2_id='+qacat2_id+'&qa_id='+qa_id,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_add_question').html(msg);
		}
	});
}

function global_question_save(){
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : 'qa_process.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_add_question').html(msg);
					}
				});
				
            }
        });
}

function global_careers_apply(position_id){
	$('#myform').ajaxSubmit({
		url : 'careers_process.php?position_id='+position_id,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_careers').html(msg);
			top.location = '#';
		}
	});
}

function global_careers_cancel(){
	document.getElementById('action').value = 'cancel';
	$('#myform').ajaxSubmit({
		url : 'careers_process.php',
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_careers').html(msg);
			top.location = '#';
		}
	});
}



function global_careers_apply_save(){
	/*
	var check_val = 0;
	var applyer_name = document.getElementById('applyer_name');
	var applyer_nikename = document.getElementById('applyer_nikename');
	
	if(applyer_name.value == ''){
		applyer_name.style.backgroundColor = '#FFCCCC';
		applyer_name.focus();
		check_val = 1;
	}
	
	if(applyer_nikename.value == ''){
		applyer_nikename.backgroundColor = '#FFCCCC';
		check_val = 1;
	}
	
	if(check_val == 1){
		return false;	
	}
	*/


	/*
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {	
			
				
				
				$('#myform').ajaxSubmit({
					
					url : 'careers_process.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_careers').html(msg);
						top.location = '#';
						//window.location = 'careers.php';
					}
					
				});
				
				
				
            }
       });
	*/
	var applyer_name = document.getElementById('applyer_name');
	var applyer_name_alert = $("#applyer_name").attr("real");
	var applyer_nikename = document.getElementById('applyer_nikename');
	var applyer_nikename_alert = $("#applyer_nikename").attr("real");
	var applyer_height = document.getElementById('applyer_height');
	var applyer_height_alert = $("#applyer_height").attr("real");
	var applyer_weight = document.getElementById('applyer_weight');
	var applyer_weight_alert = $("#applyer_weight").attr("real");
	var applyer_domicile_address = document.getElementById('applyer_domicile_address');
	var applyer_domicile_address_alert = $("#applyer_domicile_address").attr("real");
	var applyer_birthday = document.getElementById('applyer_birthday');
	var applyer_birthday_alert = $("#applyer_birthday").attr("real");
	var applyer_religion = document.getElementById('applyer_religion');
	var applyer_religion_alert = $("#applyer_religion").attr("real");
	var applyer_nationality = document.getElementById('applyer_nationality');
	var applyer_nationality_alert = $("#applyer_nationality").attr("real");
	var applyer_origin = document.getElementById('applyer_origin');
	var applyer_origin_alert = $("#applyer_origin").attr("real");
	var applyer_current_address = document.getElementById('applyer_current_address');
	var applyer_current_address_alert = $("#applyer_current_address").attr("real");
	var applyer_tel = document.getElementById('applyer_tel');
	var applyer_tel_alert = $("#applyer_tel").attr("real");
	var applyer_email = document.getElementById('applyer_email');
	var applyer_email_alert = $("#applyer_email").attr("real");
	var applyer_email_incorrect_alert = $("#applyer_email_incorrect").attr("real");
	var applyer_start_date = document.getElementById('applyer_start_date');
	var applyer_start_date_alert = $("#applyer_start_date").attr("real");
	
	if(applyer_name.value == ''){
		alert(applyer_name_alert);
		applyer_name.focus();
		return false;
	}
	if(applyer_nikename.value == ''){
		alert(applyer_nikename_alert);
		applyer_nikename.focus();
		return false;
	}
	if(applyer_height.value == ''){
		alert(applyer_height_alert);
		applyer_height.focus();
		return false;
	}
	if(applyer_weight.value == ''){
		alert(applyer_weight_alert);
		applyer_weight.focus();
		return false;
	}
	if(applyer_domicile_address.value == ''){
		alert(applyer_domicile_address_alert);
		applyer_domicile_address.focus();
		return false;
	}
	if(applyer_birthday.value == ''){
		alert(applyer_birthday_alert);
		applyer_birthday.focus();
		return false;
	}
	if(applyer_religion.value == ''){
		alert(applyer_religion_alert);
		applyer_religion.focus();
		return false;
	}
	if(applyer_nationality.value == ''){
		alert(applyer_nationality_alert);
		applyer_nationality.focus();
		return false;
	}
	if(applyer_origin.value == ''){
		alert(applyer_origin_alert);
		applyer_origin.focus();
		return false;
	}
	if(applyer_current_address.value == ''){
		alert(applyer_current_address_alert);
		applyer_current_address.focus();
		return false;
	}
	if(applyer_tel.value == ''){
		alert(applyer_tel_alert);
		applyer_tel.focus();
		return false;
	}
	if(applyer_email.value == ''){
		alert(applyer_email_alert);
		applyer_email.focus();
		return false;
	}else{
		if(check_email_format(applyer_email.value) == 0){
			alert(applyer_email_incorrect_alert);
			applyer_email.focus();
			return false;
		}
	}
	if(applyer_start_date.value == ''){
		alert(applyer_start_date_alert);
		applyer_start_date.focus();
		return false;
	}
	
}


function global_call_calendar(obj_id){
	jQuery(function($){
		$("#"+obj_id).datepicker({changeYear:true,changeMonth:true});
	});
}

function global_open_panel(condition_val){//$('li.ui-tabs-selected').next().children('a').triggerHandler('click');return;
	if(condition_val == 1){
		document.getElementById('content_panel_01').style.display = '';
		document.getElementById('content_panel_02').style.display = 'none';
		document.getElementById('content_panel_03').style.display = 'none';
	}else if(condition_val == 2){
		document.getElementById('content_panel_01').style.display = 'none';
		document.getElementById('content_panel_02').style.display = '';
		document.getElementById('content_panel_03').style.display = 'none';
	}else if(condition_val == 3){
		document.getElementById('content_panel_01').style.display = 'none';
		document.getElementById('content_panel_02').style.display = 'none';
		document.getElementById('content_panel_03').style.display = '';
	}else{
		document.getElementById('content_panel_01').style.display = '';
		document.getElementById('content_panel_02').style.display = 'none';
		document.getElementById('content_panel_03').style.display = 'none';
	}
	top.location = '#';
}


function global_contact_send(){	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {	
			
				var contact_email = document.getElementById('contact_email').value;
				if(check_email_format(contact_email) == 0){
					document.getElementById('check_email').value = 'Y';
				}else{
					document.getElementById('check_email').value = '';
				}
			
				$('#myform').ajaxSubmit({
					url : 'contact_us_process.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_contact_err').html(msg);
						
						if(document.getElementById('contact_success').value == 'success'){
							document.getElementById('contact_name').value = '';
							document.getElementById('contact_email').value = '';
							document.getElementById('contact_subject').value = '';
							document.getElementById('contact_message').value = '';
							document.getElementById('check_email').value = '';
						}
					}
				});
				
            }
       });	
}

// ------------------------------ BEGIN : E-mail รับ-ไม่รับข่าวสาร DHC --------------------------------

function global_receive_email(){	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {	
			
				var dhcr_email_email = document.getElementById('dhcr_email_email').value;
				if(check_email_format(dhcr_email_email) == 0){
					document.getElementById('check_email').value = 'INCORRECT';
				}else{
					document.getElementById('check_email').value = 'CORRECT';
				}
			
				$('#myform').ajaxSubmit({
					url : 'dhc_receive_email_process.php?action=save_request',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_body').html(msg);
						if(document.getElementById('receive_success').value == 'success'){
							document.getElementById('dhcr_email_email').value = '';
							timer = setTimeout('global_receive_email_go()',6000);
						}
					}
				});
				
				
            }
       });	
}



function global_receive_email_go(){
	window.location='dhc_receive_email.php';
}


/*
function global_receive_email_status(url_process){		
	$('#myform').ajaxSubmit({
		url : url_process,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			global_receive_email_go();
		}
	});		
}
*/


// ------------------------------ END : E-mail รับ-ไม่รับข่าวสาร DHC ----------------------------------


function global_express_product(express_pro_id, product_id){
	document.getElementById('express_order_id_'+product_id).value = express_pro_id;	
}

function global_news(newscat_id){
	if(newscat_id != ''){
		goto_url = 	'news_process.php?newscat_id='+newscat_id
	}else{
		goto_url = 'news_process.php';
	}
	$('#myform').ajaxSubmit({
		url : goto_url,
		clearForm: false,
		success: function(msg){
			$('#div_news').html(msg);
		}
	});	
}

function global_activity_gallery(album_id){
	$('#myform').ajaxSubmit({
		url : 'news_process.php?album_id='+album_id+'&action=gallery',
		beforeSubmit: block,
		clearForm: true,
		success: function(msg){
			$('#div_news').html(msg);
		}
	});
}


// ------------------------- BEGIN : Members Join Games ---------------------------------------------
function global_members_join_games(){
	var url_goto = 'memberjoin_process.php';
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_memberjoin_games').html(msg);
			if(document.getElementById('games_success').value == 'success'){
				window.location='memberjoin_games.php';
			}
		}
	});
}

function global_members_join_login(){
	var url_goto = 'memberjoin_process.php';
	document.getElementById('action').value = 'login';
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : url_goto,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_memberjoin_games').html(msg);
						
						if(document.getElementById('check_login_success').value == 'success'){
							window.location = 'memberjoin_games.php';
						}
						
					}
				});
				
            }
        });
}

function global_members_join_play_games(){
	var url_goto = 'memberjoin_process.php?action=play_games';
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_memberjoin_games').html(msg);
		}
	});
}

function global_members_join_cancel_games(){
	var url_goto = 'memberjoin_process.php?action=cancel_games';
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_memberjoin_games').html(msg);
		}
	});
}

function global_members_join_check_submit(){
	var joingame_reason_love = document.getElementById('joingame_reason_love');
	var joingame_img = document.getElementById('joingame_img');
	
	if(joingame_img.value == ''){
		alert($("#joingame_img").attr("real"));
		joingame_img.focus();
		return false;
	}
	
	if(joingame_reason_love.value == ''){
		alert($("#joingame_reason_love").attr("real"));	
		joingame_reason_love.focus();
		return false;
	}
}

function global_em(em,obj){	
	document.getElementById(obj).value = document.getElementById(obj).value+em;
}

function global_members_join_games_detail(joingame_id){
	var url_goto = 'memberjoin_process.php?joingame_id='+joingame_id+'&action=goto_detail';
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			window.location = 'memberjoin_games_detail.php';
		}
	});
}

// ------------------------- END : Members Join Games -----------------------------------------------




// ------------------------- BEGIN : Members Email Games --------------------------------------------

function global_members_email_games(){
	var url_goto = 'members_email_games_process.php';
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_members_email_games').html(msg);
			if(document.getElementById('games_success').value == 'success'){
				window.location='members_email_games_send.php';
			}
		}
	});
}

function global_members_email_games_login(){
	var url_goto = 'members_email_games_process.php?action=login';
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : url_goto,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_members_email_games').html(msg);
						
						if(document.getElementById('check_login_success').value == 'success'){
							window.location = 'members_email_games.php';
						}
						
					}
				});
				
            }
        });
}

function global_members_email_games_add(){
	
	var url_goto = 'members_email_games_process.php?action=add';
	var emailgame_friends_email = document.getElementById('emailgame_friends_email');
	
	if(check_email_format(emailgame_friends_email.value) == 0){
		document.getElementById('email_incorrect').value = 'Y';
	}else{
		document.getElementById('email_incorrect').value = 'N';
	}
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {
				
				
				$('#myform').ajaxSubmit({
					url : url_goto,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_email_games_send').html(msg);
						
						if(document.getElementById('check_success').value == 'success'){
							document.getElementById('emailgame_friends_email').value = '';
							document.getElementById('emailgame_friends_name').value = '';
						}
						
					}
				});
				
            }
        });
	
}



function global_members_email_games_send(){
	var url_goto = 'members_email_games_process.php?action=send';
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_email_games_send').html(msg);
		}
	});
}


// ------------------------- END : Members Email Games ----------------------------------------------



// -------------------------- BEGIN : Game of OC 2009-03 --------------------------------------------------

function global_oc200903_game(){
	
	var url_goto = 'oc200903_game_process.php?action=save_answer';
	
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {
				
				
				$('#myform').ajaxSubmit({
					url : url_goto,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_oc200903_game').html(msg);						
					}
				});
				
            }
        });
	
}

function global_oc200903_game_login(){
	var url_goto = 'oc200903_game_process.php?action=login';
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : url_goto,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_oc200903_game').html(msg);						
					}
				});
				
            }
        });
}

// -------------------------- END : Game of OC 2009-03 ----------------------------------------------------



// -------------------------- BEGIN : Member Join Member Share Game ---------------------------------------

function global_member_join_shar_game(myform, obj_respond, url_process, url_after){
	
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#"+myform).validate({
    	    meta: "validate",
            submitHandler: function(form) {


				$('#'+myform).ajaxSubmit({
					url : url_process,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						if(url_after != ''){
							window.location = url_after;
						}else{
							$('#'+obj_respond).html(msg);
						}
					}
				});
				
				
            }
        });
	
}

// -------------------------- END : Member Join Member Share Game -----------------------------------------

// ------------------------- BEGIN : DHC Olive Club Cover Activity ----------------------------------
function global_game_cover_vote(div_obj, url_vote){	
	$('#myform').ajaxSubmit({
		url : url_vote,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#'+div_obj).html(msg);
		}
	});
}


function global_display_cover_iframe(url){
		oc_cover_game.location.href=url;
}
	
	
	
	
	function global_open_cover_style(condition){
		if(condition == 'main'){
			document.getElementById('div_cover_main').style.display = '';
			document.getElementById('div_cover_left').style.display = 'none';			
			document.getElementById('div_cover_right').style.display = 'none';		
			document.getElementById('div_cover_bottom').style.display = 'none';			
			document.getElementById('div_cover_dhc_style').style.display = 'none';
		}
		
		
		
		if(condition == 'left'){
			document.getElementById('div_cover_main').style.display = 'none';
			document.getElementById('div_cover_left').style.display = '';			
			document.getElementById('div_cover_right').style.display = 'none';		
			document.getElementById('div_cover_bottom').style.display = 'none';			
			document.getElementById('div_cover_dhc_style').style.display = 'none';			
		}
		
		
		
		if(condition == 'right'){
			document.getElementById('div_cover_main').style.display = 'none';
			document.getElementById('div_cover_left').style.display = 'none';			
			document.getElementById('div_cover_right').style.display = '';		
			document.getElementById('div_cover_bottom').style.display = 'none';			
			document.getElementById('div_cover_dhc_style').style.display = 'none';
		}
		
		
		if(condition == 'bottom'){
			document.getElementById('div_cover_main').style.display = 'none';
			document.getElementById('div_cover_left').style.display = 'none';			
			document.getElementById('div_cover_right').style.display = 'none';		
			document.getElementById('div_cover_bottom').style.display = '';			
			document.getElementById('div_cover_dhc_style').style.display = 'none';
		}
		
		if(condition == 'dhc_style'){
			document.getElementById('div_cover_main').style.display = 'none';
			document.getElementById('div_cover_left').style.display = 'none';			
			document.getElementById('div_cover_right').style.display = 'none';		
			document.getElementById('div_cover_bottom').style.display = 'none';			
			document.getElementById('div_cover_dhc_style').style.display = '';
		}
		
		
	}
	

function global_game_cover_save(){	
		jQuery.validator.messages.required = "";
		$.metadata.setType("attr", "rule");
		var v = jQuery("#myform").validate({
				meta: "validate",
				submitHandler: function(form) {	
				
					$('#myform').ajaxSubmit({
						url : 'game_cover_process.php?action=save_cover',
						beforeSubmit: block,
						clearForm: false,
						success: function(msg){
						
							$('#div_body').html(msg);
							
							timer = setTimeout('global_game_cover_finish()',5000);
						}
					});
					
				}
		   });	
}
	
function global_game_cover_finish(){
	window.location.href = 'game_cover_list.php';
}




function global_game_cover_edit(){	
		jQuery.validator.messages.required = "";
		$.metadata.setType("attr", "rule");
		var v = jQuery("#myform").validate({
				meta: "validate",
				submitHandler: function(form) {	
				
					$('#myform').ajaxSubmit({
						url : 'game_cover_process.php?action=save_cover',
						beforeSubmit: block,
						clearForm: false,
						success: function(msg){
						
							$('#div_body').html(msg);
							
							timer = setTimeout('global_game_cover_edit_finish()',5000);
						}
					});
					
				}
		   });	
}
	
function global_game_cover_edit_finish(){
	window.location.href = 'game_cover_my_list.php';
}


function global_game_cover_delete(saveForm,url1,url2){
	if(confirm('คุณต้องการลบปก DHC ของคุณ ใช่หรือไม่?') == true) {
		$('#'+saveForm).ajaxSubmit({
			url : url1,
			clearForm: true,
			success: function(msg){
				
				if(url2){
					window.location = url2;
				}else{
					$('#'+divObj).html(msg);
				}
			}
		});
	}
}


function global_game_cover_comment(){	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
	var v = jQuery("#myform").validate({
			meta: "validate",
			submitHandler: function(form) {	
				
				$('#myform').ajaxSubmit({
					url : 'game_cover_process.php?action=save_comment',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						
						$('#div_body').html(msg);
						
						if(document.getElementById('check_success').value == 'success'){
							timer = setTimeout('global_game_cover_comment_finish()',4000);
						}
					}
				});
					
			}
		  });	
}
	
function global_game_cover_comment_finish(){
	window.location.href = 'game_cover_detail.php';
}


function global_game_cover_login(myform, obj_respond, url_process){
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#"+myform).validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#'+myform).ajaxSubmit({
					url : url_process,
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#'+obj_respond).html(msg);
						if(document.getElementById('check_success').value == 'success'){
							window.location.href='game_cover_my_list.php';
						}
					}
				});
				
            }
        });
	
}

function global_CheckIsIE(){ 
	if (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER'){ 
		return true;
	}else{ 
		return false; 
	} 
} 


function global_game_cover_PrintThisPage(){
	if(global_CheckIsIE() == true){ 
		document.oc_cover_game_detail.focus(); 
		document.oc_cover_game_detail.print(); 
	}else{ 
		window.frames['oc_cover_game_detail'].focus(); 
		window.frames['oc_cover_game_detail'].print(); 
	} 
} 

	
// ------------------------- END : DHC Olive Club Cover Activity ------------------------------------


// ------------------------- Images Over ------------------------------------------------------------
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];}
}
// --------------------------------------------------------------------------------------------------


// --------------------------- // Check input number only -------------------------------------------

function keypress(evt) {
		try{
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode != 127 && charCode != 8 && (charCode < 48 || charCode > 57))
            return false;
		} catch(e){}
         return true;

/*	if (keycode < 45 || keycode > 57) {		
		if (keycode == 13)
			$(document.body).focus();
		else 
			if ( ! e) event.returnValue = false; else e.preventDefault();		
		return false;	*/		
//		alert('กรุณาป้อนข้อมูลเป็นตัวเลขเท่านั้น');
//	}

}

// --------------------------------------------------------------------------------------------------

// --------------------------- // Blink // ----------------------------------------------------------

	function BlinkLoad(){
		setInterval('blinkIt()',550);
	
	}
	
	function blinkIt() {
	
		
	
		if (!document.all) return;
	
		else {
	
			for(i=0;i<document.all.tags('blink').length;i++){
	
				s=document.all.tags('blink')[i];
	
				s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
	
			}
	
		}
	
	}

// ------------------------- // Bling // ------------------------------------------------------------

// ------------------------- BEGIN : Middle window --------------------------------------------------
function kPopup(theURL,winName,posx,posy,width,height,features) {
	if (!winName.closed && winName.location) {
		winName.location.href = theURL;
	} else {
		var left,top = 0;
		if(posx=="right"){
			left = screen.width - width;
		} else if(posx=="center") {
			left = (screen.width - width)/2;
		} else {
			left = 0;
		}

		if(posy=="bottom") {
			top = screen.height - height;
		} else if(posy=="middle") {
			top = (screen.height - height)/2;
		} else {
			top = 0;
		}
		winName=window.open(theURL,winName,"width="+width+",height="+height+",left="+left+",top="+top+","+features);
		if (!winName.opener) {
			winName.opener = self;
		}
	}
	if (window.focus) {
		winName.focus();
	}
	return false;
}



function global_popup_midel(theURL,winName,posx,posy,width,height,features) {
	if (!winName.closed && winName.location) {
		winName.location.href = theURL;
	} else {
		var left,top = 0;
		if(posx=="right"){
			left = screen.width - width;
		} else if(posx=="center") {
			left = (screen.width - width)/2;
		} else {
			left = 0;
		}

		if(posy=="bottom") {
			top = screen.height - height;
		} else if(posy=="middle") {
			top = (screen.height - height)/2;
		} else {
			top = 0;
		}		
		winName=window.open(theURL,winName,'toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=yes,resizable=no,width='+width+',height='+height+',left='+left+',top='+top);
		
		if (!winName.opener) {
			winName.opener = self;
		}
	}
	if (window.focus) {
		winName.focus();
	}
	return false;
}
// ------------------------- END : Middle window ----------------------------------------------------

// ------------------------- BEGIN : Printing -------------------------------------------------------
function global_print(){  
	if (window.print) {
		window.print() ;  
	}else{
		var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
		document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
		WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";  
	}
}
// ------------------------- END : Printing ---------------------------------------------------------

// ------------------------- BEGIN : Show image -----------------------------------------------------
function MM_openBrWindow(theURL,winName,features){
		window.open(theURL,winName,features);
}
function decision(message, url){
		if(confirm(message)) location.href = url;
}
	
	hs.registerOverlay(
    	{
    		thumbnailId: null,
    		overlayId: 'controlbar',
    		position: 'top right',
    		hideOnMouseOut: true
		}
	);
	
    hs.graphicsDir = 'js/highslide/graphics/';
    hs.outlineType = 'rounded-white';
    window.onload = function() {
    hs.preloadImages(5);
}
// ------------------------- END : Show image --------------------------------------------------------



/* ----------------- BEGIN : For Tisco promotion ---------------------------*/

function global_strtoupper(obj) {
	var obj_value = document.getElementById(obj.id).value;
	document.getElementById(obj.id).value = obj_value.toUpperCase();
}


function global_tisco_check_code(){
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : 'products_tisco_process.php?action=check_code',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_check_code').html(msg);
						if(document.getElementById('check_tisco_code').value == 'success'){
							window.location.href='products_tisco.php';
						}
					}
				});
				
            }
        });
	
}
/* ----------------- END : For Tisco promotion -----------------------------*/

// ----------- Function Webboard 26 ต.ค.52 --------------//


function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else 
countfield.value = maxlimit - field.value.length;
}


function global_check_login(){
	var url_goto = 'webboard_process.php';
	$('#myform').ajaxSubmit({
		url : url_goto,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_members_login').html(msg);
			
			/*if(document.getElementById('check_login_success').value == 'successful'){
				window.location = 'webboard_post.php';
			}*/
			
		}
	});
}


function global_members_login_webboard(){
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : 'members_login.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						
						$('#div_members_login').html(msg);
						if(document.getElementById('check_login_success').value == 'successful'){
							window.location.href = window.location.href;
						}
					}
				});
				
            }
        });
	

	
}

function global_post_webboard(url_goto,room_board_id){
	
	$('#myform').ajaxSubmit({
			beforeSubmit: block,
			clearForm: false,
			success: function(msg){
						
				$('#div_members_login').html(msg);
				window.location.href = url_goto+'?room_board_id='+room_board_id ;
				
			}
	});
	
}

function global_webboard_input_em(em){	
	document.getElementById('topic_board_detail').value = document.getElementById('topic_board_detail').value+em;
}

function global_webboard_input_reply_em(em){	
	document.getElementById('reply_board_detail').value = document.getElementById('reply_board_detail').value+em;
}
function global_webboard_save(room_board_id){
	//var qacat2_id = document.getElementById('qacat2_id').value;

	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#myform').ajaxSubmit({
					url : 'webboard_process.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						
						$('#div_members_login').html(msg);
							
							if(document.getElementById('post_board_success').value == 1){
								if(room_board_id==0){
									window.location.href = 'webboard.php';
								}else{
									window.location.href = 'webboard_topic_list.php?room_board_id='+room_board_id;
								}
							}
					}
				});
				
            }
        });
}


function global_webboard_save_reply(room_board_id,topic_code){
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#form_reply").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#form_reply').ajaxSubmit({
					url : 'webboard_process.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						
						$('#div_reply_webboard').html(msg);
							var page = $("#Page").val();
						
							if($('#reply_board_success').val() == 1){
								 window.location.href = 'webboard_showtopic.php?topic_code='+topic_code+'&room_board_id='+room_board_id+'&Page='+page;
							}
						
						}
				});
				
            }
        });
}

function goto_login(){
	document.getElementById('members_username').focus();
}

function global_webboard_save_report(){
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#form_report").validate({
    	    meta: "validate",
            submitHandler: function(form) {

				$('#form_report').ajaxSubmit({
					url : 'webboard_process.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						
						$('#div_report_webboard').html(msg);
						
						/*if(document.getElementById('report_board_success').value == 1){
							window.location.href = 'webboard_showtopic.php?topic_code='+topic_code+'&room_board_id='+room_board_id;
						}*/
						
					}
				});
				
            }
        });
	
}


function global_reply_webboard(room_board_id,topic_board_code){
	
	$('#form_reply').ajaxSubmit({
			beforeSubmit: block,
			clearForm: false,
			success: function(msg){
						
				$('#div_members_login').html(msg);
				window.location.href = 'webboard_reply.php?room_board_id='+room_board_id+'&topic_board_code='+topic_board_code ;
				
				}
	});
	
}
// ----------- Function Webboard 26 ต.ค.52 --------------//
/*********************************/
/*------------New Function--------------*/
/********************************/

function number_format (number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    //
    // version: 906.1806
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +     improved by: davook
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Jay Klehr
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *     example 10: number_format('1.20', 2);
    // *     returns 10: '1.20'
    // *     example 11: number_format('1.20', 4);
    // *     returns 11: '1.2000'
    // *     example 12: number_format('1.2000', 3);
    // *     returns 12: '1.200'
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

function calculate_exchange_point(){
	var objPoint = { 
		factor: 10,
		minimum: function(recMin){ return recMin; },
		msg_min: function(recMin){ return "คะแนนที่ใช้สำหรับแลกของกำนัลที่คุณเลือกต้อง "+recMin+" คะแนนขึ้นไปค่ะ"; },
		msg_notenough: "คะแนนของคุณไม่เพียงพอในการแลกของกำนัลค่ะ"
	};
	var bf_cal = cv2num($('#div_before_cal').text());
	var used = cv2num($('#txt_point_used').val());
	var p_min = cv2num($('#hdn_point_min').val());
	if ( ! used){
		$('#txt_point_used').val($('#hdn_point_min').val()).focus();
	} else if (used < p_min){
		alert(objPoint.msg_min(p_min));
		$('#txt_point_used').val($('#hdn_point_min').val()).focus();
	} else if (used > Math.ceil(bf_cal / objPoint.factor) && used > p_min){
		$('#txt_point_used').val(Math.ceil(bf_cal / objPoint.factor)).focus();
	}
	used = cv2num($('#txt_point_used').val());
	var used_value = currency_format((used * objPoint.factor), 2);
	$('#txt_point_used_value').val(used_value);
	global_calculate_ex_point_orders();
}

function global_calculate_ex_point_orders(ddObj){
	if (ddObj){
		var obj = $(ddObj); //obj jquery style		
		var sum_voucher = 0;
		var chk_warn = false;
		//check duplicate with another	
		$("select[name='orders_voucher_code[]']").each(function(inx){
			if ($(this).val() == obj.val() && $(this).attr('id') != obj.attr('id') && obj.val() != '0'){
				alert("คุณเลือกรหัสคูปองใบนี้แล้วค่ะ");
				obj.val(0);
				chk_warn = true;
				sum_voucher = 0;
				return false;
			}
			if ($(this).attr('id') != obj.attr('id')) sum_voucher += cv2num($('#orders_voucher_value_'+inx).val());			
		});
		if ( ! chk_warn){
			if (obj.val() != '0' && sum_voucher >= cv2num($('#div_grand_total').text())){
				alert('จำนวนเงินเพียงพอสำหรับยอดที่ต้องชำระแล้วค่ะ');
				obj.val(0);
			}
		}
		//---		
		var inx = obj.attr('id').substring(obj.attr('id').lastIndexOf('_') + 1);
		var value = obj.val().split('_').pop();		
		$('#orders_voucher_value_'+inx).val(currency_format(value, 2));
	}
	var url_goto = 'exchange_point_orders_process.php?action_calculate=calculate_order';	
	$('#myform').ajaxSubmit({
		url : url_goto,
		clearForm: false,
		success: function(msg){			
			$('#div_orders_messagebox').html(msg);

			$('#div_grand_total').text($('#grand_total_diff_return_value').val());
			$('#div_grand_total_append').text($('#grand_total_append_return_value').val());			
			$('#div_orc_point').text($('#orc_point_return').val());
			$('#div_none_orc_point').text($('#none_orc_point_return').val());
			
			$('#orders_transport_cost').val(cv2num($('#transport_cost_return_value').val()));
			$('#grand_total_post_value').val(cv2num($('#grand_total_post_return_value').val()));
			
			$('#mem_point_value').val(cv2num($('#mem_none_orc_point_total_return').val()));
			
			$('#mem_orc_point_one').val(cv2num($('#mem_orc_point_one_return').val()));
			$('#mem_orc_point_two').val(cv2num($('#mem_orc_point_two_return').val()));
			$('#mem_orc_point_three').val(cv2num($('#mem_orc_point_three_return').val()));
			$('#mem_orc_point_four').val(cv2num($('#mem_orc_point_four_return').val()));
			$('#mem_orc_point_five').val(cv2num($('#mem_orc_point_five_return').val()));
			$('#mem_orc_point_total').val(cv2num($('#mem_orc_point_total_return').val()));
			
			$('#mem_none_orc_point_one').val(cv2num($('#mem_none_orc_point_one_return').val()));
			$('#mem_none_orc_point_two').val(cv2num($('#mem_none_orc_point_two_return').val()));
			$('#mem_none_orc_point_three').val(cv2num($('#mem_none_orc_point_three_return').val()));
			$('#mem_none_orc_point_four').val(cv2num($('#mem_none_orc_point_four_return').val()));
			$('#mem_none_orc_point_five').val(cv2num($('#mem_none_orc_point_five_return').val()));
			$('#mem_none_orc_point_total').val(cv2num($('#mem_none_orc_point_total_return').val()));
			
			//check value before display payment method
			var cv2bool =  ! Boolean(parseFloat($('#grand_total_post_value').val()));
			if ($('#orders_payment_method:visible').length) $('#orders_payment_method').attr('disabled', cv2bool);
			if ($('#orders_pod_method:visible').length) $('#orders_pod_method').attr('disabled', cv2bool);
			//---
		}
	});	
}

function global_dhc_treatment_alert_before_add(product_id, obj, url, product_price,product_code){
	
	//alert(product_treatment_code_1);
	if($('#treatment_no').val()==2){
			var answer = confirm('***คุณต้องการเปลี่ยนสินค้าโปรโมชั่น Onzen Body Treatment ที่เลือกหรือไม่ ถ้าต้องการระบบจะลบสินค้าในตระกร้าของคุณทั้งหมด***\n***หากต้องการเลือกโปรโมชั่น Onzen Body Treatment เพิ่ม กรุณาทำการเปิด Order ใหม่ค่ะ');
			if(answer == true){
					delete_to_cart('cart_delete.php?action=deleteall');
					return false ;				
			}else{
				return false ;
			}
		}else if($('#treatment_no').val()==null){
			alert('ทางบริษัท ดีเอชซี (ประเทศไทย) จำกัด ได้จัดโปรโมชั่น Onzen Body Treatment ตั้งแต่วันที่ 25 มีนาคม 2553 ถึง 10 พฤษภาคม 2553\n\n*** เพียงซื้อ Onzen Body Treatment ใดๆ คอร์สราคาปกติรับส่วนลดทันที 50% สำำหรับซื้อคอร์สที่ 2 (ไม่รวมคอร์สทรีทเมนต์อื่น *สามารถเลือกคอร์สเหมือนกันหรือต่างกันได้ โดยคอร์สที่ 2 มีราคาเท่ากันหรือต่ำกว่าคอร์สแรก และสงวนสิทธิ์ในการซื้อครั้งเดียวกันค่ะ)');
		}
		add_to_cart(product_id, obj, url,product_code);
}

// --------------------- Onzen Body Treatment 25 มี.ค. - 10 พ.ค. 53 หลังจากนี้ให้ลบทิ้ง ------------------------

function add_to_cart_fleece(product_id, obj, url,product_code){
/*	alert(product_id);
	return ;*/
	if($(':checkbox + img').length){
		alert('ขอโทษน่ะค่ะ ใบเสร็จ 1 ใบสามารถใช้เป็นสิทธิ์แลกซื้อได้ 1สิทธิ์ค่ะ');
		return ;
	}
	var go_url = url+'?product_id='+product_id+'&quantity='+document.getElementById(obj).value+'&action=get_fleece';
	$('#myform').ajaxSubmit({
		url : go_url,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){
			$('#div_cart').html(msg);
			$('#'+obj).val(1);
			if($('#add_fleece').val()==1){
				window.location.href="orders.php";	
			}
		}
	});
	
}

function delete_to_cart_fleece(url){
	$('#myform').ajaxSubmit({
		url : url,
		beforeSubmit: block,
		clearForm: false,
		success: function(msg){			
			$('#div_cart').html(msg);
			if($('#del_fleece').val()==1){
				window.location.href="orders.php";	
			}
		}
	});
}


/*####### Surprise gift  8 - 19 feb 2010 #########*/

function chk_surprise(){
			if($('td.surprise_card :checked').attr('checked')){
				alert('สงวนสิทธิ์ให้บริการเฉพาะในเขตกทม.และปริมณฑล ด้วยการจัดส่งแบบปกติเท่านั้นค่ะ (ไม่รวมบริการ Payment on Delivery)');
				$('td.surprise_card :checked').attr('checked',false);
				$('#surprise_text').val('');
				$('#reciever').val('');
				$('#sender').val('');
				$('#surprise_text').attr('disabled',true);	
				$('#tb_display').css('display','none');
			}
		}
		
function surprise_gift(obj){
		 	var chk = $(obj).attr('checked') ;
			var chk_pod = $('#orders_send_address02').attr('checked');
			if(chk_pod){
				alert('สงวนสิทธิ์ให้บริการเฉพาะในเขตกทม.และปริมณฑล ด้วยการจัดส่งแบบปกติเท่านั้นค่ะ (ไม่รวมบริการ Payment on Delivery)');
				$('td.surprise_card :checked').attr('checked',false);
				$('#surprise_text').val('');
				
				$('#surprise_text').attr('disabled',true);	
				
				//$('#orders_send_address01').attr('checked',true);
				/*$('#surprise_text').attr('disabled',false);
				$('#surprise_text').val('ของขวัญเพื่อคุณคนพิเศษ ขอให้มีความสุข สดใส สุขภาพดี ในทุกๆวันนะคะ');*/
				return false;
			}
			
			$('td.surprise_card :checked').attr('checked',false);
			
			
			$(obj).attr('checked',chk);
			$('#surprise_text').attr('disabled',!chk);
			$('#reciever').val('');
			$('#sender').val('');
			if(chk){
				clr_form() ;
				$('#surprise_text').val('ของขวัญเพื่อคุณคนพิเศษ ขอให้มีความสุข สดใส สุขภาพดี ในทุกๆวันนะคะ');
			}else{
				$('#surprise_text').val('');
				
			}
		
		}	
		
function clr_form(){
			$('#div_normal_address').find('select').val(0) ;
			$('#div_normal_address').find(':text').val('');
			
}
		
function chk_province_surprise(province_id){
			
			if($('td.surprise_card :checked').attr('checked') && (province_id!=1 && province_id!=2 && province_id!=4 )){
				alert('DHC Surprise Gift Delivery สงวนสิืทธิ์ให้บริการเฉพาะในเขตกทม.และปริมณฑลค่ะ');
				$('#members_conf_order_province').val(0) ;
				return false ;
			}
}
		
function show_card(code){
			
			if($('#chk_card1').attr('checked') || $('#chk_card2').attr('checked') || $('#chk_card3').attr('checked')  ){
				$('#tb_display').css('display','block');
				$('#show_card').css('background','url(images/card/l/'+code+'.jpg) no-repeat top center');
			
				
			}else {
				$('#show_card').css('background','none');
				$('#tb_display').css('display','none');
				
			}
			
			
}

    
		
/*####### Surprise gift  8 - 19 feb 2010 #########*/




function add_to_cart_set_983(product_id, obj, url, sub_product_id){
//	alert(sub_product_id);return;
	var chk = 0 ;

		$("select[name='sub_product_code_983[]']").each(function(){
																
				if($(this).val()==''){
					alert('คุณยัำงเลือกสินค้าไม่ครบค่ะ');
					chk =1 ;
					return false;
				}
			 }
			)
	
	
	if(chk==0){
				var go_url = url+'?product_id='+product_id+'&quantity='+document.getElementById(obj).value+'&sub_product_id_mini_sales='+sub_product_id ;
			$('#myform').ajaxSubmit({
				url : go_url,
				beforeSubmit: block,
				clearForm: false,
				success: function(msg){
					
					$('#div_cart').html(msg);
					
				}
			});
	}
	
	
}


function add_to_cart_set_982(product_id, obj, url, sub_product_id){

var chk = 0 ;

		$("select[name='sub_product_code_982[]']").each(function(){
																
				if($(this).val()==''){
					alert('คุณยัำงเลือกสินค้าไม่ครบค่ะ');
					chk =1 ;
					return false;
				}
			 }
			)
	
	
	if(chk==0){
				var go_url = url+'?product_id='+product_id+'&quantity='+document.getElementById(obj).value+'&sub_product_id_mini_sales='+sub_product_id ;
			$('#myform').ajaxSubmit({
				url : go_url,
				beforeSubmit: block,
				clearForm: false,
				success: function(msg){
					
					$('#div_cart').html(msg);
					
				}
			});
	}

}

function global_login_midyear_sales(){
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {
				
				$('#myform').ajaxSubmit({
					url : 'members_login.php',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_login').html(msg);
						if($('#check_login_success').val()=='successful'){
							window.location = 'products_midyear_sales.php' ;
						}
					}
				});
				
            }
        });
}

function add_to_cart_set(product_id, obj, url, product_code,chk_eye){

var chk = 0 ;
var i = 0 ;
		$("select[name='sub_product_code_"+product_code+"[]']").each(function(){
																
				if($(this).val()==''){
					
					$(this).css('backgroundColor','orange') ;
					
					chk =1 ;
					return false;
				}else{
					$(this).css('backgroundColor','white') ;
				}
				i++ ;
			 }
			)
	
	
	if(chk==0){
				if(!chk_eye){
					var go_url = url+'?product_id='+product_id+'&quantity='+document.getElementById(obj).value+'&sub_product_code_set='+product_code ;
				}else{
					var go_url = url+'?product_id='+product_id+'&quantity='+document.getElementById(obj).value+'&sub_product_code_set='+product_code+'&eye_shadow='+chk_eye ;
				}
			$('#myform').ajaxSubmit({
				url : go_url,
				beforeSubmit: block,
				clearForm: false,
				success: function(msg){
						
					$('#div_cart').html(msg);
					
				}
			});
	}

}


function show_txt(){	
		if($('#mid_double_point').val()>0){
			$('#txt_mid_double_point').css('display','block');
		}else{
			$('#txt_mid_double_point').css('display','none');
		}
}	

function numbersonly(myfield, e, dec){
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
		(key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}
	
	
function check_select_product(product_id){
	if(!$(":checked").length){
		alert('กรุณาเลือกสินค้าด้วยค่ะ') ;
		return false ;
	}else{
		add_to_cart(product_id, 'order_quantity', 'cart_add.php', '', 'special_dc');	
	}
}
	
function in_array(needle, haystack) 
{ 
    for(var key in haystack) 
    { 
        if(needle === haystack[key]) 
        { 
            return true; 
        } 
    } 
 
    return false; 
}				

function global_login_anniversary_sales(){
	
	jQuery.validator.messages.required = "";
	$.metadata.setType("attr", "rule");
    var v = jQuery("#myform").validate({
    	    meta: "validate",
            submitHandler: function(form) {
				
				$('#myform').ajaxSubmit({
					url : 'members_login.php?login=ann',
					beforeSubmit: block,
					clearForm: false,
					success: function(msg){
						$('#div_login').html(msg);
						if($('#check_login_success').val()=='successful'){
							window.location = 'products_anniversary_sales.php' ;
						}
					}
				});
				
            }
        });
}
