/*
* @version : 2.1
* @update : 2009-08-17
*/
/* exten jquery function */
function clean_username (username) {
	username = username.toLowerCase();
	return (username || "").replace(/\s/g, "" );
}

function clean_whitespace( text ) { // remove all space
	return (text || "").replace(/\s/g, "" );
}

function clean_url( url ) { // add url protocal
	if(url) {
		var regexp = /(ftp|http|https):\/\/?/;
		if (!regexp.test(url)) {
			url = "http://"+url;
		}
	}

	return (url || "").replace(/\s/g, "" );
}

function clean_email( email ) {
	email = email.toLowerCase();
	return (email || "").replace(/\s/g, "" );
}

function key_digit(e) {
	var KeyCode = (e.keyCode) ? e.keyCode : e.which;
	var CharCode = (e.charCode) ? e.charCode : 0;
	CharCode = (BrowserDetect.browser=="Explorer") ? -1 : CharCode;
	return ((KeyCode == 8) // backspace
		|| (KeyCode == 9) // tab
		|| (KeyCode == 37) // left arrow
		|| (KeyCode == 39) // right arrow
		|| ((KeyCode == 46) && (CharCode == 0)) // delete
		|| (CharCode == 0)
		|| ((KeyCode > 47) && (KeyCode < 58)) // 0 - 9
	);
}

function FormatCurrency(num) {
	//alert("currency format");
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	//eturn (((sign)?'':'-') + '$' + num + '.' + cents);
	return (((sign)?'':'-') + num);
}

function validateField(field) {
	var error = false;

	// remove whitespace
	$(field).val( jQuery.trim( $(field).val() ) );

	// username field
	if ( $(field).hasClass("username") ) {
		$(field).val( clean_username( $(field).val() ) );
	}
	// email field
	if ( $(field).hasClass("email") ) {
		$(field).val( clean_email( $(field).val() ) );
	}
	// url field
	if ( $(field).hasClass("url") ) {
		$(field).val( clean_email( $(field).val() ) );
	}

	// required fields
	if ($(field).attr("class").indexOf("required") != -1) {
		if (!$(field).val().length)
			error = true;
	}
	// numeric fields
	if ($(field).val().length && $(field).hasClass("numeric") ) {
		if (!/^[0-9]*$/.test($(field).val()))
			error = true;
	}
	// emails
	if ($(field).val().length && $(field).hasClass("email") ) {
		if (!/^[a-zA-Z0-9]{1}([\._a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+){1,3}$/.test($(field).val()))
			error = true;
	}
	// url
	if ($(field).val().length && $(field).hasClass("url") ) {
		if (!/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test($(field).val()))
			error = true;
	}

	if (error) {
		$(field).addClass("focus");
	} else {
		$(field).removeClass("focus");
	}

	return !error;
}

//
function validUsername(value) {
	try {
		var rs = (/^[a-zA-Z0-9]{1}([a-zA-Z0-9]|_){5,19}$/.test(value));
		//var rs = (/^[a-zA-Z0-9]{1}([a-zA-Z0-9]|_|-|@|\.){4,18}[a-zA-Z0-9]{1}$/.test(value));
		//var rs = (/^[a-zA-Z0-9]{5,20}$/.test(value));
		return rs;
	} catch (e) {}
	return false;
}

function validPhone(value) {
	try {
		var rs_tel = (/^[0]{1}[0-79]{1}[0-9]{7}$/.test(value));
		var rs_mobile = (/^[0]{1}[8]{1}[0-9]{8}$/.test(value));
		return (rs_tel || rs_mobile);
	} catch (e) {}
	return false;
}

$.fn.clearForm = function() {

	// iterate each matching form
	return this.each(function(){
		// iterate the elements within the form
		$(":input", this).each(function(){
			var type = this.type, tag = this.tagName.toLowerCase();
			if (type == "text" || type == "password" || tag == "textarea")
				this.value = "";
			else if (type == "checkbox" || type == "radio")
				this.checked = false;
			else if (tag == "select")
				this.selectedIndex = -1;
		});
	});
};


function valid_char(str, maxlength) {
	var total=0;
	maxlength = parseInt(maxlength);
	if ( maxlength > 0 ) {
		var str_ir = 'ั'+'ํ'+'่'+'๋'+'ี'+'ึ'+'ื'+'ิ'+'๊'+'้'+'็'+'ุ'+'ู';
		var str_len = 0;
		for(i=0; i<str.length; i++) {
			var char_code = str.substr(i, 1);

			//if (char_code == 'ั' || char_code == '' || char_code == '' || char_code == '' || char_code == '' || char_code == '' || char_code == '' || char_code == '' || char_code == '' || char_code == '' || char_code == '' || char_code == '' ) {
			if (str_ir.indexOf(char_code) != -1) {
				total++;
			} else {
				str_len++;
			}
			if ( str_len == maxlength ) break;
		}

		return str.substr(0, maxlength+total);
	} else {
		return str;
	}
}

function blockPage() {
	$.blockUI({ message: ( get_lang()=="en" ? "<h1>Please wait.</h1>" : "<h1>กรุณารอสักครู่ ระบบกำลังจัดเก็บข้อมูลค่ะ</h1>") , css: { backgroundColor: "transparent", color: "#333333", padding: "0px 0px 50px 0px" } });
}

function init_tooltip( instant, style, param_type, pos_target, pos_tooltip, pos_adject_x, pos_adject_y) {

	pos_adject_x = parseInt(pos_adject_x);
	if ( isNaN(pos_adject_x) ) pos_adject_x = 0;
	pos_adject_y = parseInt(pos_adject_y);
	if ( isNaN(pos_adject_y) ) pos_adject_y = 0;

	$(instant).qtip({
		content: {
			url: 'api/tooltip.php',
			data: { type: param_type },
			method: 'get'
		},
		position: {
			corner: {
				target: pos_target, // Position the tooltip above the link
				tooltip: pos_tooltip
			},
			adjust: { x: pos_adject_x, y: pos_adject_y }
		},
		// Effects
		show: {
			delay: 100
		},
		hide: {
			delay: 0, fixed: true
		},
		style: style
	});
}

function bindProvince(province, amphur) {

	var optiondefault = '<option value=""></option>' ;
	var optionloading = '<option>loading...</option>' ;

	if ( parseInt($(amphur).val()) == 0 || isNaN(parseInt($(amphur).val())) ) {
		$(amphur).attr("disabled", "disabled");
	}

	$(province).bind("change", function() {

		$(amphur).attr("disabled", "disabled");

		if ( !$(this).val() ) {
			$(amphur).html(optiondefault);
		} else {
			$(amphur).html(optionloading);

			$.getJSON("api/address.php", {action: "amphur", id: $(this).val()}, function(data) {
				var options = optiondefault ;
				for (var i=0; i<data.length; i++) {
					options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
				}
				$(amphur).html(options);
				$(amphur).attr("disabled", "");
				$(amphur).focus();
			});
		}
	});
}

function get_lang() {
	return ( $("body").hasClass("en") ? "en" : "th" );
}

$(document).ready(function(){

	// Global Element
	$("a").each( function() {
		if ($(this).attr("href") == undefined || $(this).attr("href") == "#" || $(this).attr("href") == "") {
			if ( $(this).parent().parent().parent().attr("id") != "menu" ) {
				$(this).attr({href:"#"});
				//$(this).css("cursor", "default");
				$(this).click( function(e) { e.preventDefault(); });
			}
		}
		$(this).focus( function() { $(this).blur(); });
	});
	$("input[type=submit], input[type=reset], input[type=button], input[type=select], input[type=image], input[type=radio], input[type=checkbox]" ).each( function() {
		$(this).focus( function() { $(this).blur(); });
	});

	// handle select text
	$("input[type=text], textarea").each( function() {
			if ( $(this).hasClass("username") || $(this).hasClass("number") || $(this).hasClass("amount") ) {
				$(this).attr("autoComplete", "Off");
			}
			$(this).focus( function() {
				$(this).select();
				if ( !$(this).hasClass("focus") ) $(this).addClass("focus");
			});

			if( $(this).hasClass("username") ) {
				$(this).blur( function() {
					$(this).val( clean_whitespace($(this).val()) );
					$(this).removeClass("focus");
				});
			} else {
				$(this).blur( function() {
					$(this).val( jQuery.trim( $(this).val() ) );
					$(this).removeClass("focus");
				});
			}
	});
	$("input[type=password]", this).each( function() {
		$(this).focus( function() {
			$(this).select();
			if ( !$(this).hasClass("focus") ) $(this).addClass("focus");
		});
		$(this).blur( function() {
			$(this).removeClass("focus");
		});
	});


	$("div#Copyright a").each(function(){
		$(this).click(function(e){
			e.preventDefault();
			if(tb_show) {
				tb_show("", $(this).attr("href")+"?keepThis=true&TB_iframe=true&height=500&width=600", "");
			}
		});
	});

	/*if($("form#frmLogin").length > 0) {
		$("form#frmLogin").each( function() {
			$(this).submit(function(){
				var validationError = false;
				$("input[type=text], input[type=password]", this).each( function() {
					if ($(this).attr("class")) {
						if (!validateField(this)) validationError = true;
					}
				});

				if ( validationError==true && $("form#frmLogin input#Username").hasClass("focus") ) {
					alert("Please enter your username.");
					$("form#frmLogin input#Username").focus();
				} else if ( validationError==true && $("form#frmLogin input#Password").hasClass("focus") ) {
					alert("Please enter your password.");
					$("form#frmLogin input#Password").focus();
				}
				return !validationError;
			});

		});

	}*/


	/*if ( $("div#footerCoin").length > 0 ) {
		$("div#footerCoin").flash({
				src: "flash/coin.swf",
				width: 700, height: 40,
				name: "bnHome",
				wmode: "transparent", menu: "false",
				flashvars: { file: "" }
			}, { version: 8 }
		);
	}*/
	if ( $("div#footerCoin").length > 0 ) {
		$("div#footerCoin").flash({
				src: "flash/text-footer.swf",
				width: 800, height: 40,
				wmode: "transparent", menu: "false",
				flashvars: { lang: get_lang() }
			}
		);
	}

	if ( $("div#swfBalloon").length > 0 ) {
		var meta = $("div#swfBalloon").metadata();
		if ( meta.flashvars.close_hour == undefined ) meta.flashvars.close_hour = "0";
		if ( meta.flashvars.close_min == undefined ) meta.flashvars.close_min = "0";
		if ( meta.flashvars.close_ms == undefined ) meta.flashvars.close_ms = "0";

		$("div#swfBalloon").flash({
				src: "flash/balloon.swf",
				width: 220, height: 115,
				wmode: "transparent", menu: "false",
				flashvars: { close_hour: meta.flashvars.close_hour, close_min: meta.flashvars.close_min, close_ms: meta.flashvars.close_ms }
		});
	}

	$("div.Shortcuts a#mnLogin").click(function(e){ e.preventDefault(); });
	$("div.Shortcuts a#mnLogout2").click(function(e){ e.preventDefault(); });

	if ( $("div#plCart").length > 0 ) {

		//setInterval(1000,function(){$("div#plCart div.Note div.note_m label").fadeOut(100).fadeIn(100);});
		$("div#plCart div.Note div.note_m div").everyTime( 3000, "controlled_storenote", function(){ $("div#plCart div.Note div.note_m div").fadeOut(100).fadeIn(100).fadeOut(150).fadeIn(150); } );

		// Update
		$("div#plCart a.btEdit").each( function() {
			$(this).click(function(e) {
				e.preventDefault();
				var meta = $.metadata.get(this);

				if ( $("div#modelMenuOption").length > 0 ) $("div#modelMenuOption").remove();
				$.ajax({
					url: "api/popup.php",
					data: "action=add_cart_option&mode=update&code="+meta.code,
					type: 'get',
					cache: false,
					dataType: "html",
					complete: function (result) {
						if ( result.responseText != "0" ) {
							$("body").append( result.responseText );
							bindFormCart();
							menu_option( function() {});
						}
					}
				});

			});
		});

		// Remove
		$("div#plCart a.btCancel").each( function() {
			$(this).click(function(e) {
				e.preventDefault();
				 $(this).closest("div.Item").fadeOut()
				var meta = $.metadata.get(this);
				$.ajax({
					url: "api/cart.php",
					data: "action=remove&code="+meta.code,
					type: "get",
					cache: false,
					dataType: "html",
					complete: function (result) {
						document.location.reload();
					},
					error: function(result) {
						document.location.reload();
						//alert(result.statusText);
					}
				});
			});
		});

		// Increase
		$("div#plCart a.btIncrease").each( function() {
			$(this).click(function(e) {
				e.preventDefault();
				var meta = $.metadata.get(this);
				$.ajax({
					url: "api/cart.php",
					data: "action=increase&code="+meta.code,
					type: "get",
					cache: false,
					dataType: "html",
					complete: function (result) {
						if ( result.responseText != "0" ) {
							document.location.reload();
						}
					},
					error: function(result) {
						document.location.reload();
						//alert(result.statusText);
					}
				});
			});
		});

		// Decrease
		$("div#plCart a.btDecrease").each( function() {
			$(this).click(function(e) {
				e.preventDefault();
				var meta = $.metadata.get(this);
				$.ajax({
					url: "api/cart.php",
					data: "action=decrease&code="+meta.code,
					type: "get",
					cache: false,
					dataType: "html",
					complete: function (result) {
						if ( result.responseText != "0" ) {
							document.location.reload();
						}
					},
					error: function(result) {
						document.location.reload();
						//alert(result.statusText);
					}
				});
			});
		});

		// Checkout
		$("div#plCart input.btCheckOut").each( function() {
			$(this).click(function(e) {
				e.preventDefault();
				//คุณสั่งอาหารจากร้าน KFC ไม่ถึง 120 บาท (ไม่รวมค่าจัดส่ง)
				//Your KFC orders price less than 120 baht. (Don't include delivery charge)

				$.ajax({
					url: "api/cart.php",
					data: 'action=chk_min_price',
					type: "get",
					cache: false,
					dataType: "text",
					complete: function (result) {
						if ( result.responseText == "1" ) {

							// Check Recommend Menu
							$.ajax({
								url: "api/cart.php",
								data: "action=chk_checkout",
								type: "get",
								cache: false,
								dataType: "text",
								complete: function (result) {
									if ( result.responseText == "12" ) { // Show Supersave
										bindMenuCheckout();
									} else if ( result.responseText == "11" ) { // Show Error Minimum Price (Virtual Money)
										$.get("api/cart.php", { action: "get_virtualmoney_min_price" }, function(data){
											bindErrorMessage("Notice", "ราคารวมรายการอาหารไม่ถึง "+parseInt(data)+" บาท<br />เพื่อใข้สิทธิ Virtual Money ค่ะ");
										});

									} else {
										location.href = 'ordering.php';
										// action=add_cart_option&id=117
									}
								},
								error: function(result) {
									location.href = 'ordering.php';
								}
							});

						} else {
							if ( $("body").hasClass("en") ) {
								bindErrorMessage("Notice", "Your KFC orders price less than 120 baht. (Don't include delivery charge)");
							} else {
								bindErrorMessage("Notice", "คุณสั่งอาหารจากร้าน KFC ไม่ถึง 120 บาท (ไม่รวมค่าจัดส่ง)");
							}
						}

					},
					error: function(result) {
						//alert(result.statusText);
					}
				});

			});
		});

		// Fixed Height
		if ( $("div#cLeft").height() > $("div#cRight").height() ) {
			$("div.BG").css("height", $("div#cLeft").height() + 80)
		}
	}

});
