/*
* @version : 1.1.0
* @update : 2011-08-04
* @author: บริษัท อีมีเดีย จำกัด
* @comment : CIMB Website
*/

function refreshCaptcha(frm) {
	if ( $(frm+" img#img_captcha").attr("default")==undefined || $(frm+" img#img_captcha").attr("default").length == 0) {
		$(frm+" img#img_captcha").attr("default", $(frm+" img#img_captcha").attr("src") );
	}
	var time = new Date();
	var urlCaptcha = $(frm+" img#img_captcha").attr("default");

	$(frm+" img#img_captcha").attr("src", urlCaptcha+"&time="+time.getTime());
	$(frm+" input[name=security_code]").focus();
}

$.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 get_lang() {
	return ( $("body").hasClass("en") ? "en" : "th" );
}

function key_digit(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
	);
}

/* exten jquery function */
function clean_whitespace( text ) {
	return (text || "").replace(/\s/g, "" );
}

function validateField(field) {
	var error = false;

	// remove whitespace
	$(field).val( jQuery.trim( $(field).val() ) );

	// username field
	if ($(field).attr("class").indexOf("username") != -1) {
		$(field).val( clean_whitespace($(field).val()) );
	}

	// required fields
	if ($(field).attr("class").indexOf("required") != -1) {
		if ( $(field).attr("type") == "radio") {

			if ( !$("form#"+$(field).parents("form").attr("name")+" input[name="+$(field).attr("name")+"]").is(":checked"))
				error = true;
		} else {
			if (!$(field).val().length)
				error = true;
		}
	}
	// numeric fields
	if ($(field).val().length && $(field).attr("class").indexOf("numeric") != -1) {
		if (!/^[0-9]*$/.test($(field).val()))
			error = true;
	}
	// float fields
	if ($(field).val().length && $(field).attr("class").indexOf("float") != -1) {
		if (!/^(\+?((([0-9]+(\.)?)|([0-9]*\.[0-9]+))))$/.test($(field).val()))
			error = true;
	}
	// emails
	if ($(field).val().length && $(field).attr("class").indexOf("email") != -1) {
		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;
	}
	// upper case
	if ($(field).attr("class").indexOf("uppercase") != -1) {
		$(field).val( $(field).val().toUpperCase() );
	}
	// lower case
	if ($(field).attr("class").indexOf("lowercase") != -1) {
		$(field).val( $(field).val().toLowerCase() );
	}

	if (error) {
		$(field).addClass("error");
	} else {
		$(field).removeClass("error");
	}

	return !error;
}

function renderDropDown(ele) {
	if ( $.fn.msDropDown!=undefined && $(ele).length > 0 ) {
		$(ele).msDropDown();
	}
}

function disableDropDown(ele, flag) {
	if ( $.fn.msDropDown!=undefined && $(ele).length > 0 ) {
		var oHandler = $(ele).msDropDown().data("dd");
		oHandler.disabled(flag);
	} else {
		if ( flag == true ) {
			$(ele).attr("disabled", "disabled");
		} else {
			$(ele).attr("disabled", "");
		}
	}
}

function setDropDown(ele, property, value) {
	if ( $.fn.msDropDown!=undefined && $(ele).length > 0 ) {
		var oHandler = $(ele).msDropDown().data("dd");
		oHandler.set(property, value);
	} else {
		if ( property == "selectedIndex" ) {
			$(ele).attr(property, value);
		}
	}
}

function bindProvince(province, amphur) {

	var optiondefault = '<option value="">'+(get_lang()=="en" ? 'Select District' : 'กรุณาเลือกอำเภอ')+'</option>' ;
	var optionloading = '<option value="">'+(get_lang()=="en" ? 'loading...' : 'กำลังโหลด.....')+'</option>' ;

	if ( parseInt($(province).val()|| 0) == 0 ) {
		if ( $.fn.msDropDown!=undefined ) {
			var oHandler = $(amphur).msDropDown().data("dd");
			if ( oHandler) oHandler.disabled(true);
		} else {
			$(amphur).attr("disabled", "disabled");
		}
	}

	$(province).bind("change", function() {

		if ( $.fn.msDropDown!=undefined ) {
			var oHandler = $(amphur).msDropDown().data("dd");
			oHandler.disabled(true);
		} else {
			$(amphur).attr("disabled", "disabled");
		}

		if ( $(this).val() ) {
			$(amphur).html(optionloading);

			$.getJSON("api/api.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);

				if ( $.fn.msDropDown!=undefined ) {
					var oHandler = $(amphur).msDropDown().data("dd");
					oHandler.disabled(false);
				} else {
					$(amphur).attr("disabled", "");
				}
				//$(amphur).focus();
			});

		} else {
			$(amphur).html(optiondefault);
		}
		$(amphur).blur();

	});
}

function bindRegion(region, province, amphur) {

	var optiondefault_province = '<option value="">'+(get_lang()=="en" ? 'All Province' : 'จังหวัดทั้งหมด')+'</option>' ;
	var optiondefault_amphur = '<option value="">'+(get_lang()=="en" ? 'All District' : 'อำเภอทั้งหมด')+'</option>' ;
	var optionloading = '<option value="">'+(get_lang()=="en" ? 'loading...' : 'กำลังโหลด.....')+'</option>' ;

	if ( parseInt($(region).val()|| 0) == 0 ) {
		if ( $.fn.msDropDown!=undefined ) {
			var oHandler = $(province).msDropDown().data("dd");
			if ( oHandler) oHandler.disabled(true);
		} else {
			$(province).attr("disabled", "disabled");
		}
	}
	if ( parseInt($(province).val()|| 0) == 0 ) {
		if ( $.fn.msDropDown!=undefined ) {
			var oHandler = $(amphur).msDropDown().data("dd");
			if ( oHandler) oHandler.disabled(true);
		} else {
			$(amphur).attr("disabled", "disabled");
		}
	}

	$(region).bind("change", function() {

		$(province).html(optiondefault_province);
		$(amphur).html(optiondefault_amphur);
		if ( $.fn.msDropDown!=undefined ) {
			var oHandler = $(province).msDropDown().data("dd");
			oHandler.disabled(true);
			var oHandler = $(amphur).msDropDown().data("dd");
			oHandler.disabled(true);
		} else {
			$(province).attr("disabled", "disabled");
			$(amphur).attr("disabled", "disabled");
		}

		if ( $(this).val() ) {
			$(province).html(optionloading);

			$.getJSON("api/api.php", {action: "province", id: $(this).val()}, function(data) {

				var options = optiondefault_province;
				for (var i=0; i<data.length; i++) {
					options += '<option value="'+data[i].id+'">'+data[i].name+'</option>';
				}

				$(province).html(options);

				if ( $.fn.msDropDown!=undefined ) {
					var oHandler = $(province).msDropDown().data("dd");
					oHandler.disabled(false);
				} else {
					$(province).attr("disabled", "");
				}
				//$(amphur).focus();
			});

		} else {
			$(province).html(optiondefault_province);
		}

	});

	$(province).bind("change", function() {
		$(amphur).html(optiondefault_amphur);
		if ( $.fn.msDropDown!=undefined ) {
			var oHandler = $(amphur).msDropDown().data("dd");
			oHandler.disabled(true);
		} else {
			$(amphur).attr("disabled", "disabled");
		}

		if ( $(this).val() ) {
			$(amphur).html(optionloading);

			$.getJSON("api/api.php", {action: "amphur", id: $(this).val()}, function(data) {

				var options = optiondefault_amphur;
				for (var i=0; i<data.length; i++) {
					options += '<option value="'+data[i].id+'">'+data[i].name+'</option>';
				}

				$(amphur).html(options);

				if ( $.fn.msDropDown!=undefined ) {
					var oHandler = $(amphur).msDropDown().data("dd");
					oHandler.disabled(false);
				} else {
					$(amphur).attr("disabled", "");
				}
				//$(amphur).focus();
			});

		} else {
			$(amphur).html(optiondefault_amphur);
		}

	});
}

function baseUrl(){
	var base="";
	if ( $("base").attr("href") != undefined && $("base").attr("href").length > 0 ) {
		base = $("base").attr("href");

	} else if ($.fn.url != undefined) {
		base+= $.url().attr('protocol')+'://'+$.url().attr('host');
		if ($.url().attr('port') != '80') base+= ':'+$.url().attr('port');
	}
	return base;
}

function pathUrl(){
	var path="";
	if ($.fn.url != undefined) {
		path = $.url().attr("source").substr(baseUrl().length);
		if ( path.substr(0,1) != '/') path = '/'+path;

		var arr = path.split('/');
		var path_url = '';
		for(i=0; i<arr.length; i++) {
			if (arr[i].length>0) path_url += '/'+$.URLEncode(arr[i]);
		}
		path = path_url+'/';
	}
	return path;
}

function blockPage() {
	$.ui.dialog.overlay.create();
}

function unblockPage() {
	$("div.ui-widget-overlay").fadeOut().remove();
}

function dialogSubscribe(unsubscribe) {
	blockPage();

	if ( $("div#dialog-subscribe").length > 0 ) {
		$("div#dialog-subscribe").dialog("destroy").remove();
	}
	if ( unsubscribe==undefined) unsubscribe=false;

	var param_url = ''; param_data = '';
	param_url = baseUrl();

	if ( param_url.substr(-1) == '/') param_url = param_url.substr(0, param_url.length-1);
	param_url+= '/api/dialog.php';
	if ( $.url != undefined && $.url().segment.length > 0 && $.inArray("en", $.url().segment()) != -1) param_data+= '&lang=en';
	param_data+= "&action="+(unsubscribe ? "unsubscribe" : "subscribe");

	$.ajax({
		url: param_url,
		data: param_data,
		type: "get",
		cache: false,
		dataType: "text",
		complete: function (data) {
			unblockPage();
			$("div#dialog-subscribe").remove();

			var responseText = '';
			responseText = data.responseText;
			//alert(responseText)
			//alert($(responseText).filter("div#ajaxContent").length)
			if ( $(responseText).filter("div#ajaxContent").length > 0 ) {
				responseText = ($(responseText).filter("div#ajaxContent").html() || "");
			}
			//alert(responseText.length)
			if ( responseText.length > 0 ) {
				$("<div id=\"dialog-subscribe\">"+responseText+"</div>").appendTo("body").hide();
			}


			// Form Binding
			if ( $("form#frmSubscribe").length > 0 ) {
				refreshCaptcha("form#frmSubscribe");
				$("form#frmSubscribe").submit(function(e){
					e.preventDefault();
					var validationError = false;
					$("form#frmSubscribe div.msg").empty();
					//$("form#frmSubscribe span.required").empty();
					$("form#frmSubscribe input").removeClass("error");

					$("form#frmSubscribe input[type=text]").each( function() {
						if ($(this).attr("class")) {
							if (!validateField(this)) {
								validationError = true;
								//$(this).removeClass("focus");
								//$(this).parents("span").parent().children("span.required").html("*");

								if( validationError ) {
									errorMessage = (get_lang()=="en" ? 'Please fill' : 'กรุณากรอก');

									switch( $(this).attr("name") ) {

										case 'name':
											errorMessage += ' "' + (get_lang()=="en" ? 'Your Name' : 'ชื่อ - นามสกุล') + '"';
											$(this).focus();
											break;
										case 'email':
											errorMessage += ' "' + (get_lang()=="en" ? ($(this).val() == "" ? 'Email' : 'Correct Email Format') : ($(this).val() == "" ? 'อีเมล์' : 'อีเมล์ที่ถูกต้อง') ) + '"';
											$(this).focus();
											break;
										case 'security_code':
											errorMessage += ' "' + (get_lang()=="en" ? 'Security Code' : 'รหัสยืนยัน') + '"';
											$(this).focus();
											break;
									}
									alert( errorMessage );
									return false;
								}
							}
						}
					});

					if ( !validationError ) {
						$("div#dialog-subscribe div.content div.result").remove();
						$("div#dialog-subscribe div.content div.box").fadeOut(function(){
							$("div#dialog-subscribe div.content").append("<div class=\"result\"><div class=\"loading\"></div></div>");
							$("div#dialog-subscribe div.content div.result").hide().fadeIn();
						});
						$("div#dialog-subscribe div.content div.title p").fadeOut();


						$.ajax({
							url: "api/"+$("form#frmSubscribe").attr("action"),
							data: "action=subscribe&"+$("form#frmSubscribe").serialize(),
							type: "post",
							cache: false,
							dataType: "text",
							complete: function (result) {
								switch( result.responseText ) {
									case "1":
										$("div#dialog-subscribe div.content div.result div.loading").fadeOut(function(){
											$(this).remove();
											$("div#dialog-subscribe div.content div.title p").fadeOut();
											$("div#dialog-subscribe div.content div.result").hide().append("<div class=\"msg_complete\">"+( (get_lang()=="en" ? "Thank you for your interest in news and information from our bank. We will always keep updated our news and information to you." : "ขอขอบคุณที่ท่านให้ความสนใจรับข้อมูลข่าวสารจากธนาคาร ธนาคารจะนำเสนอข้อมูลข่าวสารของธนาคารให้แก่ท่านอย่างสม่ำเสมอ") )+"</div>").fadeIn();

											setTimeout("$(\"div#dialog-subscribe\").dialog(\"close\");", 5000);
										});
										//$("div#dialog-subscribe").dialog("close");
										break;

									case "2": // Already Subscribe
										$("div#dialog-subscribe div.content div.result div.loading").fadeOut(function(){
											$(this).remove();
											if ( $("form#frmSubscribe input[name=subscribe]:checked").val() == "0") { // Unsubscribe
												$("div#dialog-subscribe div.content div.result").hide().append("<div class=\"msg_error\">"+( (get_lang()=="en" ? "Your email not found.<br />Please try again." : "ไม่พบอีเมลของคุณในระบบค่ะ<br />กรุณาลองอีกครั้ง") )+"</div>").fadeIn();
											} else {
												$("div#dialog-subscribe div.content div.result").hide().append("<div class=\"msg_error\">"+( (get_lang()=="en" ? "Your email already subscribe.<br />Please try again." : "พบอีเมลของคุณในระบบค่ะ<br />กรุณาลองอีกครั้ง") )+"</div>").fadeIn();
											}

											setTimeout("$(\"div#dialog-subscribe div.content div.msg_error\").fadeOut(function() { $(this).remove(); $(\"div#dialog-subscribe div.content div.box\").fadeIn(); $(\"div#dialog-subscribe div.content div.title p\").fadeIn(); })", 5000);
										});
										//$("div#dialog-subscribe").dialog("close");
										break;

									case "3": // Wrong Security Code
										$("div#dialog-subscribe div.content div.result div.loading").fadeOut(function(){
											$(this).remove();
											$("div#dialog-subscribe div.content div.result").hide().append("<div class=\"msg_error\">"+( (get_lang()=="en" ? "Security Code wrong.<br />Please try again." : "รหัสยืนยันไม่ถูกต้องค่ะ<br />กรุณาลองอีกครั้ง") )+"</div>").fadeIn();

											setTimeout("$(\"div#dialog-subscribe div.content div.msg_error\").fadeOut(function() { $(this).remove(); $(\"div#dialog-subscribe div.content div.box\").fadeIn(); $(\"div#dialog-subscribe div.content div.title p\").fadeIn(); })", 5000);
										});
										//$("div#dialog-subscribe").dialog("close");
										break;

									default:
										$("div#dialog-subscribe").dialog("close");

								}
							},
							error: function(result) {
								//alert(result.statusText);
							}
						});

					}/* else {
						alert( (get_lang()=="en" ? "Please fill complete information." : "กรุณากรอกข้อมูลให้ถูกต้องค่ะ") );
					$("form#frmSubscribe input[type=text].error:first").focus();
					}*/
				});

				$("form#frmLogin input.btnLogin").click(function(e){
					e.preventDefault();
					$("form#frmLogin").submit();
				})
			}

			// Open Dialog
			if ( $("div#dialog-subscribe").length > 0 ) {

				$("div#dialog-subscribe .btn_close").click(function(e){
					e.preventDefault();
					$("div#dialog-subscribe").dialog("close");
				});

				$("div#dialog-subscribe .btn_unsubscribe").click(function(e){
					e.preventDefault();
					$("div#dialog-subscribe").dialog("close");

					dialogUnsubscribe();
				});


				$("form#frmSubscribe input[name=subscribe]").change(function(){
					if ( $("form#frmSubscribe input[name=subscribe]:checked").val() == "0") { // Unsubscribe
						$("div#dialog-subscribe div.title div.subscribe").hide();
						$("div#dialog-subscribe div.box div.subscribe").hide();
						$("div#dialog-subscribe div.title div.unsubscribe").show();
						$("div#dialog-subscribe div.box div.unsubscribe").show();

						$("form#frmSubscribe input#name").removeClass("required");
					} else { // Subscribe
						$("div#dialog-subscribe div.title div.unsubscribe").hide();
						$("div#dialog-subscribe div.box div.unsubscribe").hide();
						$("div#dialog-subscribe div.title div.subscribe").show();
						$("div#dialog-subscribe div.box div.subscribe").show();

						$("form#frmSubscribe input#name").addClass("required");
					}
				});


				$("div#dialog-subscribe .btCaptcha").click(function(e){
					e.preventDefault();
					refreshCaptcha("form#frmSubscribe");
				});

				$("div#dialog-subscribe").dialog({
					dialogClass: "dialogSubscribe",
					width: 460,
					height: 350,
					autoOpen: true,
					modal: true,
					draggable: false,
					resizable: false,
					open: function(event, ui) {
						$("form#frmSubscribe input[name=subscribe]").trigger("change");
					},
					close: function() {
						//allFields.val('').removeClass('ui-state-error');

						$("div#dialog-subscribe").dialog("destroy").remove();
					}
				});

				//$("div#dialog-subscribe").dialog("open");
			}

		},
		error: function(){
			unblockPage();
		}
	});
}

function dialogUnsubscribe() {
	blockPage();

	if ( $("div#dialog-unsubscribe").length > 0 ) {
		$("div#dialog-unsubscribe").dialog("destroy").remove();
	}

	$.ajax({
		url: "api/dialog.php",
		data: "action=unsubscribe",
		type: "get",
		cache: false,
		dataType: "text",
		complete: function (data) {
			unblockPage();
			$("div#dialog-unsubscribe").remove();

			var responseText = '';
			responseText = data.responseText;
			//alert(responseText)
			//alert($(responseText).filter("div#ajaxContent").length)
			if ( $(responseText).filter("div#ajaxContent").length > 0 ) {
				responseText = ($(responseText).filter("div#ajaxContent").html() || "");
			}
			//alert(responseText.length)
			if ( responseText.length > 0 ) {
				$("<div id=\"dialog-unsubscribe\">"+responseText+"</div>").appendTo("body").hide();
			}


			// Form Binding
			if ( $("form#frmUnsubscribe").length > 0 ) {
				$("form#frmUnsubscribe").submit(function(e){
					e.preventDefault();
					var validationError = false;
					$("form#frmUnsubscribe div.msg").empty();
					$("form#frmUnsubscribe span.required").empty();

					$("form#frmUnsubscribe input[type=text]").each( function() {
						if ($(this).attr("class")) {
							if (!validateField(this)) {
								validationError = true;
								$(this).removeClass("focus");
								$(this).parents("span").parent().children("span.required").html("*");
							}
						}
					});

					if ( !validationError ) {
						$("div#dialog-unsubscribe div.content div.loading").remove();
						$("div#dialog-unsubscribe div.content div.box").fadeOut(function(){
							$("div#dialog-unsubscribe div.content").append("<div class=\"loading\"></div>");
							$("div#dialog-unsubscribe div.content div.loading").hide().fadeIn();
						});

						$.ajax({
							url: "api/"+$("form#frmUnsubscribe").attr("action"),
							data: "action=unsubscribe&"+$("form#frmUnsubscribe").serialize(),
							type: "post",
							cache: false,
							dataType: "text",
							complete: function (result) {
								switch( result.responseText ) {
									case "1":
										$("div#dialog-unsubscribe div.content div.loading").fadeOut(function(){
											$(this).remove();
											$("div#dialog-unsubscribe div.content").append("<div class=\"msg_complete\">"+( (get_lang()=="en" ? "Your request had been cancelled. You will not get news and information from our bank." : "คุณได้ยกเลิกการรับข้อมูลข่าวสารจากทางธนาคารเรียบร้อยแล้ว") )+"</div>");
											$("div#dialog-unsubscribe div.content div.msg_complete").hide().fadeIn();

											setTimeout("$(\"div#dialog-unsubscribe\").dialog(\"close\");", 5000);
										});
										//$("div#dialog-subscribe").dialog("close");
										break;

									case "2": // Already Subscribe
										$("div#dialog-unsubscribe div.content div.loading").fadeOut(function(){
											$("div#dialog-unsubscribe div.content div.loading").remove();
											$("div#dialog-unsubscribe div.content").append("<div class=\"msg_error\">"+( (get_lang()=="en" ? "Your email not found.<br />Please try again." : "ไม่พบอีเมลของคุณในระบบค่ะ<br />กรุณาลองอีกครั้ง") )+"</div>");
											$("div#dialog-unsubscribe div.content div.msg_error").hide().fadeIn();

											setTimeout("$(\"div#dialog-unsubscribe div.content div.msg_error\").fadeOut(function() { $(this).remove(); $(\"div#dialog-unsubscribe div.content div.box\").fadeIn(); })", 5000);
										});
										//$("div#dialog-subscribe").dialog("close");
										break;

									default :
										$("div#dialog-unsubscribe").dialog("close");
								}
							},
							error: function(result) {
								//alert(result.statusText);
							}
						});

					}
				});

				$("form#frmLogin input.btnLogin").click(function(e){
					e.preventDefault();
					$("form#frmLogin").submit();
				})
			}

			// Open Dialog
			if ( $("div#dialog-unsubscribe").length > 0 ) {

				$("div#dialog-unsubscribe .btn_close").click(function(e){
					e.preventDefault();
					$("div#dialog-unsubscribe").dialog("close");
				});


				$("div#dialog-unsubscribe").dialog({
					dialogClass: "dialogUnsubscribe",
					width: 350,
					height: 180,
					autoOpen: true,
					modal: true,
					draggable: false,
					resizable: false,
					open: function(event, ui) {
					},
					close: function() {
						//allFields.val('').removeClass('ui-state-error');

						$("div#dialog-unsubscribe").dialog("destroy").remove();
					}
				});

				//$("div#dialog-unsubscribe").dialog("open");
			}

		},
		error: function(){
			unblockPage();
		}
	});
}

function dialogSendToFriend() {
	blockPage();

	if ( $("div#dialog-sendtofriend").length > 0 ) {
		$("div#dialog-sendtofriend").dialog("destroy").remove();
	}
	//if ( unsubscribe==undefined) unsubscribe=false;

	$.ajax({
		url: "api/dialog.php",
		data: "action=send_to_friend",
		type: "get",
		cache: false,
		dataType: "text",
		complete: function (data) {
			unblockPage();
			$("div#dialog-sendtofriend").remove();

			var responseText = '';
			responseText = data.responseText;
			//alert(responseText)
			//alert($(responseText).filter("div#ajaxContent").length)
			if ( $(responseText).filter("div#ajaxContent").length > 0 ) {
				responseText = ($(responseText).filter("div#ajaxContent").html() || "");
			}
			//alert(responseText.length)
			if ( responseText.length > 0 ) {
				$("<div id=\"dialog-sendtofriend\">"+responseText+"</div>").appendTo("body").hide();
			}

			// Form Binding
			if ( $("form#frmSendtofriend").length > 0 ) {
				refreshCaptcha("form#frmSendtofriend");
				$("form#frmSendtofriend").submit(function(e){
					e.preventDefault();
					var validationError = false;
					$("form#frmSendtofriend div.msg").empty();
					//$("form#frmSubscribe span.required").empty();
					$("form#frmSendtofriend input").removeClass("error");

					$("form#frmSendtofriend input[type=text], form#frmSendtofriend textarea").each( function() {
						if ($(this).attr("class")) {
							if (!validateField(this)) {
								validationError = true;
								//$(this).removeClass("focus");
								//$(this).parents("span").parent().children("span.required").html("*");

								if( validationError ) {
									errorMessage = (get_lang()=="en" ? 'Please fill' : 'กรุณากรอก');

									switch( $(this).attr("name") ) {

										case 'name':
											errorMessage += ' "' + (get_lang()=="en" ? 'Your Name' : 'ชื่อคุณ') + '"';
											$(this).focus();
											break;
										case 'email':
											errorMessage += ' "' + (get_lang()=="en" ? ($(this).val() == "" ? 'Email' : 'Correct Email Format') : ($(this).val() == "" ? 'อีเมล์' : 'อีเมล์ที่ถูกต้อง') ) + '"';
											$(this).focus();
											break;
										case 'friend_name':
											errorMessage += ' "' + (get_lang()=="en" ? 'Friend\'s Name' : 'ชื่อเพื่อน') + '"';
											$(this).focus();
											break;
										case 'friend_email':
											errorMessage += ' "' + (get_lang()=="en" ? 'Friend\'s Email' : 'อีเมล์เพื่อน') + '"';
											$(this).focus();
											break;
										case 'message':
											errorMessage += ' "' + (get_lang()=="en" ? 'Message' : 'ข้อความ') + '"';
											$(this).focus();
											break;
										case 'security_code':
											errorMessage += ' "' + (get_lang()=="en" ? 'Security Code' : 'รหัสยืนยัน') + '"';
											$(this).focus();
											break;
									}
									alert( errorMessage );
									return false;
								}
							}
						}
					});

					if ( !validationError ) {
						$("div#dialog-sendtofriend div.content div.result").remove();
						$("div#dialog-sendtofriend div.content div.box").fadeOut(function(){
							$("div#dialog-sendtofriend div.content").append("<div class=\"result\"><div class=\"loading\"></div></div>");
							$("div#dialog-sendtofriend div.content div.result").hide().fadeIn();
						});
						$("div#dialog-sendtofriend div.content div.title p").fadeOut();


						$.ajax({
							url: "api/"+$("form#frmSendtofriend").attr("action"),
							data: "action=sendtofriend&link="+window.location.href+"&"+$("form#frmSendtofriend").serialize(),
							type: "post",
							cache: false,
							dataType: "text",
							complete: function (result) {
								switch( result.responseText ) {
									case "1":
										$("div#dialog-sendtofriend div.content div.result div.loading").fadeOut(function(){
											$(this).remove();
											$("div#dialog-sendtofriend div.content div.result").hide().append("<div class=\"msg_complete\">"+( (get_lang()=="en" ? "Thank You<br />Your friend(s) will receive an email notifying them about this webpage. " : "ขอบคุณค่ะ <br />สำหรับการแนะนำเรื่องราวดีๆ ให้คนพิเศษของคุณ ตอนนี้ข้อความของคุณได้ส่งเรียบร้อยแล้วค่ะ") )+"</div>").fadeIn();

											setTimeout("$(\"div#dialog-sendtofriend\").dialog(\"close\");", 5000);
										});
										//$("div#dialog-subscribe").dialog("close");
										break;

									case "3": // Wrong Security Code
										$("div#dialog-sendtofriend div.content div.result div.loading").fadeOut(function(){
											$(this).remove();
											$("div#dialog-sendtofriend div.content div.result").hide().append("<div class=\"msg_error\">"+( (get_lang()=="en" ? "Security Code wrong.<br />Please try again." : "รหัสยืนยันไม่ถูกต้องค่ะ<br />กรุณาลองอีกครั้ง") )+"</div>").fadeIn();

											setTimeout("$(\"div#dialog-sendtofriend div.content div.msg_error\").fadeOut(function() { $(this).remove(); $(\"div#dialog-sendtofriend div.content div.box\").fadeIn(); $(\"div#dialog-sendtofriend div.content div.title p\").fadeIn(); })", 5000);
										});
										//$("div#dialog-subscribe").dialog("close");
										break;

									default:
										$("div#dialog-sendtofriend").dialog("close");

								}
							},
							error: function(result) {
								//alert(result.statusText);
							}
						});

					}/* else {
						alert( (get_lang()=="en" ? "Please fill complete information." : "กรุณากรอกข้อมูลให้ถูกต้องค่ะ") );
						$("form#frmSendtofriend input[type=text].error:first").focus();
					}*/
				});

				$("form#frmSendtofriend input.btn_submit").click(function(e){
					e.preventDefault();
					$("form#frmSendtofriend").submit();
				})
			}

			// Open Dialog
			if ( $("div#dialog-sendtofriend").length > 0 ) {

				$("div#dialog-sendtofriend .btn_close").click(function(e){
					e.preventDefault();
					$("div#dialog-sendtofriend").dialog("close");
				});

				$("div#dialog-sendtofriend .btn_unsubscribe").click(function(e){
					e.preventDefault();
					$("div#dialog-sendtofriend").dialog("close");

					dialogSendToFriend();
				});

				$("div#dialog-sendtofriend .btCaptcha").click(function(e){
					e.preventDefault();
					refreshCaptcha("form#frmSendtofriend");
				});

				$("div#dialog-sendtofriend").dialog({
					dialogClass: "dialogSendToFriend",
					width: 460,
					height: 420,
					autoOpen: true,
					modal: true,
					draggable: false,
					resizable: false,
					open: function(event, ui) {
						$("form#frmSendtofriend input[name=sendtofriend]").trigger("change");
					},
					close: function() {
						//allFields.val('').removeClass('ui-state-error');

						$("div#dialog-sendtofriend").dialog("destroy").remove();
					}
				});

				//$("div#dialog-subscribe").dialog("open");
			}

		},
		error: function(){
			unblockPage();
		}
	});
}

function dialogExchangeRatesCalculator() {
	blockPage();

	if ( $("div#dialog-forex_calculator").length > 0 ) {
		$("div#dialog-forex_calculator").dialog("destroy").remove();
	}
	//if ( unsubscribe==undefined) unsubscribe=false;

	$.ajax({
		url: "api/dialog.php",
		data: "action=exchange_rates_calculator",
		type: "get",
		cache: false,
		dataType: "text",
		complete: function (data) {
			unblockPage();
			$("div#dialog-forex_calculator").remove();

			var responseText = '';
			responseText = data.responseText;
			//alert(responseText)
			//alert($(responseText).filter("div#ajaxContent").length)
			if ( $(responseText).filter("div#ajaxContent").length > 0 ) {
				responseText = ($(responseText).filter("div#ajaxContent").html() || "");
			}
			//alert(responseText.length)
			if ( responseText.length > 0 ) {
				$("<div id=\"dialog-forex_calculator\">"+responseText+"</div>").appendTo("body").hide();
			}

			// Form Binding
			if ( $("form#frmCalculate").length > 0 ) {

				$("form#frmCalculate select").msDropDown({style:'width:185px !important'});

				$("form#frmCalculate input.numeric,form#frmCalculate input.float").each(function() {
					$(this).keypress(function(e) {
						return key_digit(e);
					});
					$(this).blur(function(){
						//$(this).formatCurrency({symbol:'', roundToDecimalPlace:2});
					});
					$(this).focus(function(){
						$(this).toNumber();
					});
				});

				$("form#frmCalculate input.btn_calculate").click(function(e){
					e.preventDefault();

					var validationError = false;
					$("form#frmCalculate input[type=text], form#frmCalculate select").each( function() {
						if ($(this).attr("class")) {
							if (!validateField(this)) validationError = true;
						}
					});

					if ( validationError ) {
						if ( $("form#frmCalculate input#amount_exchange").hasClass("focus") ) {
							alert((get_lang()=="en" ? "lease enter the amount you wish to exchange." : "กรุณาระบุจำนวนเงินที่ต้องการคำนวณ"));
							$("form#frmCalculate input#amount_exchange").focus();
						}
					} else {
						$("form#frmCalculate input#estimate_result").val((get_lang()=="en" ? "Calculating" : "กำลังทำการคำนวณ")).css("text-align", "center");

						$.getJSON("api/rates.php", {action: "exchange_rate_calculate", currency_buy: $("form#frmCalculate select#currency_buy").val(), currency_sell: $("form#frmCalculate select#currency_sell").val(), amount_exchange: $("form#frmCalculate input#amount_exchange").val()}, function(data) {
							if ( data!=undefined && data.length > 0 ) {
								var rates_title = data[0].estimate;

								$("form#frmCalculate input#estimate_result").val(data[0].estimate).formatCurrency({symbol:'', roundToDecimalPlace:2}).css("text-align", "right");
							}
						});
					}
				});
			}

			// Open Dialog
			if ( $("div#dialog-forex_calculator").length > 0 ) {

				$("div#dialog-forex_calculator .btn_close").click(function(e){
					e.preventDefault();
					$("div#dialog-forex_calculator").dialog("close");
				});

				$("div#dialog-forex_calculator").dialog({
					dialogClass: "dialogExchangeRate",
					width: 460,
					height: 330,
					autoOpen: true,
					modal: true,
					draggable: false,
					resizable: false,
					open: function(event, ui) {
						//$("form#frmSendtofriend input[name=sendtofriend]").trigger("change");
					},
					close: function() {
						//allFields.val('').removeClass('ui-state-error');

						$("div#dialog-forex_calculator").dialog("destroy").remove();
					}
				});

				//$("div#dialog-subscribe").dialog("open");
			}

		},
		error: function(){
			unblockPage();
		}
	});
}

function bindExchangeRateTime() {
	var eleTime = "form#frmExchangeRate select#update_time";
	$(eleTime).unbind('change');
	if ( $(eleTime).get(0).options.length > 0) {
		$(eleTime).bind("change", function() {
			if ( $(this).val().length > 0 ) {
				exchange_rates_list($(this).val());
			}
		});
	}
}

function exchange_rates_time(year, month, day) {
	var eleTime = "form#frmExchangeRate select#update_time";
	var optiondefault = '<option value="">'+(get_lang()=="en" ? 'Time' : 'เวลา')+'</option>' ;

	$(eleTime).unbind('change');
	$(eleTime).html('');

	if ( $.fn.msDropDown!=undefined ) {
		var oHandler = $(eleTime).msDropDown().data("dd");
		oHandler.disabled(true);
	} else {
		$(eleTime).attr("disabled", "disabled");
	}

	$.getJSON("api/rates.php", {action: "exchange_rate_time", y: parseInt(year||0), m: parseInt(month||0), d: parseInt(day||0)}, function(data) {

			var options = '';
			if ( data!=undefined && data.length > 0 ) {
				options+= optiondefault;
				for (var i=0; i<data.length; i++) {
					options+= '<option value="'+data[i].date+' '+data[i].time+'" '+(i==data.length-1 ? 'selected' : '')+'>'+data[i].time+'</option>';
				}
			} else {
				//options = '<option value="">N/A</option>' ;
			}

			$(eleTime).html(options);

			if ( $.fn.msDropDown!=undefined ) {
				var oHandler = $(eleTime).msDropDown().data("dd");
				oHandler.disabled(false);
			} else {
				$(eleTime).attr("disabled", "");
			}

			if ( data!=undefined && data.length > 0 ) {
				bindExchangeRateTime();
			}

			//modify
			exchange_rates_list(data[data.length-1].date+' '+data[data.length-1].time+'">'+data[data.length-1].time);

	});
}

function exchange_rates_list(date) {

	$("div#Container.plExchangeRates div.plContent div.cList table").fadeOut(function(){
		$("div#Container.plExchangeRates div.plContent div.cList div.cLoading").remove();
		$("div#Container.plExchangeRates div.plContent div.cList").append("<div class=\"cLoading\"></div>");

		$("div#Container.plExchangeRates div.plContent div.cList table tbody").empty();

		$.getJSON("api/rates.php", {action: "exchange_rate_title", date: date}, function(data) {

			if ( data!=undefined && data.length > 0 ) {
				var rates_title = data[0].title;


				$.getJSON("api/rates.php", {action: "exchange_rate_list", date: date}, function(data) {
				if ( data!=undefined && data.length > 0 ) {
					$("div#Container.plExchangeRates div.plContent div.cTitle h3").html(rates_title);

					$("div#Container.plExchangeRates div.plContent div.cList table tbody").empty();
					for (var i=0; i<data.length; i++) {
						var row = '';
						row+='<tr'+(i%2==1 ? ' class="alt"' : '')+'>';
						row+='<td class="currency '+data[i].currency+'">'+data[i].title+'</td>';
						row+='<td>'+data[i].buy_note+'</td>';
						row+='<td>'+data[i].buy_cdft+'</td>';
						row+='<td>'+data[i].btt+'</td>';
						row+='<td>'+data[i].sell_cdft+'</td>';
						row+='<td>'+data[i].sell_note+'</td>';
						row+='</tr>';

						$("div#Container.plExchangeRates div.plContent div.cList table tbody").append(row);
					}

					$("div#Container.plExchangeRates div.plContent div.cList div.cLoading").fadeOut(function(){
						$("div#Container.plExchangeRates div.plContent div.cList div.cLoading").remove();
						$("div#Container.plExchangeRates div.plContent div.cList table").fadeIn();
					});
				}
				});
			}
		});
	});
}


