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

var timer_menu_product = null;
var timer_menu_banking = null;

function resetContactusForm(){
	refreshCaptcha("form#frmContactUs");

	$('#return_message').hide().empty();

	$("form#frmContactUs input[type=text]").val("");
	$("form#frmContactUs textarea").val("");
	$("form#frmContactUs input[name=q]:first").attr("checked", "checked");
	//bindProvince("form#frmContactUs select#dprovince', 'form#frmContactUs select#ddistrict");
	$('#contactForm').fadeIn(function(){
		setDropDown("form#frmContactUs select#dprovince", "selectedIndex", 0);
		setDropDown("form#frmContactUs select#ddistrict", "selectedIndex", 0);
		disableDropDown("form#frmContactUs select#ddistrict", true);
		if( $("div#Container div.plContent form#frmContactUs").length > 0 ) {
			setDropDown("form#frmContactUs select#contact_subject", "selectedIndex", 0);
		}
	});
}

$(function(){
	$("a").each(function(){
		if ($(this).attr("href") == undefined || $(this).attr("href") == "#" || $(this).attr("href") == "") {
			$(this).attr({href:"#"});
			$(this).click( function(e) {e.preventDefault();});
		}
		$(this).focus( function() {$(this).blur();});
	});

	// Open new window
	$("a._blank").attr("target", "_blank");

	// GROUP WEBSITES
	if ( $("form#frmGrpWebsite").length > 0 ) {
		$("form#frmGrpWebsite select#grp_website").msDropDown({mainCSS:'dd2', visibleRows:26});

		$("form#frmGrpWebsite select#grp_website").change(function(){

			if ( $(this).val().length > 0 ) {
				//window.open($(this).val(), '_blank');

				if ( $("div.group_website form#frmGrpWebsiteHidden").length == 0 ) {
					$("div.group_website").append("<form id=\"frmGrpWebsiteHidden\" method=\"get\" action=\"\" target=\"_blank\"></form>");
				}

				$("form#frmGrpWebsiteHidden").attr("action", $(this).val());
				$("form#frmGrpWebsiteHidden").attr("target", "_blank");
				$("form#frmGrpWebsiteHidden").submit();
			}
		});
	}

	// CURRENT LOCATION
	if ( $("form#frmLocation").length > 0 ) {
		$("form#frmLocation select#location").msDropDown({mainCSS:'dd2'});

		$("form#frmLocation select#location").change(function(){
			if ( $(this).val().length > 0 ) {
				//window.open($(this).val());

				if ( $("div.location form#frmLocationHidden").length == 0 ) {
					$("div.location").append("<form id=\"frmLocationHidden\" method=\"get\" action=\"\" target=\"_blank\"></form>");
				}
				$("form#frmLocationHidden").attr("action", $(this).val());
				$("form#frmLocationHidden").attr("target", "_blank");
				$("form#frmLocationHidden").submit();
			}
		});
	}

	// LOCATE US
	if ( $("form#frmLocateUs").length > 0 ) {
		$("form#frmLocateUs select").msDropDown({style:'width:130px !important'});
		bindRegion("form#frmLocateUs select#locate_region", "form#frmLocateUs select#locate_province", "form#frmLocateUs select#locate_amphur");

		$("form#frmLocateUs").submit(function() {
			var url = '';
			/*url+= $.url.attr('protocol')+'://'+$.url.attr('host');
			if ($.url.attr('port') != '80') url+= ':'+$.url.attr('port');

			if ($.url.segment()>0 && $.url.segment(0)=='en') url+= '/en';

			url+= '/locate_us';*/
			url = $("form#frmLocateUs").attr("action");
			$("form#frmLocateUs select").each( function(idx) {
				url+= ( $(this).val().length > 0 ? $(this).val() : 'all')+'/' ;
			});
			//$("form#frmSearch input").remove(); //Remove Query String
			//$("form#frmSearch").attr("action", url);
			//alert(url);
			location.href = url;
			return false;
		});
	}

	// PROPERTIES
	if ( $("form#frmProperty").length > 0 ) {
		$("form#frmProperty select").msDropDown();
		bindRegion("form#frmProperty select#property_region", "form#frmProperty select#property_province", "form#frmProperty select#property_amphur");
	}

	// MAP
	if( $("div.plLocateUs div.plContent div.cTab").length > 0 ) {
		$("div.plLocateUs div.plContent div.cTab").tabs({ fxAutoHeight: true, selected: current_tabs });
	}

	/*if( $("div#flag_branch").length > 0 ) {

		var results = "action=search&param="+$("div#flag_branch").metadata().param+"&"+$("form#frmLocateUs").serialize();
		$('div#flag_branch').html('<div class="loading"></div>').fadeIn();

		$.post("api/locate_us.php", results, function(data) {
			$('div#flag_branch').html( data );
		});
	}*/


	// CONTACT US
	if ( $("form#frmContactUs").length > 0 ) {
		$("form#frmContactUs select").msDropDown();
	}

	// INVESTOR RELATION
	if( $("div#Container div.cList div.cTab").length > 0 ) {
		$("div#Container div.cList div.cTab").tabs({ fxAutoHeight: true });
	}

	// MAIN MENU
	if ( $("div#Menu").length > 0 ) {
		$("div#Menu ul ul li:first a").addClass("first");

		// INTERNET BANKING
		$("div#Menu a.banking").click(function(){
			var ele = $("div#Menu ul.banking");
			if ( $(ele).css("display") == "none" ) {
				$(ele).fadeIn();
			}
		}).mouseover(function(){
			if (timer_menu_banking != null) {
				clearTimeout(timer_menu_banking);
			}
		}).mouseout(function(){
			clearTimeout(timer_menu_banking);
			timer_menu_banking = setTimeout(function(){
				$("div#Menu ul.banking").fadeOut();
			}, 500);
		});

		$("div#Menu ul.banking li").mouseover(function(){
			if (timer_menu_banking) {
				clearTimeout(timer_menu_banking);
			}
		}).mouseout(function(){
			clearTimeout(timer_menu_banking);
			timer_menu_banking = setTimeout(function(){
				$("div#Menu ul.banking").fadeOut();
			}, 500);
		});
	}

	// SUB MENU
	if ( $("div#subMenu").length > 0 ) {
		$("div#subMenu > ul > li:last > a").addClass("last");

		$("div#subMenu ul > li").click(function(e){
			var ele = $(this).find("ul");
			if ( $(ele).css("display") == "none" ) {
				if (timer_menu_product) {
					clearTimeout(timer_menu_product);
				}

				$("div#subMenu ul > li").removeClass("active");
				$("div#subMenu ul > li > ul").fadeOut();
				$(this).addClass("active");

				if ( ele ) {
					if ( ($(this).position().left + ele.outerWidth()) > $(this).parents("div#subMenu").outerWidth()) {
						ele.css("left", $(this).parents("div#subMenu").outerWidth() - ele.outerWidth());
					} else {
						ele.css("left", $(this).position().left);
					}
					ele.css("top", $(this).position().top+18);
					ele.fadeIn();
				}
			}

			//$(this).find("ul").fadeIn();
		}).mouseover(function(){
			if (timer_menu_product != null) {
				clearTimeout(timer_menu_product);
			}
		}).mouseout(function(){
			$(this).removeClass("active");
			//$(this).find("ul").fadeOut();
			clearTimeout(timer_menu_product);
			timer_menu_product = setTimeout(function(){
				$("div#subMenu ul > li > ul").fadeOut();
			}, 500);
		});

		$("div#subMenu ul > li > ul > li").mouseover(function(){
			if (timer_menu_product) {
				clearTimeout(timer_menu_product);
			}
		}).mouseout(function(){
			clearTimeout(timer_menu_product);
			timer_menu_product = setTimeout(function(){
				$("div#subMenu ul > li > ul").fadeOut();
			}, 500);
		});
	}

	// CONTENT SEARCH
	if ( $("form#frmSearch").length > 0 ) {
		$("form#frmSearch input[name=keyword]").focus(function(){
			if ( $(this).val() == (get_lang()=="en" ? 'Search' : 'ค้นหา') ) $(this).val('');
		});
		$("form#frmSearch input[name=keyword]").blur(function(){
			if ( $(this).val() == '' ) $(this).val( (get_lang()=="en" ? 'Search' : 'ค้นหา') );
		});
		$("form#frmSearch input[name=keyword]").blur();

		$("form#frmSearch").submit(function() {
			var validationError = false;

			// for each field test it
			$("form#frmSearch input[type=text]").each( function() {
				if ($(this).attr("class")) {
					if (!validateField(this)) validationError = true;
					if ( $(this).val()=='Search' || $(this).val()=='ค้นหา' ) validationError = true;
				}
			});

			if (!validationError) {
				var url = '';
				/*url+= $.url.attr('protocol')+'://'+$.url.attr('host');
				if ($.url.attr('port') != '80') url+= ':'+$.url.attr('port');
				/*var segments = $.url.segment();
				for(i=0;i<$.url.segment();i++) {
					url+='/'+$.url.segment(i);
					if ($.url.segment(i)=='search') {
						break;
					}
				}* /
				if ($.url.segment() >0 && $.url.segment(0)=='en') url+= '/en';
				//url+= '/search/'+$.URLEncode($("form#frmSearch input[type=text]:first").val());
				url+= '/search/'+$("form#frmSearch input[type=text]:first").val();*/

				url = $("form#frmSearch").attr("action");
				if ($("form#frmSearch").attr("action").substr(-1) != '/') url+= '/';
				url+= $("form#frmSearch input[name=keyword]").val()+'/';

				//$("form#frmSearch input").remove(); //Remove Query String
				//$("form#frmSearch").attr("action", url);
				location.href = url;
				validationError = true;
			} else {
				$("form#frmSearch input[type=text]:first").focus();
			}

			return !validationError;
		});
	}

	if ( $("form#frmSearchBox").length > 0 ) {
		$("form#frmSearchBox").submit(function() {
			var validationError = false;

			// for each field test it
			$("form#frmSearchBox input[type=text]").each( function() {
				if ($(this).attr("class")) {
					if (!validateField(this)) validationError = true;
				}
			});

			if (!validationError) {
				var url = '';
				/*url+= $.url.attr('protocol')+'://'+$.url.attr('host');
				if ($.url.attr('port') != '80') url+= ':'+$.url.attr('port');
				/*var segments = $.url.segment();
				for(i=0;i<$.url.segment();i++) {
					url+='/'+$.url.segment(i);
					if ($.url.segment(i)=='search') {
						break;
					}
				}* /
				if ($.url.segment() >0 && $.url.segment(0)=='en') url+= '/en';
				//url+= '/search/'+$.URLEncode($("form#frmSearchBox input[type=text]:first").val());
				url+= '/search/'+($("form#frmSearchBox input[type=text]:first").val());*/

				url = $("form#frmSearchBox").attr("action");
				if ($("form#frmSearchBox").attr("action").substr(-1)!='/') url+= '/';
				url+= $("form#frmSearchBox input[name=keyword]").val()+'/';

				//alert(url);
				//$("form#frmSearch input").remove(); //Remove Query String
				//$("form#frmSearch").attr("action", url);
				location.href = url;
				validationError = true;
			} else {
				$("form#frmSearchBox input[type=text]:first").focus();
			}

			return !validationError;
		});
	}

	// SUBSCRIBE ENEWSLETTER
	if ( $("div#Footer div.Enews a").length > 0 ) {
		$("div#Footer div.Enews a:first").click(function(e){
			e.preventDefault();
			dialogSubscribe();
		});
	}

	//	 SEND TO FRIEND
	if ( $("div.print a.send").length > 0 ) {
		$("div.print a.send").click(function(e){
			e.preventDefault();
			dialogSendToFriend();
		});
	}

	// HOME > WHAT'S NEW
	/*if ( $("div#Container div.WhatNew").length > 0 ) {
		//$("div#Container div.WhatNew div.Content > ul").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true);

		$("div#Container div.WhatNew div.Content").tabs({fx:{opacity: "toggle"}, event: "mouseover"}).tabs("rotate", 10000, true);
		$("div#Container div.WhatNew div.Content").hover(function(){
				$("div#Container div.WhatNew div.Content").tabs("rotate", 0, true);

				/*var idx = $("div#Container div.WhatNew div.Content a").index(this);
				$("div#Container div.WhatNew div.Content").tabs("select", idx);* /
			},
			function() {
				$("div#Container div.WhatNew div.Content").tabs("rotate", 10000, true);
			}
		);
	}*/

	// GO TO PAGE
	if( $("form#frmGotoPage").length > 0 ) {
		$("form#frmGotoPage").each( function() {
			/*$(this).submit(function () {
				split = $(this).attr('action').split('/');
				split[3] = ( $("form#frmGotoPage input#page").val() == "" ? 1 : $("form#frmGotoPage input#page").val() );
				newUrl = split[0]+'/'+split[1]+'/'+split[2]+'/'+split[3];
				$(this).attr('action', newUrl);

				$(this).submit();
			});*/
			$(this).submit(function () {
				var validationError = false;

				// for each field test it
				$("form#frmGotoPage input[type=text]", this).each( function() {
					if ($(this).attr("class")) {
						if (!validateField(this)) validationError = true;
					}
				});

				if (!validationError) {
					var url = '';

					if ( $.url != undefined && $.url().segment.length > 0 ) {
						$.each($.url().segment(), function(index, value) {
							if (value=='page') {
								return false;
							} else {
								url+='/'+value;
							}
						});
					}
					var curr_page = $("form#frmGotoPage input[type=text]:first").val();
					if( curr_page <= 0 ) curr_page = 1;

					url+='/page/'+curr_page+'/';
					//alert(url)
					//$("form#frmGotoPage input").remove();
					//$("form#frmGotoPage").attr("action", url);
					location.href = url;
					validationError = true;
				} else {
					$("form#frmGotoPage input[type=text]:first").focus();
				}

				return !validationError;
			});
		});
	}

	//  LOCATE US GO TO PAGE
	if( $("form.frmGotoPage").length > 0 ) {
		$("form.frmGotoPage").each( function() {
			$(this).submit(function () {
				var validationError = false;

				// for each field test it
				$("form#"+$(this).attr("id")+" input[type=text]", this).each( function() {
					if ($(this).attr("class")) {
						if (!validateField(this)) validationError = true;
					}
				});

				if (!validationError) {
					var url = '';
					if ( $("form#"+$(this).attr("id")).attr("action").length > 1 ) {
						url = $("form#"+$(this).attr("id")).attr("action");
						if ($("form#"+$(this).attr("id")).attr("action").substr($("form#"+$(this).attr("id")).attr("action").length-1,1) == '/') {
							url = $("form#"+$(this).attr("id")).attr("action").substr(0, $("form#"+$(this).attr("id")).attr("action").length-1);
						}
					} else {
						if ( $.url != undefined && $.url().segment.length > 0 ) {
							$.each($.url().segment(), function(index, value) {
								if (value=='page') {
									return false;
								} else {
									url+='/'+value;
								}
							});
						}
					}
					var curr_page = $(this).find("input[type=text]:first").val();
					if( curr_page <= 0 ) curr_page = 1;

					url+='/page/'+curr_page+'/';

					location.href = url;
				} else {
					$("form#"+$(this).attr("id")+" input[type=text]:first").focus();
				}
				validationError = true;

				return !validationError;
			});
		});
	}

	// CONTENT CONTACT
	if ( $('div#Container div.cContact').length > 0 || $('div#Container div.plContent').length > 0 ) {

		if( $('div#Container div.cContact').length > 0 ) {
			//$('div#Container div.cTab').tabs({fxShow: {height: 'show', opacity: 'show'}, fxSpeed: 'normal'});
			$("div#Container div.cContact div.cTab").tabs({ fxAutoHeight: true });
		}

		// Form Let Content Info
		if ( $("div#Container div.cContact form#frmContactUs").length > 0 || $("div#Container div.plContent form#frmContactUs").length > 0 ) {
			if ( $("div#Container div.cContact form#frmContactUs").length > 0 ) {
				bindProvince('form#frmContactUs select#dprovince', 'form#frmContactUs select#ddistrict');
			}

			$("form#frmContactUs").each( function() {

				// handle submissions without filling any field
				$(this).submit(function () {
					var validationError = false;
					var errorMessage = '';
					//$("#Err_Msg").empty();
					//$("form#frmContactUs span.required").empty();

					// for each field test it
					$("form#frmContactUs input[type=text], form#frmContactUs input[type=radio], form#frmContactUs select, form#frmContactUs 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 ) {
									if( $(this).is("select") || $(this).attr("type") == "radio") {
										errorMessage = (get_lang()=="en" ? 'Please select' : 'กรุณาเลือก');
									}else{
										errorMessage = (get_lang()=="en" ? 'Please fill' : 'กรุณากรอก');
									}

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

										case 'firstname':
											errorMessage += ' "' + (get_lang()=="en" ? 'First Name' : 'ชื่อ') + '"';
											$(this).focus();
											break;
										case 'lastname':
											errorMessage += ' "' + (get_lang()=="en" ? 'Last Name' : 'นามสกุล') + '"';
											$(this).focus();
											break;
										case 'telephone':
											errorMessage += ' "' + (get_lang()=="en" ? 'Telephone' : 'โทรศัพท์') + '"';
											$(this).focus();
											break;
										case 'email':
											errorMessage += ' "' + (get_lang()=="en" ? ($(this).val() == "" ? 'Email' : 'Correct Email Format') : ($(this).val() == "" ? 'อีเมล์' : 'อีเมล์ที่ถูกต้อง') ) + '"';
											$(this).focus();
											break;
										case 'dprovince':
											errorMessage += ' "' + (get_lang()=="en" ? 'Province' : 'จังหวัด') + '"';
											break;
										case 'ddistrict':
											errorMessage += ' "' + (get_lang()=="en" ? 'District' : 'อำเภอ') + '"';
											break;
										case 'customer':
											if ( !$("form#frmContactUs input[name="+$(this).attr("name")+"]").is(":checked")) {
												errorMessage = ' "' + (get_lang()=="en" ? 'Are you a CIMB Thai Bank Customer?' : 'ปัจจุบันคุณเป็นลูกค้าของธนาคาร ซีไอเอ็มบี ไทย หรือไม่?') + '"';
											}
											break;
										case 'security_code':
											errorMessage += ' "' + (get_lang()=="en" ? 'Security Code' : 'รหัสยืนยัน') + '"';
											$(this).focus();
											break;
										// Contact Us
										case 'contact_subject':
											errorMessage += ' "' + (get_lang()=="en" ? 'Type Of Contact' : 'เรื่องที่จะติดต่อ') + '"';
											$(this).focus();
											break;
										case 'subject':
											errorMessage += ' "' + (get_lang()=="en" ? 'Subject' : 'หัวเรื่อง') + '"';
											$(this).focus();
											break;
										case 'message':
											errorMessage += ' "' + (get_lang()=="en" ? 'Message' : 'เนื้อหา') + '"';
											$(this).focus();
											break;

									}
									alert( errorMessage );
									return false;
								}
							}
						}

					});


					if ( !validationError ) {
						var results = "action=send_contact&param="+$("div#contactForm").metadata().param+"&"+$("form#frmContactUs").serialize();
						$('#contactForm').hide();
						$('#return_message').html('<div class="loading"></div>').fadeIn();

						$.post("api/api.php", results, function(data) {
							if( data == 'Success') {

								$('#return_message').fadeOut(function() {
									$.fn.prettyPhoto({callback: function(){ resetContactusForm(); }});
									$.prettyPhoto.open( baseUrl()+'thankyou?iframe=true&width=400&height=200&iframe=true' );
								});

								/*$('#return_message').fadeOut(function(){

									$(this).html('<div class="message"><h3>'+(get_lang()=="en" ? 'Thank you for your submission.' : 'ขอบคุณสำหรับการติดต่อ ทางธนาคารจะติดต่อคุณกลับโดยเร็วที่สุด')+'<br/><br/><a href="#" id="backtosendform">'+(get_lang()=="en" ? '&laquo; Back to Submit Form' : '&laquo; กลับหน้าส่งแบบฟอร์ม')+'</a></h3></div>').fadeIn(function(){

										// BACK TO FORM
										$("div#return_message a").click(function(e) {
											e.preventDefault();
											refreshCaptcha("form#frmContactUs");

											$('#return_message').hide().empty();

											$("form#frmContactUs input[type=text]").val("");
											$("form#frmContactUs textarea").val("");
											$("form#frmContactUs input[name=q]:first").attr("checked", "checked");
											//bindProvince("form#frmContactUs select#dprovince', 'form#frmContactUs select#ddistrict");
											$('#contactForm').fadeIn(function(){
												setDropDown("form#frmContactUs select#dprovince", "selectedIndex", 0);
												setDropDown("form#frmContactUs select#ddistrict", "selectedIndex", 0);
												disableDropDown("form#frmContactUs select#ddistrict", true);
												if( $("div#Container div.plContent form#frmContactUs").length > 0 ) {
													setDropDown("form#frmContactUs select#contact_subject", "selectedIndex", 0);
												}
											});
										});
									});
								});*/
							}else if( data == 'Invalid security code' ) {
								$('#return_message').fadeOut(function() {
									$('#contactForm').fadeIn();
								});

								alert( (get_lang()=="en" ? 'Invalid security code' : 'รหัสยืนยันไม่ถูกต้องค่ะ') );
							}
						})
						.error(function() {
								$('#return_message').fadeOut(function() {
									$('#contactForm').fadeIn();
								});
								alert( (get_lang()=="en" ? 'An error. During the data transfer.' : 'เกิดการผิดพลาดระหว่างกาำรส่งข้อมูล') );
						});

					}
					return false;
				});

				// handle select text
				$("form#frmContactUs input[type=text], form#frmContactUs select, form#frmContactUs textarea").each( function() {
					$(this).focus( function() {
						$(this).select();
						if ( !$(this).hasClass("focus") ) $(this).addClass("focus");
					});

					$(this).blur( function() {
						$(this).val( jQuery.trim( $(this).val() ) );
						if ( $(this).hasClass("focus") ) $(this).removeClass("focus");
						if ( $(this).hasClass("captcha") ) { $(this).val( $(this).val().toLowerCase() ); }
					});
				});

				$("form#frmContactUs .btCaptcha").click(function(e){
					e.preventDefault();
					refreshCaptcha("form#frmContactUs");
				});

			});

		};
	}

	// PAGE BANNER
	if ( $("div.pageBanner").length > 0 ) {
		if ( $("div.pageBanner div.nivoSlider img").length > 1 ) {
			$('div.pageBanner div.nivoSlider').nivoSlider({
				effect:'random', //Specify sets like: 'fold,fade,sliceDown'
				slices:10,
				animSpeed: 500, //Slide transition speed
				pauseTime: 5000,
				startSlide:0, //Set starting Slide (0 index)
				directionNav:false, //Next & Prev
				directionNavHide:true, //Only show on hover
				controlNav:true, //1,2,3...
				controlNavThumbs:false, //Use thumbnails for Control Nav
				controlNavThumbsFromRel:false, //Use image rel for thumbs
				controlNavThumbsSearch: '.jpg', //Replace this with...
				controlNavThumbsReplace: '_thumb.jpg', //...this in thumb Image src
				keyboardNav:true, //Use left & right arrows
				pauseOnHover:true, //Stop animation while hovering
				manualAdvance:false, //Force manual transitions
				captionOpacity:0.8 //Universal caption opacity
			});
		} else {
			$("div.pageBanner div.nivoSlider img:first").show();
		}

		// Banner Flash
		/*if ( $("div.pageBanner div.nivoSlider a.flash").length > 0 ) {
			$("div.pageBanner div.nivoSlider a.flash").each(function(){
				var meta = $(this).metadata();
				$(this).flash({
					swf: meta.swf,
					width: meta.width,
					height: meta.height,
					wmode: 'opaque',
					salign: 'tl',
					menu: "false",
					scale: "scale"
				});
			});
		}*/

		// Banner Flash
		if ( $("div.pageBanner div.flashBanner").length > 0 ) {
			$("div.pageBanner div.flashBanner").each(function(){
				var meta = $(this).metadata();
				$(this).flash({
					swf: meta.swf,
					width: meta.width,
					height: meta.height,
					wmode: 'opaque',
					salign: 'tl',
					menu: "false",
					scale: "scale"
				});
			});
		}
	}

	// FOREIGN EXCHANGE RATES
	if ( $("div#Container.plExchangeRates").length > 0 ) {
		$("form#frmExchangeRate select").msDropDown();

		if ( get_lang()=="th") jQuery(function(a){a.datepicker.setDefaults(a.datepicker.regional["th-TH"])});
		$("form#frmExchangeRate input#exchange_date").datepicker({
			showOn: "button",
			buttonImage: "images/rates/icon-date.gif",
			buttonImageOnly: true,
			numberOfMonths: 1,
			minDate: '-1y',
			maxDate: new Date(),
			dateFormat: "dd/mm/y",
			beforeShowDay: $.datepicker.noWeekends,
			onSelect: function(dateText, inst) {
				var year = parseInt(inst.currentYear || 0);
				var month = parseInt(inst.currentMonth || 0) + 1;
				var day = parseInt(inst.currentDay || 0);

				exchange_rates_time(year, month, day);
			}
		});

		$("div#Container.plExchangeRates div.cTools a.bt_current").click(function(e){
			e.preventDefault();
			exchange_rates_list('last');
		});

		$("div#Container.plExchangeRates div.cTools a.bt_calculate").click(function(e){
			e.preventDefault();
			dialogExchangeRatesCalculator();
		});

		bindExchangeRateTime();
	}

	// PROPERTIES SEARCH
	if ( $("form#frmProperty").length > 0 ) {

		$("form#frmProperty").submit(function() {
			var validationError = true;

			var url = '';
			if ( $.url != undefined && $.url().segment.length > 0 ) {
				$.each($.url().segment(), function(index, value) {
					if (value=='search') {
						return false;
					} else {
						url+='/'+value;
					}
				});
			}

			//url+= '/search/'+$.URLEncode($("form#frmSearch input[type=text]:first").val());
			url+= '/search';
			url+= '/'+($("form#frmProperty select#property_type").val()||'all')+'-'+($("form#frmProperty select#property_region").val()||'all')+'-'+($("form#frmProperty select#property_province").val()||'all')+'-'+($("form#frmProperty select#property_amphur").val()||'all')+'-'+($("form#frmProperty select#property_price").val()||'all')+'-'+($("form#frmProperty input#code").val()||'all')+'/';
			//$("form#frmSearch input").remove(); //Remove Query String
			//$("form#frmSearch").attr("action", url);

			location.href = url;
			validationError = true;

			return !validationError;
		});
	}


	// Initial prettyPhoto
	$("a[rel^=\'prettyPhoto\']").prettyPhoto({
		slideshow: false,
		show_title: false,
		overlay_gallery: false,
		modal: true,
		deeplinking: false,
		default_width: 700,
		default_height: 400,
		allow_resize: false,
		keyboard_shortcuts: false
	});

	if ( $("div.Content a.ico-map").length > 0 ) {
		$("div.Content a.ico-map").each(function(){
			$(this).click(function(e){
				var meta = $(this).metadata();
				var download_url = meta.download_url;
				var print_url = meta.print_url;
				e.preventDefault();
				if ($.fn.prettyPhoto!=undefined) {
					var api_url = $(this).attr("href");
					if ( api_url.length > 1) {
						var api_titles = [];
						var api_descriptions = [];
						$.prettyPhoto.open( api_url, api_titles, api_descriptions, download_url, print_url );
					}
				}
			});
		});
	}

	if ( $("div.Content a.ico-google-map").length > 0 ) {
		$("div.Content a.ico-google-map").each(function(){
			$(this).click(function(e){
				e.preventDefault();

				if ($.fn.prettyPhoto!=undefined) {
					var api_url = $(this).attr("href");
					//api_url += "?iframe=true&width=700";
					api_url += "?iframe=true&width=100%&height=100%";
					var api_titles = [];
					var api_descriptions = [];
					$.prettyPhoto.open( api_url, api_titles,api_descriptions);
				}
			});
		});
	}

	if ( $("div.Content a.view_branch").length > 0 ) {
		$("div.Content a.view_branch").each(function(){
			$(this).click(function(e){
				e.preventDefault();
				var meta = $(this).metadata();
				var download_url = meta.download_url;
				var print_url = meta.print_url;

				if ($.fn.prettyPhoto!=undefined && meta.popup_url!=undefined) {
					//var api_url = $(this).attr("href");
					var api_url = meta.popup_url;
					api_url += "?iframe=true&width=750&height=500";
					if ( api_url.length > 1) {
						var api_titles = [];
						var api_descriptions = [];
						$.prettyPhoto.open( api_url, api_titles, api_descriptions, download_url, print_url );

					}

				}
			});
		});
	}

	// Print This Page
	$("div#breadcrumbs a.print").click(function(e){
		e.preventDefault();

		var url = '';
		var path = pathUrl();
		var segments = $.url(path).segment();
		url = baseUrl();
		if ( url.substr(-1) == '/') url = url.substr(0, url.length-1);
		if ( $.url != undefined && $.url(path).segment.length > 0 ) {
			if ( $.inArray("en", $.url(path).segment()) != -1 ) {
				url+='/en';
			}
			url+='/print';
			$.each($.url(path).segment(), function(index, value) {
				if (value!='en') {
					url+='/'+value;
				}
			});

		}

		if ( $("form#frmExchangeRate").length > 0 ) { // GET Date & Time
			/*var y = ''; var m = ''; var d = ''; var time = '';
			y = $("form#frmExchangeRate input#exchange_date").datepicker('getDate').getFullYear();

			if ( $("form#frmExchangeRate input#exchange_date").datepicker('getDate').getMonth() < 9 ) {
				m = '0'+($("form#frmExchangeRate input#exchange_date").datepicker('getDate').getMonth()+1);
			} else {
				m = ($("form#frmExchangeRate input#exchange_date").datepicker('getDate').getMonth()+1);
			}

			if ( $("form#frmExchangeRate input#exchange_date").datepicker('getDate').getDate() < 10 ) {
				d = '0'+$("form#frmExchangeRate input#exchange_date").datepicker('getDate').getDate();
			} else {
				d = $("form#frmExchangeRate input#exchange_date").datepicker('getDate').getDate();
			}*/

			if ( $.inArray("foreign_exchange_rates", $.url(path).segment()) != 1 ) {
				url+='/foreign_exchange_rates';
			}
			url+= '/'+$("form#frmExchangeRate select#update_time").val();
		}
		if ( url.substr(-1) != '/') url+='/';

		if ($.fn.prettyPhoto!=undefined && url.length > 0) {
			var api_url = url;
			api_url += "?iframe=true&width=750&height=500";
			var api_titles = [];
			var api_descriptions = [];
			$.prettyPhoto.open( api_url, api_titles,api_descriptions);
		}
	});

	$('a.pp_print').live('click',function(e){

		if ($.fn.prettyPhoto!=undefined && $(this).attr('href').length > 1) {
			$.prettyPhoto.close();

			var api_url = $(this).attr('href');

			api_url += "?iframe=true&width=750&height=500";
			var api_titles = [];
			var api_descriptions = [];

			setTimeout('$.prettyPhoto.open("'+api_url+'");', 500);
		}
		return false;
	});
});

$(document).ready(function(){
	if ( $.url != undefined && $.url().segment.length > 0) {

		if ( $.inArray("unsubscribe", $.url().segment()) != -1 ) {
			dialogSubscribe(true);
		} else if ( $.inArray("subscribe", $.url().segment()) != -1 ) {
			dialogSubscribe(false);
		}
	}
});
