function changeLang(lang) {
	var u = window.location.href;
	var s = 'change_lang.php?lang=' + lang + '&url=' + escape(u);
	window.location.replace(s);
}

function viewPopDetails( id, url, title ) {
	new Popdetail().open(id, url, title);
}

function frontendIsValidEmail( email )
{
	var emailPatterns = [
		/.+@.+\..+$/i,
		/^\w.+@\w.+\.[a-z]+$/i,
		/^\w[-_a-z~.]+@\w[-_a-z~.]+\.[a-z]{2}[a-z]*$/i,
		/^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/i /* modified by jim ma */
		];
	if ( ! emailPatterns[0].test( email ) )
	{
		return false;
	}
	return true;
}	

function frontendMsnMessage(person) {
try{messenger.classid="clsid:B69003B3-C55E-4B48-836C-BC5946FC3B28";}
catch(e){if(!(e.number && 2148139390) == 2148139390) {alert("请先安装MSN！");return;}}
if(messenger.MyStatus==1){alert("你还没有登陆MSN Messegner。");return;}
//try{var contact = messenger.GetContact(person,"");}
//catch(e){
//if((e.number && 2164261642) == 2164261642) //MSGR_E_USER_NOT_FOUND{
//if(confirm("把 " + screen + " 加入你的列表？") == true) messenger.AddContact(0, person);}}
//if(confirm("给 " + screen + " 发送一个信息？") == true) messenger.InstantMessage(person);}
messenger.InstantMessage(person);
}


//~~~~~ COOKIES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var Cookies  = {
	prefix : '',

	set: function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		} else {
			var expires = "";
		}
		document.cookie = this.prefix+name+"="+encodeURIComponent(value)+expires+"; path=/";
	},

	get: function (name) {
		var nameEQ = this.prefix+name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) {
				return decodeURIComponent ( c.substring(nameEQ.length,c.length) );
			}
		}
		return '';
	},

	del: function (name) {
		this.set(this.prefix+name,"",-1);
	}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


function search_prod_quick() {
	var u = 'product_search.php?adv_keyword=' + encodeURIComponent($('quick_keyword').value);
	
	if ( !!$('FRONTEND_USE_AJAX') && $('FRONTEND_USE_AJAX').value == '1' ) {
		ajaxUpdateMainContent(u);
	} else {
		window.location.href = u;
	}
}

function search_prod_adv() {
	var adv_brand = [];
	var cb = $('adv_brand_list').getElements('input[type=checkbox]');
	for (var i=0; i<cb.length; i++) {
		if (cb[i].checked) {
			adv_brand.push(cb[i].value);
		}
	}

	var u = 'product_search.php?adv_keyword=' + encodeURIComponent($('adv_keyword').value);
	u+= '&adv_cat=' + encodeURIComponent($('adv_cat').value);
	u+= '&adv_brand=' + adv_brand.join(',');
	u+= '&adv_price1=' + encodeURIComponent($('adv_price1').value);
	u+= '&adv_price2=' + encodeURIComponent($('adv_price2').value);

	if ( !!$('FRONTEND_USE_AJAX') && $('FRONTEND_USE_AJAX').value == '1' ) {
		ajaxUpdateMainContent(u);
	} else {
		window.location.href = u;
	}
}

function clear_search_prod_adv() {
	$('adv_keyword').value = '';
	$('adv_cat').selectedIndex = -1;
	$('adv_price1').value = '';
	$('adv_price2').value = '';

	var cb = $('adv_brand_list').getElements('input[type=checkbox]');
	for (var i=0; i<cb.length; i++) {
		cb[i].checked = false;
	}

}

function ajax_cart_view( close_only ) {
	if ( !!Popdetail.win ) {
		Popdetail.win.hide();
	}

	if ( !close_only ) {
		var other_options = {
			onDisplay: function() {
				$('ajax_cart_view').setStyle('display', '');
			}
		};

		window.ajax_cart_win = new Popdetail().open('ajax_cart_view', 'view_cart.ajax.php', $('ajax_cart_win_title').value , other_options);
		//viewPopDetails('ajax_cart_view', 'view_cart.ajax.php', $('ajax_cart_win_title').value );
		ajax_update_sidebar_cart();
	}
}

function ajax_update_sidebar_cart() {
	if ( $('sidebar_cart')) {
		var o = {url:$('Path_httpRoot').value+'view_cart.ajax.php' /*, update: $('sidebar_cart')*/
			, evalScripts: false, onSuccess: function(responseTree, responseElements, responseHTML,		responseJavaScript) { 
				$('sidebar_cart').set('html', responseHTML);
				$exec(responseJavaScript);
				frontend_ajax_OnLoad($('sidebar_cart'));
			}
		};

		var  data = { type: 'sidebar' };
		var myHTMLRequest = new Request.MYHTML(o).get( data );
	}
}
function ajax_update_sidebar_memarea() {
	if ( $('sidebar_memarea')) {
		var o = {url:$('Path_httpRoot').value+'mem_area.php'/*, update: $('sidebar_memarea')*/
			, evalScripts: false, onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) { 
				$('sidebar_memarea').set('html', responseHTML);
				$exec(responseJavaScript);
				frontend_ajax_OnLoad($('sidebar_memarea'));
			}
		};
		var  data = { type: 'sidebar' };
		var myHTMLRequest = new Request.MYHTML(o).get( data );
	}
}


function ajax_cart_add(id) {

	var d = {
		cart_item_id: id,
		cart_todo: 'add',
		ajax: '1'
	};
	
	var o = {
		url: 'cart.php',
		method: 'post',
		data: d,
		onComplete: function () {
				var text = this.response.text;
				var xml = this.response.xml;

				ajax_cart_view();
			}
	};
	new Request( o ).send();
}

function ajax_cart_update( checkout ) {
	var d = $('form_cart').toQueryString()+'&cart_todo=update&ajax=1';

	var o = {
		url: 'cart.php',
		method: 'post',
		data: d,
		is_checkout: !!checkout,
		onComplete: function () {
				var text = this.response.text;
				var xml = this.response.xml;

				if ( o.is_checkout ) {
					u = 'checkout.php';
					if ( !!$('FRONTEND_USE_AJAX') && $('FRONTEND_USE_AJAX').value == '1' ) {
						ajax_cart_view(true);
						ajaxUpdateMainContent(u);
					} else {
						window.location.href=i;
					}
				} else {
					ajax_cart_view();
				}
			}
	};
	new Request( o ).send();
}

function ajax_cart_empty( msg ) {
	if ( confirm(msg) ) {
		var d = {
			cart_todo: 'empty',
			ajax: '1'
		};
		
		var o = {
			url: 'cart.php',
			method: 'post',
			data: d,
			onComplete: function () {
					var text = this.response.text;
					var xml = this.response.xml;

					ajax_cart_view();
				}
		};
		new Request( o ).send();
	}
}

/*
function cart_add(id) {
	var f = $('form1');
	
	f.cart_todo.value = "add";
	f.cart_item_id.value = id;
	f.cart_redirect_to.value = "view_cart.php";
	
	f.onsubmit = null;
	f.action = 'cart.php';
	f.submit();
}
*/
function cart_form_submit(f, load_url, ajax_callback ) {
	if ( !!$('FRONTEND_USE_AJAX') && $('FRONTEND_USE_AJAX').value == '1' ) {
		if ( $(f.ajax_content) ) {
			$(f.ajax_content).value = '1';
		}
		if ( $(f.ajax) ) {
			f.ajax.value = "1";
		}

		var o = {};
		o.load_url = load_url;
		o.ajax_callback = ajax_callback || function(){};
		o.onComplete = function() {
			ajaxUpdateMainContent( o.load_url );
			o.ajax_callback();
		};
		f.set('send', {onComplete: o.onComplete});
		f.send();
	} else	{
		f.submit(); 
	}
}

function cart_update() {
	var f = $('form_cart');

	f.cart_todo.value = "update";
	f.cart_item_id.value = "";
	f.ajax.value = "";
	f.cart_redirect_to.value = 'view_cart.php';

	f.method = 'POST';
	f.onsubmit = null;
	f.action = 'cart.php';

	cart_form_submit(f, 'view_cart.php', ajax_update_sidebar_cart);

}
function cart_empty() {

	if ( confirm(  flt('Are you sure to empty the shopping cart?', '你確定要清除購物車嗎?', '你确定要清除购物车吗?')) ) {
		
		var f = $('form_cart');
		
		f.cart_todo.value = "empty";
		f.cart_item_id.value = "";
		f.cart_redirect_to.value = 'view_cart.php';

		f.method = 'POST';
		f.onsubmit = null;
		f.action = 'cart.php';
		
		cart_form_submit(f, 'view_cart.php', ajax_update_sidebar_cart);
	}
}
function cart_check_qty(f, id) {
	var e = f.elements["cart_item_" + id + "_qty"];
	var qty = e.value;
	
	msg = flt("Please enter a integer >= 0!", '請輸入一個數值 >=0 的整數!', '请输入一个数值 >=0 的整数!');
	var regex = new RegExp( "^\\d+$" );
	if ( !regex.test( qty ) )
	{
		alert( msg);
		e.select();
		e.focus();
		return;
	}
	
//	alert(qty);
	
	qty = parseInt( qty, 10 );
	
	if ( isNaN(qty) || qty < 0) {
		alert(msg);
		e.select();
		e.focus();
		return;
	}
	
	
}

function cart_update_subtotal(id) {
	var f = $('form_cart');
	
	var e_qty = f.elements["cart_item_" + id + "_qty"];
	var e_price = f.elements["cart_item_" + id + "_price"];
	var e_subtotal = f.elements["cart_item_" + id + "_subtotal"];
	
	e_subtotal.value = e_qty.value * e_price.value;
	
}

function cart_checkout( f ) {
	var f = $('form_cart');
	
	f.cart_todo.value = "update";
	f.cart_item_id.value = "";
	f.cart_redirect_to.value = 'checkout.php';
	f.method = 'POST';
	f.onsubmit = null;
	f.action = 'cart.php';


	cart_form_submit(f, 'checkout.php', ajax_update_sidebar_cart);
}

function cart_checkout2() {
	alert('called cart_checkout2');
	var f = $('form_checkout');
	
	f.method = 'POST';
	f.onsubmit = null;
	f.action = 'checkout_submit.php';
	f.submit();
}

function cart_checkout_confirm() {
	var f = $('form_checkout_confirm');
	
	f.cart_todo.value = "confirm";
	
	f.method = 'POST';
	f.onsubmit = null;
	f.action = 'checkout_confirm_submit.php';
	//f.submit();

	if ( !!$('FRONTEND_USE_AJAX') && $('FRONTEND_USE_AJAX').value == '1' ) {
		$(f.ajax_content).value = '1';

		var o = {};
		o.onComplete = function() {
			var json_data = JSON.decode(this.response.text);

			ajax_update_sidebar_cart();
			ajaxUpdateMainContent( json_data.redirect );
		};
		f.set('send', {onComplete: o.onComplete});
		f.send();
	} else	{
		f.submit(); 
	}

}

function flt( en, tc, sc ) {
/*
	if ( is_array($en) ) {
		$t = $en;
		$en = $t[0];
		$tc = @$t[1];
		$sc = @$t[2];
	}
*/
	switch ( $('FRONTEND_LANG').value ) {
		case 'en':	
			s = en;
			break;
		case 'tc':	
			s = tc;
			break;
		case 'sc':	
			s = sc;
		break;
	}
	if (s == '') {
		s = en;
	}
	
	return s;
}

/*
Script: Popdetail.js
*/
var Popdetail = new Class({
	Implements: [Options, Events],

	options: {
//	anchors: null,
		resizeDuration: 400,
//	resizeTransition: false,	// default transition
		initialWidth: 850,
		initialHeight: 450,
		zIndex: 5000,
		autoScanLinks: true,
		relString: 'Popdetail'
//	onDisplay: $empty,
//	onHide: $empty
	},
	initialize: function(options){
		this.setOptions(options);
		this.anchors = this.options.anchors || arguments[1];
		if (this.options.autoScanLinks && !this.anchors) {
			this.anchors = [];
			$$('a[rel^='+this.options.relString+']').each(function(el){
				if(!el.retrieve('Popdetail')) this.anchors.push(el);
			}, this);
		}
		if(!$$(this.anchors).length) return; //no links!
		this.addAnchors(this.anchors);
	},

	addAnchors: function(anchors){
		$$(anchors).each(function(el){
			if(!el.retrieve('Popdetail')) {
				el.store('Popdetail', this);
				el.addEvent('click', function(e){
					e.stop();
					this.click(el);
				}.bind(this));
			}
		}.bind(this));
	},


	click: function(link){
		link = $(link);
		var url = link.get('href');
		var title = link.get('title')
		var rel = link.get('rel')||this.options.relString;
//		if (rel == this.options.relString) {
			return this.open(url, title);
//		}
	},

	open: function(id, url, title, other_o){
		var o = {};
		o.title = title;
		o.url = url;
		//detail_url = 'test.html';

		other_o = other_o||{};

		var obj = {
			url: o.url,
			position: 'center',
			height: 450,
			width: 850,
			caption: title,
			draggable: true,
			hideOnClick: false,
			//noCache: true,


	//		useWaiter: true,
	//		waiterOptions: {	fxOptions: {duration: 500}	},

			handleResponse: function(response){
				var html = StickyWin.ui( '<div class="popup_title">'+o.title+'</div>', '<div class="popup_body">'+response+'</div>', {
					cssClassName: 'redStickyWin',
					closeButton: false,
					width: '850px'
				});
				this.setContent(html);
				this.show();
			},
			onDisplay : function() {
			},
			onClose : function () {
			}
		};


		if ( id.length )
		{
			obj['id'] = id;
		}

		obj = $merge(obj, other_o);

		return Popdetail.win = new StickyWin.Fx.Modal.Ajax(obj).update();
	}
});
window.addEvent('domready', function(){if($(document.body).get('html').match(/rel=?.Popdetail/i)) new Popdetail()});


/* overwrite default to change the default baseHref for clientcide version: '2.2.0', */
StickyWin.ui = function(caption, body, options){
	options = options ||	{baseHref: $('Path_httpRoot').value+'images/stickyWin/'};
	return document.id(new StickyWin.UI(caption, body, options));
};

StickyWin.MyAlert = function(msg, type, onClose, my_op) {
	//var baseHref_ui = $('Path_httpRoot').value+'images/stickyWin/';
	var baseHref = $('Path_httpRoot').value+'images/stickyWin/alert/';
	var img = '';
	switch (type) {
		case 'success':
		case 'error':
		case 'info':
			img = type + '.png';
			break;
		case 'loading':
			img = type + '.gif';
			break;
	}
	msg = '<p class="errorMsg SWclearfix" style="margin: 0px;min-height:10px;font-size:12pt;line-height:150%;">' +
						'<img src="'+baseHref+img+ '"'+
						' class="bang clearfix" style="float: left; width: 30px; height: 30px; margin: 3px 5px 5px 0px;">'
						 + msg + '</p>';
	var ui_options = {width: 250};
	//ui_options.baseHref = baseHref_ui;

	var body = StickyWin.ui('', msg, ui_options);


	var o = {};
	o.MyOnClose = onClose;
	o.onClose = function(){
		this.destroy();
		if ( $type(o.MyOnClose) )
		{
			o.MyOnClose();
		}
	};

	var op = {
		destroyOnClose: true,
		//hideOnClick: false,
		maskOptions: {
			style: {
				zIndex: 11000
			}
		},
		zIndex: 110001,
		content: body,
		position: 'center', //center, corner
		onClose: o.onClose
	};
	my_op = my_op||{};
	op = $merge(op, my_op);

	var win = new StickyWin.Modal(op);

	win.pin();

	return win;
};

document.write1 = function(str){
	var moz = !window.opera && !/Apple/.test(navigator.vendor);
	
	// Watch for writing out closing tags, we just
	// ignore these (as we auto-generate our own)
	if ( str.match(/^<\//) ) return;

	// Make sure & are formatted properly, but Opera
	// messes this up and just ignores it
	if ( !window.opera )
		str = str.replace(/&(?![#a-z0-9]+;)/g, "&");

	// Watch for when no closing tag is provided
	// (Only does one element, quite weak)
	str = str.replace(/<([a-z]+)(.*[^\/])>$/, "<$1$2></$1>");
	
	// Mozilla assumes that everything in <acronym title="Extensible HyperText Markup Language">XHTML</acronym> innerHTML
	// is actually <acronym title="Extensible HyperText Markup Language">XHTML</acronym> - Opera and Safari assume that it's <acronym title="Extensible Markup Language">XML</acronym>
	if ( !moz )
		str = str.replace(/(<[a-z]+)/g, "$1 xmlns='http://www.w3.org/1999/xhtml'");
	 
	// The HTML needs to be within a XHTML element
	var div = document.createElementNS("http://www.w3.org/1999/xhtml","div");
	div.innerHTML = str;
	
	// Find the last element in the document
	var pos;
	
	// Opera and Safari treat getElementsByTagName("*") accurately
	// always including the last element on the page
	if ( !moz ) {
		pos = document.getElementsByTagName("*");
		pos = pos[pos.length - 1];
		
	// Mozilla does not, we have to traverse manually
	} else {
		pos = document;
		while ( pos.lastChild && pos.lastChild.nodeType == 1 )
			pos = pos.lastChild;
	}
	
	// Add all the nodes in that position
	var nodes = div.childNodes;
	while ( nodes.length )
		pos.parentNode.appendChild( nodes[0] );
};


FormValidator.addAllThese([
	['ajax_check', {
		errorMsg: function(element, props) { 
			if ( $type(props.ajax_check_error_msg_id) )
			{
				if ( $type($(props.ajax_check_error_msg_id)) )
				{
					return $(props.ajax_check_error_msg_id).value;
				}
			}
			return '';
		},
		test: function(element, props){
			var postdata = {};
			postdata[element.name] = element.value;

			if ( element.value == '' ) {
				return false;
			}

			var request_url = $type(props.ajax_url) ? props.ajax_url : './';
		
			var o = {
				pass: false,
				field_props: props,
				url: request_url,
				method: 'post',
				data: postdata,
				async: false,
				onComplete: function ( data ) {
						if  ( data.status == 'success' ) {
							o.pass = true;
						} else {
							if ( $type(data.message) && $type(o.field_props.ajax_check_error_msg_id) ) {
								$(o.field_props.ajax_check_error_msg_id).value = data.message;
							}
						}
					}
			};
			new Request.JSON( o ).send();

			return o.pass;
		}
	}],

	['validate-toggle-onvalue', {
		test: function(element, props){
			var fv = element.getParent('form').retrieve('validator');
			if (!fv) return true;
			var eleArr = props.toToggle || $(props.toToggleChildrenOf).getElements('input, select, textarea');
			if (!element.value == props.matchValue ){
				eleArr.each(function(item){
					fv.ignoreField(item);
					fv.resetField(item);
				});
			} else {
				eleArr.each(function(item){
					fv.enforceField(item);
				});
			}
			return true;
		}
	}]
]);

/*
FormValidator.addAllThese([

	['validate-enforce-oncheck', {
		test: function(element, props){
			if (element.checked){
				var fv = element.getParent('form').retrieve('validator');
				if (!fv) return true;
				(props.toEnforce || $(props.enforceChildrenOf).getElements('input, select, textarea')).map(function(item){
					fv.enforceField(item);
				});
			}
			return true;
		}
	}],
*/

FormValidator.add('phone', {
	errorMsg: FormValidator.getMsg.pass('phone'),
	test: function(element){
		return (/^[\d]{8,}$/.test(element.get('value')));
	}
});

FormValidator.MyTips = new Class({
	Extends: FormValidator.Tips,
	options: {
		evaluateFieldsOnBlur: false,
		evaluateFieldsOnChange: false
	},
	makeAdviceItem: function(className, field, error, warn){
		//console.info('makeAdviceItem');
		var validClassName = className;
		if (!error && !warn) return;
		var advice = this.getAdvice(field);
		var errorMsg = this.makeAdviceMsg(field, error, warn);
		if (advice && advice.msgs[className]) return advice.msgs[className].set('html', errorMsg);
		return new Element('li', {
			'html': errorMsg,
			'class': validClassName,
			'display': 'none'
		});
	}
});


var frontendFormValidatorTips = new Class({
	Implements: [Options],

	options: {
		form_name: '',
		url: '',
		method: 'post',
		ajax: true
	},
	initialize: function(options){
		this.setOptions(options);
		this.instance = this;
	},
	install: function( my_o ) {
		var o = {};
		o.form_name = this.options.form_name;
		o.url = this.options.url;
		o.method = this.options.method;
		o.ajax = this.options.ajax;

		o.pass_callback = function( ) {
			var f = $(o.form_name);

			if ( o.ajax ) {
				showLoadingWin();

				f.set('send', {url: o.url, method: o.method, onComplete: o.onComplete});
				f.send(); 
			} else {
				f.method=o.method;
				f.action=o.url;
				f.submit(); 
			}
		};

		o.onComplete = function() {
			var text = this.response.text;
			var data = JSON.decode(text); 

			hideLoadingWin();

			if ( data.status == 'success' ) {
				if ( o.success != null) {
					o.success( data );
				}
			} else if ( data.status == 'fail' ) {
				if ( o.success != null) {
					o.fail( data );
				}
			}
		}

		o.success = function( data ) {};
		o.fail = function( data ) {};
//		o.onElementValidate = function (isValid, field, className, warn) {
//		}

		
		o = $merge( o, my_o );
		this.options = o;

		
		o.validator = new FormValidator.MyTips(this.options.form_name, {
			onFormValidate: function (pass, form, onsubmit) {
				if ( pass && o.pass_callback != null) {
					o.pass_callback( o );
				}
			},
//			onElementValidate: function(isValid, field, className, warn) {
//				o.onElementValidate(isValid, field, className, warn);
//			},
			onElementFail:function(field, validatorsFailed) {
				// == only display first failed validator ====
				var pointytips = field.retrieve('PointyTip');
				pointytips.show();
				pointytips.win.setStyle('visibility', 'visible');
				pointytips.win.setStyle('display', '');
				pointytips.win.setStyle('opacity', '1');
				pointytips.win.getElements('li').each ( function (e) {e.style.display='none';}  );
				pointytips.win.getElements('li.'+validatorsFailed[0]).each ( function (e) {e.style.display='block';}  );
				pointytips.position();
			},
			serial: true,
			pointyTipOptions: {
				pointyOptions: {
					theme: 'pink',
					themes: {
							pink: {
								bgColor: '#FF99CC',
								fgColor: '#CC00CC',
								imgset: 'pink'
							}
						},
					//closeButton: false,
					baseHref: $('Path_httpRoot').value+'images/'
				}
			}
		});

		this.FormValidator = o.validator;
	}
});
function FormValidatorSetup() {

	MooTools.lang.set('en-US', 'frontend_lang_text', {
		error: 'Error'
	});
	MooTools.lang.set('zh-TW', 'frontend_lang_text', {
		error: '錯誤'

	});
	MooTools.lang.set('zh_CN', 'frontend_lang_text', {
		error: '错误'
	});

	MooTools.lang.set('zh-TW', 'Form.Validator', {

		required:'必須填寫這個欄位',
		minLength:'請輸入不少於{minLength}個字元(已輸入{length}個字元)',
		maxLength:'請輸入不多於{maxLength}個字元(已輸入{length}個字元)',
		integer:'只限輸入整數，不允許輸入小數(例如: 1.25)',
		numeric:'只限輸入數字(例如: "1" 或 "1.1" 或 "-1" 或 "-1.1" 等)',
		digits:'只限使用數字及標點符號(例如: 包含破折號或點之電話號碼)',
		alpha:'只限使用英文字母(a-z)， 不容許空格或其他字元',
		alphanum:'只限使用英文字母(a-z)或數字(0-9)，不容許空格或其他字元',
		dateSuchAs:'請輸入有效的日期,例如{date}',
		dateInFormatMDY:'請使用有效的日期格式(MM/DD/YYYY)， 例如: "12/31/1999"',
		email:'請使用有效的電郵， 例如: "fred@domain.com"',
		url:'請使用有效的網址， 例如:http://www.google.com',
		currencyDollar:'請輸入有效的$數額，例如 $100.00',
		oneRequired:'請最少輸入這幾個欄位中其中一個',
		errorPrefix: '錯誤: ',
		warningPrefix: '警告: ',
		phone:'請使用正確的電話號碼，只限使用數字，例如: 98765432, 13141234567',

		//FormValidator.Extras

		noSpace: 'There can be no spaces in this input.',
		reqChkByNode: 'No items are selected.',
		requiredChk: 'This field is required.',
		reqChkByName: 'Please select a {label}.',
		match: '這個欄位必須與{matchName}相同',
		startDate: 'the start date',
		endDate: 'the end date',
		currendDate: 'the current date',
		afterDate: 'The date should be the same or after {label}.',
		beforeDate: 'The date should be the same or before {label}.',
		startMonth: 'Please select a start month',
		sameMonth: 'These two dates must be in the same month - you must change one or the other.'

	});


	MooTools.lang.set('zh-CN', 'Form.Validator', {

		required:'必须填写这个栏位',
		minLength:'请输入不少于{minLength}个字元(已输入{length}个字元)',
		maxLength:'请输入不多于{maxLength}个字元(已输入{length}个字元)',
		integer:'只限输入整数，不允许输入小数(例如: 1.25)',
		numeric:'只限输入数字(例如: "1" 或 "1.1" 或 "-1" 或 "-1.1" 等)',
		digits:'只限使用数字及标点符号(例如: 包含破折号或点之电话号码)',
		alpha:'只限使用英文字母(a-z)， 不容许空格或其他字元',
		alphanum:'只限使用英文字母(a-z)或数字(0-9)，不容许空格或其他字元',
		dateSuchAs:'请输入有效的日期,例如{date}',
		dateInFormatMDY:'请使用有效的日期格式(MM/DD/YYYY)， 例如: "12/31/1999"',
		email:'请使用有效的电邮， 例如: "fred@domain.com"',
		url:'请使用有效的网址， 例如:http://www.google.com',
		currencyDollar:'请输入有效的$数额，例如 $100.00',
		oneRequired:'请最少输入这几个栏位中其中一个',
		errorPrefix: '错误: ',
		warningPrefix: '警告: ',
		phone:'請使用正確的電話號碼，只限使用數字，例如: 98765432, 13141234567',

		//FormValidator.Extras

		noSpace: 'There can be no spaces in this input.',
		reqChkByNode: 'No items are selected.',
		requiredChk: 'This field is required.',
		reqChkByName: 'Please select a {label}.',
		match: '这个栏位必须与{matchName}相同',
		startDate: 'the start date',
		endDate: 'the end date',
		currendDate: 'the current date',
		afterDate: 'The date should be the same or after {label}.',
		beforeDate: 'The date should be the same or before {label}.',
		startMonth: 'Please select a start month',
		sameMonth: 'These two dates must be in the same month - you must change one or the other.'

	});

	MooTools.lang.set('en-US', 'Form.Validator', {
		phone:'Please use a correct phone number, only allows digits，e.g.,: 98765432, 13141234567'
	});


	var lang = 'zh-TW';
	switch( $('FRONTEND_LANG').value ) {
		case 'en':		lang = 'en-US';		break;
		case 'tc':		lang = 'zh-TW';		break;
		case 'sc':		lang = 'zh-CN';		break;
	}
	MooTools.lang.setLanguage( lang );

}

Request.MYHTML = new Class({

	Extends: Request.HTML,

	options: {
		update: false,
		append: false,
		evalScripts: true,
		filter: false
	},

	success: function(text){
		var options = this.options, response = this.response;

		document_write_text = [];

		var reg1 = /(<script[^>]*>)([\s\S]*?)(<\/script>)/ig;
		var reg2 = /(<script)([^>]*?)(>)([\s\S]*?)(<\/script>)/i;
		var m = text.match(reg1);
		text = text.replace(/document.write/ig, "document_write");

		if (m) {
			for (var i =0;  i<m.length; i++)
			{
				text = text.replace(reg2, "<span id=\"script"+i+"\"></span>\n<ZZZscript$2$3\nscript_id="+i+";if (!document_write_text[script_id]){document_write_text[script_id]='';};\n$4</ZZZscript>");
			}
			text = text.replace(/ZZZscript/ig, "script");
		}


		response.html = text.stripScripts(function(script){
			response.javascript = script;
		});

		var temp = this.processHTML(response.html);

		response.tree = temp.childNodes;
		response.elements = temp.getElements('*');

		if (options.filter) response.tree = response.elements.filter(options.filter);
		if (options.update) $(options.update).empty().set('html', response.html);
		else if (options.append) $(options.append).adopt(temp.getChildren());
		if (options.evalScripts) $exec(response.javascript);

		document_write_commit();

		this.onSuccess(response.tree, response.elements, response.html, response.javascript);
	}

});

document_write_text = {};
function document_write(s) {
	if ( !document_write_text[script_id] ) {
		document_write_text[script_id] = '';
	}
	document_write_text[script_id] += s;
}

function document_write_commit() {
	var e;
	for (var i =0; i<document_write_text.length; i++ ) {
		e = $('script'+i);
		if ( e ) {
			e.innerHTML = document_write_text[i];
		}
		
	}
}

function showLoadingWin() {
//	if (!window.loading_win) 
	{
		window.loading_win = StickyWin.MyAlert( '<span style="font-size:22pt;line-height:30px;">Loading...</span>', 'loading', function(){}, {hideOnClick: false} );
	}
	//window.loading_win.show();
}
function hideLoadingWin() {
	window.loading_win.hide();
}

function ajaxUpdateMainContent( url ) {
	if ( !$('FRONTEND_USE_AJAX') || $('FRONTEND_USE_AJAX').value != '1' )
	{
		window.location.href = url;
		return;
	}
	
	var uri = url.toURI();
	var q = uri.get('query') || 'd=1';
	var ajax_url = uri.get('directory')+uri.get('file')+'?'+ q
	if ( !q.match(/ajax_content=1/) )
	{
		ajax_url+= '&ajax_content=1';
	}
	ajax_url+= '&random=' + (new Date()).valueOf();
	//alert(ajax_url);
	//window.open(ajax_url, "_blank");
	//uri.get('fragment')

	$('FRONTEND_LAST_AJAX_URL').value = url;
	showLoadingWin();
	var o = {url:ajax_url, evalScripts: false /*, update: $('page_main_content')*/ };
	o.onSuccess = function(responseTree, responseElements, responseHTML, responseJavaScript) { 
		hideLoadingWin();

		if ($('FRONTEND_LAST_AJAX_URL').value.match(/(mem_area\.php)|(checkout\.php)|(check_confirm\.php)/ig))
		{
			ajax_update_sidebar_memarea();
		}
		//console.info(responseTree);
		//console.info(responseElements);
		//console.info(responseHTML);
		//console.info(responseJavaScript);
		$('page_main_content').set('html', responseHTML);

		window.jim = {};
		window.jim.js = responseJavaScript;
		//$('jim1').value = responseJavaScript;
		$exec(responseJavaScript);
		
		frontend_ajax_OnLoad();

		var myFx = new Fx.Scroll(window).toElement('page_main_content');
	};

	var myHTMLRequest = new Request.MYHTML(o).get();
	//$('page_main_content').load( ajax_url );
}

function frontendOnLoad() {
	FormValidatorSetup();

	$('FRONTEND_USE_AJAX').value = '1';

	$$('a').each( function (el) {
		var target = el.getAttribute('target');
		
		if ( target == null || target == '' || target =='self') {
			var href = el.getAttribute('href');
			if ( !!href && !href.match(/javascript:/ig) ) {
				var re = new RegExp("^http://"+ window.location.hostname, "i");
				var re2 = new RegExp("^http://",  "i");
				href = href.replace(re, '');
				if ( href.match(re2) ) {
					return;
				}

				href = "javascript:ajaxUpdateMainContent('" + href + "');";
				el.setAttribute('href', href);
			}
		}
	});
}
function frontend_ajax_OnLoad(el) {
//	FormValidatorSetup();
	if( typeof(RabidRatings) != 'undefined') {
		var rating = new RabidRatings({url:$('Path_httpRoot').value+'lib/ratings/ratings.php'});
	}
	el = el || $('page_main_content');
	el.getElements('a').each( function (el) {
		var target = el.getAttribute('target');
		
		if ( target == null || target == '' || target =='self') {
			var href = el.getAttribute('href');
			if ( !!href && !href.match(/javascript:/ig ) ) {
				var re = new RegExp("^http://"+ window.location.hostname, "i");
				var re2 = new RegExp("^http://",  "i");
				href = href.replace(re, '');
				if ( href.match(re2) ) {
					return;
				}

				href = "javascript:ajaxUpdateMainContent('" + href + "');";
				el.setAttribute('href', href);
			}
		}
	});
}


window.addEvent("domready", frontendOnLoad);

//  ajaxUpdateMainContent('content.php?id=0');

