/* contact.html */

$.cookie('lang', 'en');

var yourname_flag = false;
var email_flag = false;
var subject_flag = false;
var description_flag = false;

$(document).ready(function() {
	$('form').submit(function() {
		// 檢查your name欄位
		if ($(':text:eq(0)').val() == '') {
			$('#yourname_msg').addClass('msg').text('Please enter your name.').show();
			yourname_flag = false;
		}
		else {
			$('#yourname_msg').hide();
			yourname_flag = true;
		}

		// 檢查email欄位
		if ($(':text:eq(1)').val() == '') {
			$('#email_msg').addClass('msg').text('Please enter your email.').show();
			email_flag = false;
		}
		else {
			var emailReg = /^[\w\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z\.]{2,6}$/;
			if (!emailReg.test($(':text:eq(1)').val())) {
				$('#email_msg').addClass('msg').text('It is not an email format, please enter again.').show();
				email_flag = false;
			}
			else {
				$('#email_msg').hide();
				email_flag = true;
			}
		}

		// 檢查subject欄位
		if ($(':text:eq(2)').val() == '') {
			$('#subject_msg').addClass('msg').text('Please enter a subject.').show();
			subject_flag = false;
		}
		else {
			$('#subject_msg').hide();
			subject_flag = true;
		}

		// 檢查description欄位
		if ($('textarea').val() == '') {
			$('#description_msg').addClass('msg').text('Please enter the description.').show();
			description_flag = false;
		}
		else {
			if (nowChr < 0) {
				$('#description_msg').addClass('msg').text('Description can not exceed the maximum character of 2,000.').show();
				description_flag = false;
			}
			else {
				$('#description_msg').hide();
				description_flag = true;
			}
		}

		if (yourname_flag && email_flag && subject_flag && description_flag) {
			$.ajax({
				url: 'php/contact_us.php',
				type: 'POST',
				cache: false,
				data: {'yourname': $(':text:eq(0)').val(), 'email': $(':text:eq(1)').val(), subject: $(':text:eq(2)').val(), 'description': $('textarea').val(), 'lang': $.cookie('lang')},
				success: function(data) {
					if (data == 'ERROR') {
						$('#email_msg').addClass('msg').text('Sorry, we are having trouble to send email. Please try again later.').show();
					}
					else if (data == 'EMAIL_FORMATERROR') {
						$('#email_msg').addClass('msg').text('It is not an email format, please enter again.').show();
					}
					else if (data == 'OK') {
						$('#contact_text').hide();
						$('#contact_sent').show();
					}
				}
			});
		}

		return false;
	});

});

var nowChr = 0;

// 計算可輸入剩餘字數
function count(value) {
	nowChr = 2000 - value.length;
	$('#count_char').text(nowChr);
	if (nowChr < 0) {
		$('#count_char').addClass('count_character');
		$('#description_msg').addClass('msg').text('Description can not exceed the maximum character of 2,000.').show();
	}
	else {
		$('#count_char').removeClass('count_character');
		$('#description_msg').hide();
	}
}
