/*
* @version : 2.9.4
* @update : 2010-01-27
*/
function plProfileTop_Height() {
	if ( $("div#cTopProfile").height() != null ) {
		return ( $("div#cTopProfile").height() > 430 ? -1*($("div#cTopProfile").height() + 70) : -500);
	} else {
		return -500;
	}
}

function insertOverlay() {
	$("div.qtip").hide();
	if($("div#bg-overlay").length == 0) {
		$('<div id="bg-overlay"></div>').appendTo('body');
		$("div#bg-overlay").bgiframe();
	}

}

function destroyOverlay() {
	//console.log( $("div#simplemodal-container").css("display")  );
	if ( $("div#simplemodal-container").css("display") != "block" ) {
		$("div#bg-overlay").each(function() { $(this).remove(); } );
	}
}

function closeLoginTop() {
	if ( $("div#navTop div.Shortcuts").css("display") == "none" || parseInt($("div#cTopLogin").css("top")) == 0) {
		$("div#navTop div.Shortcuts").fadeIn(10);
		//$("div#Home div#bannerMain").show();
		$("div#cTopLogin").animate(
			{ top: -350 }, {
			queue: false, duration: 300,
			complete:function(callback){
				destroyOverlay();
				$(document).unbind("mousemove");
			}
		});
	}
}

function hideProfileTop() {
	if ( $("div#navTop div.Shortcuts").css("display") == "none" || parseInt($("div#cTopProfile").css("top")) == 0) {
		$("div#navTop div.Shortcuts").fadeIn(10);
		//$("div#Home div#bannerMain").show();
		$("div#cTopProfile").animate( { top: plProfileTop_Height() }, { queue: false, duration: 300, complete:function() { destroyOverlay(); $(document).unbind("mousemove");} } );
	}
}

function openProfileTop() {
	insertOverlay();

	$("div#navTop div.Shortcuts").fadeOut(10);
	//$("div#Home div#bannerMain").hide();
	$("div#cTopProfile").animate( { top: 0 },
		{
		queue: false, duration: 400,
		complete: function() {
			$("div.qtip").hide();
			$(document).bind("mousemove", function(e) {

				//alert('hideProfileTop: '+e.pageY+', '+$("div#cTopProfile").css("height"))
				if (e.pageY > parseInt($("div#cTopProfile").css("height")) ) {
					hideProfileTop();
				}
			});

		}
	});
}

function closeProfileTop(callback) {
	/*if ( $("div#navTop div.Shortcuts").css("display") == "none" || parseInt($("div#cTopProfile").css("top")) == 0) {
		$("div#navTop div.Shortcuts").fadeIn(10);
		$("div#cTopProfile").animate( { top: -450 }, { queue: false, duration: 300, complete:function(){ destroyOverlay(); $(document).unbind("mousemove");} } );
	}*/

	if ( $("div#navTop div.Shortcuts").css("display") == "none" || parseInt($("div#cTopProfile").css("top")) == 0) {
		$("div#navTop div.Shortcuts").fadeIn(10);
		//$("div#Home div#bannerMain").show();
		$("div#cTopProfile").animate(
			{ top: plProfileTop_Height() }, {
			queue: false, duration: 300,
			complete: function(){
				//destroyOverlay();
				$(document).unbind("mousemove");
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
			}
		});
	}
}

function closeProfileView(callback) {
	$("div#cProfileView").fadeOut("fast", function() {
		$('html, body').animate({scrollTop:0}, 'slow');
		$("div#cProfileView").remove();
		destroyOverlay();

		// call the callback
		if ($.isFunction(callback)) {
			callback.apply();
		}
	});
}

function closeProfileEdit(callback) {
	$("div#cProfileEdit").fadeOut("fast", function() {
		$('html, body').animate({scrollTop:0}, 'slow');
		destroyOverlay();
		$("div#cProfileEdit").remove();
		// call the callback
		if ($.isFunction(callback)) {
			callback.apply();
		}
	});
}

function closeDeliveryAddress() {
	$("div#cDeliveryAddress").fadeOut("fast", function() {
		$('html, body').animate({scrollTop:0}, 'slow');
		$("div#cDeliveryAddress").remove();
		destroyOverlay();
	});
}

function closeTaxAddress() {
	$("div#cTaxAddress").fadeOut("fast", function() {
		$('html, body').animate({scrollTop:0}, 'slow');
		$("div#cTaxAddress").remove();
		destroyOverlay();
	});
}

function saveProfile() {
	$("div#cProfileEdit").fadeOut("fast", function() {
		$('html, body').animate({scrollTop:0}, 'slow');
		$("div#cProfileEdit").remove();
		destroyOverlay();
		bindDisplayMessage("ระบบได้รับข้อมูลของท่านแล้ว", "หากเป็นการแก้ไขที่อยู่ ท่านจะได้รับเมล์เพื่อยืนยันที่อยู่ที่เพิ่มเติมหรือแก้ไข ภายใน 1 ชม ถ้าไม่ได้รับกรุณาติดต่อ 1150");
	});
}

function saveDeliveryAdddress() {
	$("div#cDeliveryAddress").fadeOut("fast", function() {
		$('html, body').animate({scrollTop:0}, 'slow');
		$("div#cDeliveryAddress").remove();
		destroyOverlay();
		bindDisplayMessage("ท่านจะได้รับเมล์เพื่อยืนยันที่อยู่ที่เพิ่มเติมหรือแก้ไข ภายใน 1 ชม ถ้าไม่ได้รับกรุณาติดต่อ 1150", "",  function() { document.location.reload(); } );
	});
}

function saveTaxAdddress() {
	$("div#cTaxAddress").fadeOut("fast", function() {
		$('html, body').animate({scrollTop:0}, 'slow');
		$("div#cTaxAddress").remove();
		destroyOverlay();
		bindDisplayMessage("ระบบได้รับข้อมูลของท่านแล้ว", "", function() { document.location.reload(); } );
	});
}

function bindLoginTop() {

	if ( $("div#cTopLogin").length == 0 ) {
		if ($("div#navTop div.Shortcuts a#mnLogout").length == 0) {
			$.get("api/popup.php", { action: "login_top" }, function(html){
				$("div.Wrapper").prepend( html );

				bindLoginTop();
			});
		}

	} else {
		$("div#cTopLogin div#swfLoginPromotion").flash({ src: "flash/top-login_promotion.swf", width: 472, height: 200, name: "", wmode: "opaque", menu: "false" });

		$("div#navTop div.Shortcuts a#mnLogin").mouseover(function(){
			insertOverlay();

			$("div#navTop div.Shortcuts").fadeOut(10);
			//$("div#Home div#bannerMain").hide();
			$("div#cTopLogin").animate( { top: 0 },
				{
				queue: false, duration: 300,
				complete: function() {
					$("div.qtip").hide();
					$(document).bind("mousemove", function(e) {

						if (e.pageY > parseInt($("div#cTopLogin").css("height")) ) {
							closeLoginTop();
							//$("div#navTop div.Shortcuts").fadeIn(10);
							//$("div#cTopLogin").animate( { top: -350 }, { queue: false, duration: 300, complete:function(){ destroyOverlay();$(document).unbind("mousemove");} } );
						}
					});

				}
			});



			$("div#cTopLogin a.btPanelClose").each(function() {
				$(this).click(function(){
					closeLoginTop();
					//$("div#navTop div.Shortcuts").fadeIn(10);
					//$("div#cTopLogin").animate( { top: -350 }, { queue: false, duration: 300, complete: function() { destroyOverlay();} } );
					return false;
				});

				$(this).focus( function() { $(this).blur(); });
			});

		});

		$("div#navTop div.Shortcuts a#mnLogin").click(function(){ return false;} );

		/*$("div#navTop div.Shortcuts a#mnLogout").click(function(){
			insertOverlay();
			return false;
		});*/

		if($("form#frmTopLogin").length > 0) {
			$("form#frmTopLogin").each( function(){
				$(this).submit(function(e){
					e.preventDefault();
					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#frmTopLogin input#topUsername").hasClass("focus") ) {
						alert("Please enter your username.");
						$("form#frmTopLogin input#topUsername").focus();
					} else if ( validationError==true && $("form#frmTopLogin input#topPassword").hasClass("focus") ) {
						alert("Please enter your password.");
						$("form#frmTopLogin input#topPassword").focus();
					}
					if ( !validationError ) {
						$.ajax({
							url: "api/login.php",
							data: $("form#frmTopLogin").serialize(),
							type: "post",
							cache: false,
							dataType: "html",
							complete: function (result) {
								switch( result.responseText ) {
									case "1":
										/*document.location.reload();*/
										$("div#cTopLogin").animate( { top: -350 }, { queue: false, duration: 300, complete: function() { destroyOverlay(); $(document).unbind("mousemove"); bindLocation(); } } );
										break;
									case "100": alert("Please try again."); break;
									case "101":
									case "102": alert("Invalid username or password. Please try again."); break;
									case "103": alert("Your registration not complete. Please activate your account."); break;
								}
								$("form#frmTopLogin input#topUsername").focus();

							},
							error: function(result) {
								//alert(result.statusText);
							}
						});

					}
					return false;
					//return !validationError;
				});

			});

		}

	}
}

function bindEmotion() {

	$("div.Emotions a").each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			var emo =0;
			if ( $(this).hasClass("btEmotion1") ) {
				emo = 1;
			} else if ( $(this).hasClass("btEmotion2") ) {
				emo = 2;
			} else if ( $(this).hasClass("btEmotion3") ) {
				emo = 3;
			} else if ( $(this).hasClass("btEmotion4") ) {
				emo = 4;
			}
			$("div.Emotions a").removeClass("btEmotion1_active").removeClass("btEmotion2_active").removeClass("btEmotion3_active").removeClass("btEmotion4_active");

			$.get("api/member.php", { action: "set_emotion", id: emo }, function(html){
				emo = parseInt(html);
				$("div.Emotions a.btEmotion"+emo).addClass("btEmotion"+emo+"_active");
			});
		});
		$(this).focus(function() { $(this).blur(); });
	});
}

function bindProfileTop() {

	if ( $("div#cTopProfile").length == 0 ) {

		$.get("api/popup.php", { action: "profile_top" }, function(html){
			$("body").prepend( html );
			bindProfileTop();
		});

	} else {

		$.getScript("js/page-member_top.js");

		//console.log('mouseover');
		$("div#navTop div.Shortcuts a#mnProfile").mouseover(function(){
			openProfileTop();
		});

	}
}

function bindProfileView() {
	if ( $("div#cProfileView").length > 0 ) $("div#cProfileView").remove();

	$.get("api/popup.php", { action: "profile_preview" }, function(html){
		$("body").prepend( html );

		//insertOverlay();
		$.getScript("js/page-member_view.js");

	});
}

function bindProfileEdit() {
	if ( $("div#cProfileEdit").length > 0 ) $("div#cProfileEdit").remove();

	$.get("api/popup.php", { action: "profile_edit" }, function(html){
		if ( html == "offline" ) { // Web Offline
			destroyOverlay();
			bindErrorMessage("ขออภัยค่ะ", "ปิดปรับปรุงระบบชั่วคราว");

		} else {
			$("body").prepend( html );

			$.getScript("js/page-member_edit.js");
		}
	});
}

function bindDeliveryAddress() {
	if ( $("div#cDeliveryAddress").length > 0 ) $("div#cDeliveryAddress").remove();

	insertOverlay();
	$.get("api/popup.php", { action: "address_delivery" }, function(html){
		$("body").prepend( html );

		$.getScript("js/page-address_delivery.js");
	});
}

function bindTaxAddress() {
	if ( $("div#cTaxAddress").length > 0 ) $("div#cTaxAddress").remove();

	$.get("api/popup.php", { action: "address_tax" }, function(html){
		$("body").prepend( html );
		insertOverlay();
		$.getScript("js/page-address_tax.js");
	});
}

function bindEventVirtualMoney() {
	/*if ( $("div.cProfile div.VirtualMoney").length > 0 ) {
		$("div.cProfile div.VirtualMoney a").each(function(){
			$(this).click(function(e){e.preventDefault();});
			$(this).focus(function(){$(this).blur();});
		});
		$("div.cProfile div.VirtualMoney a").filter(".enable").click(function(e){
			e.preventDefault();
			bindVirtualMoney();
		});
	}*/
}

function bindVirtualMoney() {

	/*if ( $("div#cVirtualMoney").length > 0 ) $("div#cVirtualMoney").remove();

	$(document).unbind("mousemove");

	$.ajax({
		url: 'api/popup.php',
		data: "action=virtual_money",
		type: 'get',
		cache: false,
		dataType: 'html',
		complete: function (result) {
			if ( result.responseText != "0" ) {
				$("body").append( result.responseText );

				$.getScript("js/page-virtual_money.js");

			} else {
				if ( $("div#cTopProfile").length != 0 ) {
					$(document).bind("mousemove", function(e) {
						if (e.pageY > parseInt($("div#cTopProfile").css("height")) ) {
							hideProfileTop();
						}
					});
				}
				//bindErrorMessage("Notice", "ปิดการสั่งเมนูชั่วคราว<br />กรุณาลองใหม่ในวันพรุ่งนี้นะค่ะ");
			}
		},
		success: function(html){
			//$("div#VirtualMoney").empty().append(html);
			//$.getScript("js/page-member_voucher.js");
		}

	});*/
}

function delivery_address ( callback) {
	$("div#cDeliveryAddress").modal({
		close: false,
		position: ["0%",],
		overlayId: 'bg-overlay',
		onShow: function (dialog) {
			$(".qtip").hide();
		}
	});
}

function Voucher_close ( callback) {

	$("div#Choose").modal({
		close: false,
		position: ["20%",],
		persist: true,
		overlayId: 'Profile',
		containerId: 'Choose',
		onShow: function (dialog) {

			$(".qtip").hide();
			$("div#Choose input[type=checkbox]").checkbox( {empty: 'images/spacer.gif'} );

			dialog.data.find('a.modalClose').click(function (e) {
				$("div#Choose").remove();
				$.modal.close();
			});

		}
	});
}

function displayAvatar( eleName ) {
	$.get("api/member.php", { action: "get_avatar" }, function(html) {
		//alert(html)
		//imgSrc = 'uploads/member/' + $.trim(response) ;
		$(eleName+" div.Avatar div.image img").css("background-image", "url('"+html+"')");
		$(eleName).css("cursor", "");
	});
}

function openProfileView() {
	$("div#navTop div.Shortcuts").fadeIn(10);
	$("div#cTopProfile").animate({ top: plProfileTop_Height() },
		{ queue: false, duration: 300,
		complete:function() { bindProfileView(); $(document).unbind("mousemove");}
	});
}

function openProfileEdit() {
	$("div#cProfileView").fadeOut("fast", function(){
		$("div#cProfileView").remove()
		bindProfileEdit();
		//destroyOverlay();
	});
}

function bindLoginLeft() {

	if($("form#frmLeftLogin").length > 0) {
		$("form#frmLeftLogin").each( function(){
			$(this).submit(function(e){
				e.preventDefault();
				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#frmLeftLogin input#topUsername").hasClass("focus") ) {
					alert("Please enter your username.");
					$("form#frmLeftLogin input#topUsername").focus();
				} else if ( validationError==true && $("form#frmLeftLogin input#topPassword").hasClass("focus") ) {
					alert("Please enter your password.");
					$("form#frmLeftLogin input#topPassword").focus();
				}
				if ( !validationError ) {
						$.ajax({
							url: "api/login.php",
							data: $("form#frmLeftLogin").serialize(),
							type: "post",
							cache: false,
							dataType: "html",
							complete: function (result) {
								//console.log(result.responseText)
								if (  result.responseText  == "1" )  {
									bindLocation();
								} else {
									switch( result.responseText ) {
										/*case "1": document.location.reload(); break;*/
										case "100": alert("Please try again."); break;
										case "101":
										case "102": alert("Invalid username or password. Please try again."); break;
										case "103": alert("Your registration not complete. Please activate your account."); break;
									}
									$("form#frmLeftLogin input#leftUsername").focus();
								}

							},
							error: function(result) {
								//alert(result.statusText);
							}
						});

				} else {
					alert("Please enter your username and password.");
				}
				//return !validationError;
				return false;
			});

		});

		/*$("form#frmLeftLogin input.btLogin").click(function (e) {
			e.preventDefault();
			// Validate
			var validationError = false;
			$("input[type=text], input[type=password]", this).each( function() {
				console.log(  $(this).attr("id") );
				if ($(this).attr("class")) {
					if (!validateField(this)) validationError = true;
				}
			});
		});*/
	}
}

function bindLocation() {
	if ( $("div#modelConfirmLocation").length == 0 ) {
		$.get("api/popup.php", { action: "select_location" }, function(html){
			$("body").append( html );
			//alert(html)
			bindLocation();
		});

	} else {
		$("div#navTop div.Shortcuts").fadeIn(10);

		$("form#frmConfirmLocation input[type=radio]").checkbox( {empty: 'images/spacer.gif'} );

		$("form#frmConfirmLocation input[name=chk_adv_order_k]").bind("check", function() {
			if ($("form#frmConfirmLocation input[name=chk_adv_order_k]:checked").val() == 0)
				$("div#modelConfirmLocation div.date span.date_delivery").hide();
			else
				$("div#modelConfirmLocation div.date span.date_delivery").show();
		});

		$("form#frmConfirmLocation select#address_id").change(function(){
			var id=$(this).val();
			$.ajax({
				url: "api/address.php",
				data: "action=address_delivery_info&address_id="+$(this).val(),
				type: "get",
				cache: false,
				dataType: 'text',
				complete: function (result) {
					$("div#modelConfirmLocation div.address").html( result.responseText );
				}
			});
		});

		if ($("form#frmConfirmLocation input[name=chk_adv_order_k]:checked").val() == 0)
			$("div#modelConfirmLocation div.date span.date_delivery").hide();
		else
			$("div#modelConfirmLocation div.date span.date_delivery").show();

		$.getScript("js/ui.datetimepicker.js", function(){
			$("form#frmConfirmLocation input#txt_adv_order").datepicker({dateFormat: 'd M yy HH:II', minDate: -1, maxDate: +6, showOn: 'button', buttonImage: 'images/ordering/bt-calendar.gif', buttonImageOnly: true});

			confirm_location( function() {
				$.ajax({
					url: "api/set_location.php",
					data: $("form#frmConfirmLocation").serialize(),
					type: "post",
					cache: false,
					dataType: "text",
					complete: function (result) {
						if (result.responseText == "11") { // Invalid
							alert("รหัส Virtual Money ของคุณไม่ถูกต้องค่ะ");
							bindLocation();
						} else if (result.responseText == "12") { // Invalid
							alert("รหัส Virtual Money นี้ได้ถูกใช้ไปแล้วค่ะ");
							bindLocation();
						} else {
							//alert(result.responseText)
							document.location.reload();
						}
					},
					error: function (result) {
						document.location.reload();
					}
				});
			});
		});
	}
}

function bindForgotPassword() {
	if ( $("div#modelForgotPassword").length == 0 ) {
		$.get("api/popup.php", { action: "forgot_password" }, function(html){
			$("body").append( html );

			bindForgotPassword();
		});

	} else {
		closeLoginTop();

		forgot_password();
	}
}

function bindErrorMessage( title, message, callback ) {
	if ( $("div#modelMessage").length == 0 ) {
		$.get("api/popup.php", { action: "error_message" }, function(html){
			$("body").append( html );
			//alert(html)
			bindErrorMessage( title, message, callback );
		});

	} else {
		/*displayMessage( title, message, function() {
			$.get("api/logout.php", function(html){
				document.location.reload();
			});
		});*/
		displayMessage( title, message, callback );
	}
}

function bindDisplayMessage( title, message, callback ) {
	if ( $("div#modelMessage").length == 0 ) {
		$.get("api/popup.php", { action: "error_message" }, function(html){
			$("body").append( html );

			bindDisplayMessage( title, message, callback );
		});

	} else {
		displayMessage( title, message, callback );
	}
}

function bindLogout() {
	if ( $("div#modelConfirmLogout").length == 0 ) {

		$.get("api/popup.php", { action: "logout_confirm" }, function(html){
			$("body").append( html );
			//alert(html)
			bindLogout();
		});

	} else {
		confirm_logout( function() {
			$.get("api/logout.php", function(html){
				document.location.reload();
			});
		});
	}
}

function bindMenuOptions( id, code, choice ) {

	if ( $("div#modelMenuOption").length > 0 ) $("div#modelMenuOption").remove();

	//if ( code != undefined && (parseInt(id) == 0 || isNaN(parseInt(id)) )  ) {
	if ( code != undefined && ( (parseInt(id) || 0) == 0 ) ) {
		params = "action=add_cart_option&code="+code;

		var bl = (parseInt(choice) || 0);
		var flag_choice = Boolean(bl);
		if ( flag_choice ) {
			params += "&choice=1";
		}
	} else {
		params = "action=add_cart_option&id="+id;
	}
	$.ajax({
		url: "api/popup.php",
		data: params,
		type: "get",
		cache: false,
		dataType: "html",
		complete: function (result) {
			$("body").append( result.responseText );

			bindFormCart();

			destroyOverlay();
			menu_option( function() { } );
		}
	});
}

function bindCampaignOptions(code) {

	if ( $("div#modelMenuOption").length > 0 ) $("div#modelMenuOption").remove();

	$.ajax({
		url: "api/popup.php",
		data: "action=add_campaign_option"+(code!=undefined ? "&code="+code : ''),
		type: "get",
		cache: false,
		dataType: "html",
		complete: function (result) {
			$("body").append( result.responseText );

			bindFormCart();

			destroyOverlay();
			menu_option( function() { } );
		}
	});
}

function bindMenuCheckout( ) {
	if ( $("div#MenuAdditional").length > 0 ) $("div#MenuAdditional").remove();

	$.ajax({
		url: "api/popup.php",
		data: "action=add_cart_checkout",
		type: "get",
		cache: false,
		dataType: 'html',
		complete: function (result) {
			$("body").append( result.responseText );

			menu_checkout();
		}
	});
}

function bindFormCart() {

	$("form#frmAddCart input[type=radio]").checkbox( {empty: 'images/spacer.gif'} );
	$("form#frmAddCart input[type=checkbox]").checkbox( {empty: 'images/spacer.gif'} );

	$("form#frmAddCart div.swf_title").each(function() {
		var meta = $.metadata.get(this);
		$( this ).flash({
			src: "flash/text-menu_price_4.swf",
			width: 220, height: 35,
			wmode: "transparent", menu: "false",
			flashvars: { title: meta.title, price: meta.price, lang: meta.lang }
		});
	});

	$("form#frmAddCart").each( function() {
		$(this).submit(function() {
			checkProductChoice();

			var validationError = false;
			$("form#frmAddCart input[type=text]", this).each( function() {
				if ($(this).attr("class")) {
					if (!validateField(this)) validationError = true;
				}
			});

			//if ( parseInt($("form#frmAddCart input#product_num").val()) == 0 || isNaN(parseInt($("form#frmAddCart input#product_num").val())) ) {
			if ( (parseInt($("form#frmAddCart input#product_num").val()) || 0) == 0 ) {
				$("form#frmAddCart input#product_num").focus();
				validationError = true;
			}

			//return false;
			return !validationError;
		});

	});

	$("form#frmAddCart input#product_num").each(function() {
		$(this).keypress(function(e) {
			var KeyCode = (e.keyCode) ? e.keyCode : e.which;
			var CharCode = (e.charCode) ? e.charCode : 0;
			CharCode = ($.browser.msie ? -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
			);
		});

		$(this).keyup(function(e) {
			if ( parseInt($(this).val()) > 0 ) {
				updateProductChoice();
				updatePrice();
			}
		});

		$(this).blur(function(e) {
			if ( parseInt($(this).val()) == 0 || isNaN(parseInt($(this).val())) ) {
				$(this).val( 1 );
			}
			updateProductChoice();
			updatePrice();
		});
	});

	$("form#frmAddCart input.choice").each(function() {
		$(this).keypress(function(e) {
			var KeyCode = (e.keyCode) ? e.keyCode : e.which;
			var CharCode = (e.charCode) ? e.charCode : 0;
			CharCode = ($.browser.msie ? -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
			);
		});

		$(this).keyup(function(e) {
			if ( parseInt($(this).val()) > (parseInt($("form#frmAddCart input#chicken_amt").val()) * parseInt($("form#frmAddCart input#product_num").val())) ) {
				$(this).val( parseInt($("form#frmAddCart input#chicken_amt").val()) * parseInt($("form#frmAddCart input#product_num").val()) );
			}
			updateChoice( $(this).attr("id") );
		});

		$(this).focus(function() { $(this).select(); } );
	});

	if ( (parseInt($("form#frmAddCart input#product_chicken_amt").val()) || 0) > 0 && $("form#frmAddCart input.choice").length > 2 ) {
		$("form#frmAddCart input.choice:last").attr("readonly", true);
	}

	$("form#frmAddCart input.product_select").bind("check", function() {
		updateProductSelect();
	});

	$("form#frmAddCart input.tradeup").bind("check", function() {
		updatePrice();
	});
	$("form#frmAddCart input.tradeup").bind("uncheck", function() {
		updatePrice();
	});

	updatePrice();
}

function updateProductSelect() {
	/*if ( parseInt($("form#frmAddCart input#product_num").val()) == 0 || isNaN(parseInt($("form#frmAddCart input#product_num").val())) ) {
		$("form#frmAddCart input#product_num").val( 1 );
	}*/
	if ( (parseInt($("form#frmAddCart input#product_num").val()) || 0) == 0) $("form#frmAddCart input#product_num").val( 1 );

	var meta = $("form#frmAddCart input.product_select:checked").metadata();
	$("form#frmAddCart input#product_code").val( meta.code );
	$("form#frmAddCart input#product_price").val( meta.price );

	/*if ( parseInt($("form#frmAddCart input#product_num").val()) == 0 || isNaN(parseInt($("form#frmAddCart input#product_num").val())) ) {
		$("form#frmAddCart input#product_num").val(1);
	}*/

	var val = meta.code;

	if ( $("form#frmAddCart input.choice").length > 0 ) {
		//val = parseInt(val.replace(/x/g,''));
		//if ( isNaN(val) ) val = 0;

		//val = (parseInt(val.replace(/x/g,'')) || 0);

		if ( val == "3f1" ) { // CHICKEN 3 FREE 1
			val = 4;
		} else {
			val = (parseInt(val.replace(/x/g,'')) || 0);
		}

		$("form#frmAddCart input#chicken_amt").val( val );

		if ( $("form#frmAddCart input.choice").length > 0 ) {
			i=0;
			$("form#frmAddCart input.choice").each(function() {
				i += 1;
				val = 0;
				if (i==1) { val = $("form#frmAddCart input#chicken_amt").val(); }
				$(this).val( val );
			});
		}

	}
	updateProductChoice();
	updateChoice('none');
	updatePrice();
}

function checkProductChoice() {
	var i=0;

	if ( parseInt($("form#frmAddCart input#product_num").val()) == 0 || isNaN(parseInt($("form#frmAddCart input#product_num").val())) ) {
		$("form#frmAddCart input#product_num").val( 1 );
	}

	var chicken_amt = parseInt($("form#frmAddCart input#chicken_amt").val()) * parseInt($("form#frmAddCart input#product_num").val());

	$("form#frmAddCart input#product_chicken_amt").val( chicken_amt );

	var chicken_remind = chicken_amt;
	$("form#frmAddCart input.choice").each(function() {
		chicken_remind -= $(this).val();
	});

	//console.log('chicken_amt : ' + chicken_amt);
	//console.log('chicken_remind : ' + chicken_remind);
	if (chicken_remind > 0 ) {
		unit = Math.ceil( Math.abs(chicken_remind) / $("form#frmAddCart input.choice").length);
		//console.log(unit);

		$("form#frmAddCart input.choice").each(function() {
			if ( chicken_remind > 0 ) {
				curr_chicken = $(this).val() + unit;
				chicken_remind -= unit;
				if (chicken_remind < 0 ) curr_chicken -= Math.abs(chicken_remind);
				//console.log('chicken_remind : ' + chicken_remind);
				$(this).val( curr_chicken );
			}
		});

	} else if (chicken_remind < 0 ) {
		unit = Math.ceil( Math.abs(chicken_remind) / $("form#frmAddCart input.choice").length);
		//console.log(unit);
		$("form#frmAddCart input.choice").each(function() {
			if ( chicken_remind < 0 ) {
				curr_chicken = $(this).val() - unit;
				chicken_remind += unit;
				if (chicken_remind > 0 ) curr_chicken += chicken_remind;
				//console.log('chicken_remind : ' + chicken_remind);
				$(this).val( curr_chicken );
			}
		});

	}
}

function updateProductChoice() {
	var i=0;
	/*if ( parseInt($("form#frmAddCart input#product_num").val()) == 0 || isNaN(parseInt($("form#frmAddCart input#product_num").val())) ) {
		$("form#frmAddCart input#product_num").val( 1 );
	}*/
	if ( (parseInt($("form#frmAddCart input#product_num").val()) || 0) == 0 ) $("form#frmAddCart input#product_num").val( 1 );

	var chicken_amt = parseInt($("form#frmAddCart input#chicken_amt").val()) * parseInt($("form#frmAddCart input#product_num").val());

	$("form#frmAddCart input#product_chicken_amt").val( chicken_amt );

	var chicken_curr = 0;
	$("form#frmAddCart input.choice").each(function() {
		chicken_curr += (parseInt($(this).val()) || 0);
	});

	if ( chicken_amt != chicken_curr ) {
		$("form#frmAddCart input.choice").each(function() {
			i++;
			if (i == 1) {
				$(this).val( $("form#frmAddCart input#product_chicken_amt").val() );
			} else {
				$(this).val( 0 );
			}
		});
	}
}

function updateChoice( curr_id ) {
	/*if ( parseInt($("form#frmAddCart input#product_num").val()) == 0 || isNaN(parseInt($("form#frmAddCart input#product_num").val())) ) {
		$("form#frmAddCart input#product_num").val( 1 );
	}*/
	if ( (parseInt($("form#frmAddCart input#product_num").val()) || 0) == 0 ) $("form#frmAddCart input#product_num").val( 1 );
	if ( (parseInt($("form#frmAddCart input#chicken_amt").val()) || 0) == 0 ) $("form#frmAddCart input#chicken_amt").val( 0 );

	var total = parseInt($("form#frmAddCart input#chicken_amt").val()) * parseInt($("form#frmAddCart input#product_num").val());
	var curr = 0;
	if ( $("form#frmAddCart input#"+curr_id).length > 0) curr = parseInt($("form#frmAddCart input#"+curr_id).val());
	var avalible = parseInt(total - curr);
	//console.log('total: '+total)
	//console.log('curr: '+curr)
	//console.log('avalible: '+avalible)
	/*$("form#frmAddCart input.choice").each(function() {
		if ( $(this).attr("id") != curr_id ) {
			new_value = 0;
			curr_value = parseInt($(this).val());

			if ( curr_value > avalible ) {
				new_value = avalible;
			} else {
				new_value = avalible;
			}
			if (isNaN(new_value)) new_value = 0;

			avalible = avalible - new_value;
			//console.log('new_value: '+new_value)
			$(this).val( new_value );
		}
	});*/

	var total_choice = $("form#frmAddCart input.choice").filter(function () { return $(this).attr("id") != curr_id; }).length;
	//console.log('total_choice: '+total_choice)
	$("form#frmAddCart input.choice").filter(function () { return $(this).attr("id") != curr_id; }).each(function(index) {
		new_value = 0;
		curr_value = parseInt($(this).val());

		if ( curr_value > avalible ) {
			new_value = avalible;
		} else {
			if ( (index+1) == total_choice) {
				new_value = avalible;
			} else {
				new_value = curr_value;
			}
		}
		if (isNaN(new_value)) new_value = 0;

		avalible = avalible - new_value;
		//console.log('index: '+index)
		//console.log('new_value: '+new_value)
		$(this).val( new_value );

	});

}

function updatePrice() {
	var price_product = parseInt($("form#frmAddCart input#product_price").val()) * parseInt($("form#frmAddCart input#product_num").val());
	var price_tradeup = 0;

	$("form#frmAddCart div.sum_total label").html( price_product );

	$("form#frmAddCart div.sum_total span").empty();

	$("form#frmAddCart input.tradeup").each(function() {
		if ( $(this).attr("checked") ) {
			var meta = $.metadata.get(this);
			if ( meta.price == undefined ) meta.price = 0;
			price_tradeup += parseInt(meta.price) * parseInt($("form#frmAddCart input#product_num").val());
		}
	})
	//if ( price_tradeup > 0 ) $("form#frmAddCart div.sum_total span").html( "&nbsp;+" + price_tradeup );

	$("form#frmAddCart div.sum_total").each(function() {
		$( this ).flash({
			src: "flash/text-popup_price_total.swf",
			width: 250, height: 30,
			wmode: "transparent", menu: "false",
			flashvars: { lang: get_lang(), price: price_product, price_tradeup: price_tradeup }
		});
	});
}

function bindMenuAdvisor(id) {
	if ( $("div#modelMenuAdvisor").length > 0 ) $("div#modelMenuAdvisor").remove();

	$.ajax({
		url: "api/popup.php",
		data: "action=add_cart_advisor&advisor="+id,
		type: "get",
		cache: false,
		dataType: 'html',
		complete: function (result) {
			$("body").append( result.responseText );
			menu_advisor();
		}
	});

}

function swfAddCart( code, choice ) {
	if ( $("div#navTop div.Shortcuts a#mnLogout").length == 1 ) {
		$.ajax({
			url: "api/popup.php",
			data: "action=chk_add_cart&code="+code,
			type: "get",
			cache: false,
			dataType: "html",
			complete: function (result) {
				if ( parseInt(result.responseText) == 1 ) {
					choice = (parseInt(choice) || 0);
					bindMenuOptions( 0, code, choice );

				} else if ( parseInt(result.responseText) == 2 ) {
					bindDisplayMessage("ขออภัยขณะนี้เป็นเวลาปิดให้บริการของร้านค่ะ", "");
					// action=add_cart_option&id=117
				}
			},
			error: function(result) {
				//alert(result.statusText);
			}
		});

	} else {
		//bindErrorMessage("PLEASE LOGIN FIRST ?", "");
		bindErrorMessage( (get_lang()=="en" ? "Please login before ordering" : "กรุณาเข้าสู่ระบบก่อนสั่งซื้ออาหารค่ะ"), "");
	}
}

function swfAddCampaign(code) {
	//alert("action=chk_campaign"+(code!=undefined ? "&code="+code : ''))
	if ( $("div#navTop div.Shortcuts a#mnLogout").length == 1 ) {
		$.ajax({
			url: "api/popup.php",
			data: "action=chk_campaign"+(code!=undefined ? "&code="+code : ''),
			type: "get",
			cache: false,
			dataType: "html",
			complete: function (result) {
				if ( parseInt(result.responseText) == 1 ) {
					bindCampaignOptions(code);
				}
			},
			error: function(result) {
				//alert(result.statusText);
			}
		});

	} else {
		//bindErrorMessage("PLEASE LOGIN FIRST ?", "");
		bindErrorMessage( (get_lang()=="en" ? "Please login before ordering" : "กรุณาเข้าสู่ระบบก่อนสั่งซื้ออาหารค่ะ"), "");
	}
}

function swfLoginFirst() {
	bindErrorMessage( (get_lang()=="en" ? "Please login before ordering" : "กรุณาเข้าสู่ระบบก่อนสั่งซื้ออาหารค่ะ"), "");
}

function displayMessage ( title, message, callback) {

	$("div#modelMessage").modal({
		close: false,
		position: ["20%",],
		overlayId: 'bg-overlay',
		//containerId: 'modelMessage',
		onShow: function (dialog) {
			$(".qtip").hide();

			dialog.data.find('.title').html(title);
			dialog.data.find('.message').html(message);

			dialog.data.find(".btClose").click(function (e) {
				e.preventDefault();
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				$.modal.close();
			});

		}
	});
}

// OPEN DIALOG
function confirm_logout ( callback) {
	$("div#modelConfirmLogout").modal({
		close: false,
		position: ["20%",],
		overlayId: 'bg-overlay',
		onShow: function (dialog) {
			$(".qtip").hide();
			//dialog.data.find('.message').append(message);

			// if the user clicks "yes"
			dialog.data.find('a.btConfirm').click(function (e) {
				e.preventDefault();
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				$.modal.close();
				return false;
			});

			dialog.data.find('a.btCancel').click(function (e) {
				e.preventDefault();
				// close the dialog
				$("div#modelConfirmLogout").remove();
				$.modal.close();
				return false;
			});
		}
	});
}

function confirm_location ( callback) {
	$("div#modelConfirmLocation").modal({
		close: false,
		position: ["60px",],
		overlayId: 'bg-overlay',
		onShow: function (dialog) {
			$(".qtip").hide();

			// if the user clicks "yes"
			dialog.data.find("input.btProcess").click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				$.modal.close();
			});

			// close the dialog
			dialog.data.find('a.modalClose').click(function () {
				$.modal.close();
			});
		}
	});
}

function forgot_password () {
	$("div#modelForgotPassword").modal({
		close: false,
		position: ["20%",],
		overlayId: "bg-overlay",
		onShow: function (dialog) {
			$(".qtip").hide();

			$("form#frmForgotPassword").each( function() {
				// handle submissions without filling any field
				$(this).submit(function () {

					var validationError = false;

					// for each field validate value
					$("form#frmForgotPassword input[type=text]").each( function() {
						if ($(this).attr("class")) {
							if (!validateField(this)) {
								validationError = true;
							}
						}
					});
					if (validationError) {
						$("form#frmForgotPassword input[type=text]:first").focus();
					}
					return !validationError;
				});

			});

			// if the user clicks "yes"
			/*dialog.data.find("input.btRequestPassword").click(function () {
				// close the dialog
				$.modal.close();
				$("div#modelForgotPassword").remove();
			});*/
			dialog.data.find("input.btRequestPassword").click(function () {
				$("form#frmForgotPassword").submit();
			});

			dialog.data.find("input.btCancel").click(function () {
				// close the dialog
				$.modal.close();
				$("div#modelForgotPassword").remove();
				destroyOverlay();
			});

		}
	});
}

function menu_option ( callback) {
	$("div#modelMenuOption").modal({
		close: false,
		position: [,],
		persist: true,
		overlayId: 'bg-overlay',
		//containerId: 'modelMenuOption',
		onShow: function (dialog) {
			$(".qtip").hide();

			// if the user clicks "yes"
			dialog.data.find("input.btOrder").click(function () {

				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				$("form#frmAddCart").submit();

				// close the dialog
				$.modal.close();
			});

			// close the dialog
			dialog.data.find('input.btCancel').click(function () {
				//$("div#MenuOptions").remove();
				//$("div#modelMenuOption").remove();

				$.modal.close();
			});
			dialog.data.find('a.modalClose').click(function () {
				//$("div#MenuOptions").remove();
				//$("div#modelMenuOption").remove();

				$.modal.close();
			});
		}
	});
}

function menu_checkout ( callback ) {
	$("div#modelMenuAdditional").modal({
		close: false,
		position: ["20%",],
		persist: true,
		overlayId: 'bg-overlay',
		containerId: 'modelMenuAdditional',
		onShow: function (dialog) {
			$(".qtip").hide();
			$("div#modelMenuAdditional input[type=checkbox]").checkbox( {empty: 'images/spacer.gif'} );
			$("div#modelMenuAdditional div.item_list").jScrollHorizontalPane( {showArrows:true, arrowSize: 23, dragMinWidth:76, dragMaxWidth:76, scrollbarHeight:23, scrollbarMargin:2} );

			$("div#modelMenuAdditional div.swf_price").each(function() {
				var meta = $.metadata.get(this);

				$( this ).flash({
					src: meta.swf,
					width: 115, height: 45,
					//name: $(this).attr("id"),
					wmode: "transparent", menu: "false",
					flashvars: { title: meta.title, price: meta.price, lang: meta.lang }
				});
			});
			// if the user clicks "yes"
			dialog.data.find("input.btProcess").click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				$("form#frmChkOut").submit();

				// close the dialog
				$.modal.close();
			});

			dialog.data.find('a.modalClose').click(function () {
				$("div#modelMenuAdditional").remove();

				$.modal.close();
			});
		}
	});
}

function menu_advisor ( callback ) {
	$("div#modelMenuAdvisor").modal({
		close: false,
		position: ["20%",],
		persist: true,
		overlayId: "bg-overlay",
		containerId: "modelMenuAdvisor",
		onShow: function (dialog) {
			$(".qtip").hide();

			$("div#modelMenuAdvisor input[type=checkbox]").checkbox( {empty: "images/spacer.gif"} );
			$("div#modelMenuAdvisor div.item_list").jScrollHorizontalPane( {showArrows:true, arrowSize: 23, dragMinWidth:76, dragMaxWidth:76, scrollbarHeight:23, scrollbarMargin:2} );

			$("div#modelMenuAdvisor div.swf_price").each(function() {
				var meta = $.metadata.get(this);

				$( this ).flash({
					src: meta.swf,
					width: 115, height: 45,
					//name: $(this).attr("id"),
					wmode: "transparent", menu: "false",
					flashvars: { title: meta.title, price: meta.price, lang: meta.lang }
				});
			});

			// if the user clicks "yes"
			dialog.data.find("input.btProcess").click(function (e) {

				$("form#frmAdvisorList select#advisor option:first").attr("selected", "selected");

				if ( $("div#navTop div.Shortcuts a#mnLogout").length == 1 ) {
					// call the callback
					if ($.isFunction(callback)) {
						callback.apply();
					}
					$("form#frmAdvisor").submit();

					// close the dialog
					$.modal.close();

				} else {
					e.preventDefault();

					// close the dialog
					$.modal.close();

					bindErrorMessage( (get_lang()=="en" ? "Please login before ordering" : "กรุณาเข้าสู่ระบบก่อนสั่งซื้ออาหารค่ะ"), "");
				}
			});

			dialog.data.find("a.modalClose").click(function (e) {
				e.preventDefault();

				$("div#modelMenuAdvisor").remove();
				$("form#frmAdvisorList select#advisor option:first").attr('selected', 'selected');
				$.modal.close();
			});
		}
	});
}

/*function delivery_address ( callback) {
	$("div#cDeliveryAddress").modal({
		close: false,
		position: ["0%",],
		overlayId: 'bg-overlay',
		onShow: function (dialog) {
			$(".qtip").hide();

		}
	});
}*/


$(document).ready(function () {

	if ( $("div#navTop div.Shortcuts a#mnLogout").length == 1 ) {
		$("a.btLogout").click(function (e) {
			e.preventDefault();
			bindLogout();
		});

		$("a.btOrder").bind("click", function (e) {
			e.preventDefault();

			insertOverlay();

			var meta = $.metadata.get(this);
			if (meta.id != undefined ) {
				$.ajax({
					url: "api/popup.php",
					data: "action=chk_add_cart&id="+meta.id,
					type: "get",
					cache: false,
					dataType: "html",
					complete: function (result) {
						if ( parseInt(result.responseText) == 1 ) {
							bindMenuOptions(meta.id);
						} else if ( parseInt(result.responseText) == 2 ) {
							destroyOverlay();
							bindDisplayMessage("ขออภัยค่ะ", "รายการนี้งดการสั่งชั่วคราวค่ะ");
							// action=add_cart_option&id=117
						}
					},
					error: function(result) {
						//alert(result.statusText);
					}
				});
			}

		});

		bindProfileTop();


		$("a.btAddDeliveryAddress").bind("click", function (e) {
			e.preventDefault();
			//alert('Click');
			bindDeliveryAddress();
		});

		$("a.btEditTaxAddress").bind("click", function (e) {
			e.preventDefault();
			//alert('Click');
			bindTaxAddress();
		});


		$("div#cLeft div.shortcutVirtualMoney a").bind("click", function (e) {
			e.preventDefault();
			openProfileTop();
		});


	} else {

		// Top Login Panel
		bindLoginTop();

		// Left Login Panel
		bindLoginLeft();


		$("a.btForgot").live("click", function (e) {
			e.preventDefault();
			bindForgotPassword();
		});

		$("a.btOrder").live("click", function (e) {
			e.preventDefault();
			//alert('sfsdf');
			bindErrorMessage( (get_lang()=="en" ? "Please login before ordering" : "กรุณาเข้าสู่ระบบก่อนสั่งซื้ออาหารค่ะ"), "");
		});
	}

});
