// Swiper Setting
var isStepsSwiperActive = false;
var stepsSwiper;
// Form
var isSendingConfirmationForm = false;
// User Input Value
var currencyId;
var amount;
var districtId;
var branchId;
var date;
var name;
var tel;
var email;
var tc;
var captcha;
var branchesList = new Array();
var currencyList = new Array();
// 2017 Holidays
// Hardcode here
var holidays = ["2017-01-02", "2017-01-28", "2017-01-30", "2017-01-31", "2017-04-04", "2017-04-14", "2017-04-15", "2017-04-17", "2017-05-01", "2017-05-03", "2017-05-30", "2017-07-01", "2017-10-02", "2017-10-05", "2017-10-28", "2017-12-25", "2017-12-26"];
//var holidays = ["2017-01-02", "2017-01-12", "2017-01-28", "2017-01-30", "2017-01-31", "2017-04-04", "2017-04-14", "2017-04-15", "2017-04-17", "2017-05-01", "2017-05-03", "2017-05-30", "2017-07-01", "2017-10-02", "2017-10-05", "2017-10-28", "2017-12-25", "2017-12-26"];
// Pick Up date Setting
var currentDate = new Date();
if (typeof startDate === 'undefined') {
log('not defined');
var startDate = new Date();
} else {
log('startDate:', startDate);
}
var endDate = new Date()
, startCount = 1
, endCount = 1
, startDays = 2
, period = 7 // Includes startDate
, endDays = startDays + period - 1;
var debug = false;
$(document).ready(function() {
log('Ready!', isMobile() );
if (detectIE()===false) {
} else {
log('It is IE! ', detectIE());
$('html').addClass('ie');
}
resetAllForm();
getAllCurrencyList();
getAllBranchesList();
initEvent();
//fadeInSiteWrapper();
//fadeOutOverlay();
});
function fadeInSiteWrapper() {
$('#site-wrapper').addClass('fade-in');
}
function fadeOutOverlay() {
log('fadeOutOverlay');
$('.overlay').fadeOut(200, function() {
$('body').addClass('active');
});
}
function initEvent() {
// testing
$('.btn-testing').click(function(evt) {
evt.preventDefault();
log('click btn-testing');
resetAllForm();
//var districtId = 1;
//var branchId = 11;
//log($('#input-district option[data-id="' + districtId + '"]'));
//$('#input-district option[data-id="' + districtId + '"]').prop('selected',true);
});
// EVENT
$('.btn-switch-lang').click(function(evt) {
evt.preventDefault();
switchLang('en', 'zh');
});
//
$('.navbar-lang-nav a').click(function(evt) {
evt.preventDefault();
var from = $(this).data('fromLang');
var to = $(this).data('toLang');
switchLang(from, to);
});
// NAV EVENT
$('.btn-nav').click(function(evt) {
var target = $(this).data('target');
log('Click nav:', target);
if (target=="") {
} else {
evt.preventDefault();
$(window).scrollTo( $(target), 600, {'axis':'y'});
}
});
// SECTION 1 EVENT
// ------------------------------------------------------------------
$( '.btn-calculate').click(function(evt) {
evt.preventDefault();
//var currencyId = $('#input-currency').val();
var currencyId = $('#input-currency').find(':selected').data('id');
var amount = $('#input-amount').val();
//log('Click Button Calculate', currencyId);
// Validate
var currencyError = false;
var amountError = false;
var currencyErrorMsg = '';
var amountErrorMsg = '';
if(currencyId == '-1'){
//log( $('#input-currency').parent('.form-group') );
currencyError = true;
currencyErrorMsg = '請選擇貨幣';
}
if(amount == '' || !isNumber(amount)){
//$('#input-amount').parents('.form-group').addClass('has-error');
amountError = true;
amountErrorMsg = '請輸入金額';
//alert('2');
} else {
//alert('3');
if (currencyId != '-1') {
//alert('4');
// Check Rules
var selectedCurrency = currencyList[currencyId - 1];
var currency = selectedCurrency.currency;
var min = selectedCurrency.min;
var max = selectedCurrency.max;
var unit = selectedCurrency.unit;
//log('selectedCurrency:', selectedCurrency, min, amount);
if (amount < min) {
amountError = true;
var num = numberToMoneyFormat(min);
amountErrorMsg = '你必須最少兌換 ' + num + ' ' + currency + '';
} else if (amount > max) {
amountError = true;
var num = numberToMoneyFormat(max);
amountErrorMsg = '只可兌換最多 ' + num + ' ' + currency + '';
} else if ( !isInteger(amount/unit) ) {
amountError = true;
amountErrorMsg = '輸入金額必須為'+ unit +'之倍數';
}
}
}
if (!amountError && !currencyError) {
$('#input-currency').parents('.form-group').removeClass('has-error');
$('#input-amount').parents('.form-group').removeClass('has-error');
// Tracking
floodlight('1', 'fxfor0');
$( '.section-response' ).hide();
$( '.section-steps' ).slideDown( "slow", function(){
//if (isMobile()) {
$(window).scrollTo( $('.section-steps'), 600, {'axis':'y'});
//}
stepsSwiper.slideTo(0);
});
} else {
$('#input-currency').parents('.form-group').removeClass('has-error').find('.help-block').html('');
$('#input-amount').parents('.form-group').removeClass('has-error').find('.help-block').html('');
if (currencyError) {
$('#input-currency').parents('.form-group').addClass('has-error');
$('#input-currency').parents('.form-group').find('.help-block').html(currencyErrorMsg);
}
if (amountError) {
$('#input-amount').parents('.form-group').addClass('has-error');
$('#input-amount').parents('.form-group').find('.help-block').html(amountErrorMsg);
}
}
});
$('#input-currency').on('change', function(e){
//var currencyId = e.target.value;
var currencyId = $(this).find(':selected').data('id');
log('input-currency: ', currencyId);
if(currencyId != '-1'){
$('#input-currency').parents('.form-group').removeClass('has-error');
$('.section-calculator .btn-calculate').removeClass('disabled');
}else{
//$('.section-calculator .btn-calculate').removeClass('disabled').addClass('disabled');
}
});
$('#input-amount').on('input',function(e){
if( $('#input-amount').parents('.form-group').hasClass('has-error') ) {
//$('#input-amount').parents('.form-group').removeClass('has-error');
}
});
$('#input-amount').on('keypress', function(e) {
return e.which !== 13;
});
// EVENT STEP 1
// ------------------------------------------------------------------
$('#input-district').on('change', function(e){
//var districtId = e.target.value;
//var districtId = $('#input-district').val();
var districtId = $(this).find(':selected').data('id');
var branchId = $('#input-branch').val();
log('input-district: ', e.target.value, districtId, branchId);
if(districtId != '-1'){
$('#input-district').parents('.form-group').removeClass('has-error');
getBranchList(districtId);
$('.btn-phone').hide();
$('.btn-separator').hide();
} else {
getBranchList(districtId);
}
if(districtId != '-1' && branchId != '-1') {
$('.step-1 .btn-next').removeClass('disabled');
} else {
//$('.step-1 .btn-next').removeClass('disabled').addClass('disabled');
// Hide tel number button
$('.btn-phone').hide();
$('.btn-separator').hide();
updateStepsSwiperHeight();
}
});
$('#input-branch').on('change', function(e){
var branchId = e.target.value;
var districtId = $(this).find(':selected').data('id');
var tel = $(this).find(':selected').data('tel');
log('input-branch: ', e.target.value, tel );
if(branchId != '-1'){
$('#input-branch').parents('.form-group').removeClass('has-error');
// Update & Show tel number button
$('.btn-phone').text('致電分行 ' + tel);
if (!isMobile()) {
$('.btn-phone').attr('href','');
} else {
$('.btn-phone').attr('href','tel:'+tel);
}
$('.btn-phone').show();
$('.btn-separator').show();
updateStepsSwiperHeight();
} else {
$('.btn-phone').hide();
$('.btn-separator').hide();
updateStepsSwiperHeight();
}
if(districtId != '-1' && branchId != '-1'){
//getTimeSlots(dateId);
$('.step-1 .btn-next').removeClass('disabled');
}else{
//$('#user-time').html('');
//$('.step-1 .btn-next').removeClass('disabled').addClass('disabled');
}
});
$('.step-1 .btn-next').click(function(evt) {
evt.preventDefault();
log('Click Step-1 next button');
//var districtId = $('#input-district').val();
//var branchId = $('#input-branch').val();
var districtId = $('#input-district').find(':selected').data('id');
var branchId = $('#input-branch').find(':selected').data('id');
if (districtId == '-1') {
$('#input-district').parents('.form-group').addClass('has-error');
$('#input-district').parents('.form-group').find('.help-block').html('請選擇地區');
}
if (branchId == '-1') {
$('#input-branch').parents('.form-group').addClass('has-error');
$('#input-branch').parents('.form-group').find('.help-block').html('請選擇分行');
}
if (!isStepsSwiperActive || districtId == '-1' || branchId == '-1') {
updateStepsSwiperHeight();
return;
} else {
// Tracking
floodlight('1', 'fxfor000');
stepsSwiper.slideNext();
}
});
$('.step-1 .btn-phone').click(function(evt) {
log('Click Step-1 Phone button');
// Tracking
floodlight('1', 'fxfor00');
if (!isMobile()) {
evt.preventDefault();
} else {
}
});
$('.btn-geolocation').click(function(evt) {
evt.preventDefault();
log('Click geolocation button');
getCurrentLocation();
});
$('.btn-branch').click(function(e){
e.preventDefault();
var link = $(this).attr('href');
var target = $(this).data('target');
log('link:', link);
log('data:', target);
var msg = '';
$.ajax({
type: 'GET',
url: link,
cache: false,
success: function(data, status, xhr) {
msg = $(data).find(target).html();
showFancyBox(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
});
// EVENT STEP 2
// ------------------------------------------------------------------
$('.step-2 .btn-next').click(function(evt) {
evt.preventDefault();
var date = $('#input-date').val();
log('Click Step-2 next button', date);
if (date == '') {
log( $('#input-date').parents('.form-group') );
$('#input-date').parents('.form-group').addClass('has-error');
$('#input-date').parents('.form-group').find('.help-block').html('請選擇提取外幣現鈔的日期');
//$('#input-date').parents('.form-group').addClass('has-error');
}
if (!isStepsSwiperActive || date == '') {
updateStepsSwiperHeight();
return;
} else {
// Tracking
floodlight('1', 'fxfor001');
// Generate Ref Number
var rand = Math.random()+"";
var a = rand * 100000000000000000;
var currentDate = new Date();
var refNo = jQuery.datepicker.formatDate('@', currentDate) + '-' + a;
var a = parseInt(rand * 100000);
var currentDate = new Date();
var refNo = parseInt(jQuery.datepicker.formatDate('@', currentDate)) / a;
refNo = parseInt(refNo);
log("currentDate: ", currentDate, jQuery.datepicker.formatDate('yymmdd', currentDate), jQuery.datepicker.formatDate('@', currentDate), refNo);
$('#input-ref-no').attr('value', refNo);
stepsSwiper.slideNext();
}
});
// Calculate the next working day manually
while(startCount <= startDays){
startDate.setDate(startDate.getDate() + 1);
//if(startDate.getDay() != 0 && startDate.getDay() != 6){ // sunday & saturady
if(startDate.getDay() != 0){ // Sunday
//startCount++;
var datestring = jQuery.datepicker.formatDate('yy-mm-dd', startDate);
if (holidays.indexOf(datestring) != -1) { // Public holidays
} else {
startCount++;
}
} else {
}
}
while(endCount <= endDays){
endDate.setDate(endDate.getDate() + 1);
if(endDate.getDay() != 0){ // Sunday
//endCount++;
var datestring = jQuery.datepicker.formatDate('yy-mm-dd', endDate);
//log('datestring:::', datestring, ' -------- ', endDate);
if (holidays.indexOf(datestring) != -1) { // Public holidays
} else {
endCount++;
}
} else {
}
}
log("currentDate: ", currentDate, jQuery.datepicker.formatDate('yymmdd', currentDate), jQuery.datepicker.formatDate('@', currentDate));
log("startDate: ", startDate, jQuery.datepicker.formatDate('yy-mm-dd', startDate) );
log("endDate: ", endDate, jQuery.datepicker.formatDate('yy-mm-dd', endDate));
// Activate Datepicker
$( "#input-date" ).datepicker({
dateFormat: "dd/mm/yy",
minDate: startDate,
//maxDate: "+0M +9D",
maxDate: endDate,
showButtonPanel: true,
closeText: "關閉",
showOtherMonths: true,
selectOtherMonths: true,
monthNames: [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ],
dayNamesMin: [ "日", "一", "二", "三", "四", "五", "六" ],
showMonthAfterYear: true,
yearSuffix: "年",
onSelect: function(selectedDate) {
// custom callback logic here
//alert(selectedDate);
log('Select Date:', selectedDate);
date = selectedDate;
$('.step-2 .btn-next').removeClass('disabled');
$('#input-date').parents('.form-group').removeClass('has-error');
},
beforeShowDay: function(date){
var datestring = jQuery.datepicker.formatDate('yy-mm-dd', date);
var day = date.getDay();
//log('datestring:', datestring, day);
//return [ holidays.indexOf(datestring) == -1 ]
var isSelectable = 1;
if (day == 0) { // Sunday
isSelectable = 0;
} else {
if (holidays.indexOf(datestring) != -1) { // Public holidays
isSelectable = 0;
return [isSelectable, 'ui-datepicker-holiday'];
}
}
return [isSelectable, ''];
},
beforeShow: function(input, inst) {
//log( $('.ui-datepicker-month') );
var tmp = $('#ui-datepicker-div')[0];
log( $('#ui-datepicker-div')[0] );
log( $(tmp).find('.ui-datepicker-title') );
//log( $('#ui-datepicker-div').find('.ui-datepicker-title') );
//log( $('.nav'));
//log(inst);
}
});
$('.input-group-date .input-group-addon').click(function(evt) {
evt.preventDefault();
$( "#input-date" ).datepicker( "show" );
});
// EVENT STEP 3
// ------------------------------------------------------------------
$('.step-3 .btn-next').click(function(evt) {
evt.preventDefault();
// Validate
if (validateForm()) {
log('Form OK');
//var currencyId = $('#input-currency').val().trim();
var amount = $('#input-amount').val().trim();
//var districtId = $('#input-district').val().trim();
//var branchId = $('#input-branch').val().trim();
var date = $('#input-date').val().trim();
var name = $('#input-name').val().trim();
var tel = $('#input-tel').val().trim();
var email = $('#input-email').val().trim();
var captcha = $('#user-captcha').val();
var isexistingcustomer;
if ($("#input-exist-customer-yes").is(":checked")) {
isexistingcustomer = $("#input-exist-customer-yes").val() ;
} else {
isexistingcustomer = $("#input-exist-customer-no").val() ;
}
var refNo = $('#input-ref-no').val().trim();
log($('#input-branch').find(':selected').data('id'));
var branchID = $('#input-branch').find(':selected').data('id').toString().trim();
var branchEmail = $('#input-branch').find(':selected').data('email').trim();
//log( refNo, $('#input-currency').find(':selected').data('name').length );
var currencyName = ($('#input-currency').find(':selected').data('name').length > 0) ? $('#input-currency').find(':selected').data('name').trim() : $('#input-currency').find(':selected').data('name');
var districtName = ($('#input-district').find(':selected').data('name').length > 0) ? $('#input-district').find(':selected').data('name').trim() : $('#input-district').find(':selected').data('name');
var branchName = ($('#input-branch').find(':selected').data('name').length > 0) ? $('#input-branch').find(':selected').data('name').trim() : $('#input-branch').find(':selected').data('name');
var displayAmount = numberToMoneyFormat(parseInt(amount));
$('#user-currency').text(currencyName);
$('#user-amount').text(displayAmount);
$('#user-branch').text(branchName);
$('#user-date').text(date);
$('#user-name').text(name);
$('#user-tel').text(tel);
$('#user-email').text(email);
$('#user-exist-customer').text(isexistingcustomer);
$('#user-branch-id').text(branchID);
$('#user-branch-email').text(branchEmail);
$('#user-ref-no').text(refNo);
// goto confirmation page
if (!isStepsSwiperActive) {
return;
} else {
// Tracking
floodlight('1', 'fxfor002');
stepsSwiper.slideNext();
}
} else {
log('step3 Form NOT OK');
//stepsSwiper.updateContainerSize();
updateStepsSwiperHeight();
return;
}
});
// EVENT CONFIRMATION
// ------------------------------------------------------------------
$('.step-4 .btn-amend').click(function(evt) {
evt.preventDefault();
if (!isStepsSwiperActive) {
return;
} else {
stepsSwiper.slideTo(0);
}
});
$('.step-4 .btn-confirm').click(function(evt) {
evt.preventDefault();
if(isSendingConfirmationForm) return false;
if (!validateCaptcha()) {
log('validate error')
return false;
}
// Validate
if (validateConfirmationForm()) {
isSendingConfirmationForm = true;
// Tracking
floodlight('1', 'fxfor003');
// Send by Ajax
var userCurrency = $('#user-currency').text().trim();
var userAmount = $('#user-amount').text().trim();
userAmount = moneyToNumberFormat(userAmount);
var userBranch = $('#user-branch').text().trim();
var userDate = $('#user-date').text().trim();
var userName = $('#user-name').text().trim()
, userTel = $('#user-tel').text().trim()
, userEmail = $('#user-email').text().trim()
, userExistCustomer = $('#user-exist-customer').text().trim()
, userRefNo = $('#user-ref-no').text().trim();
var userBranchID = $('#user-branch-id').text().trim();
var userBranchEmail = $('#user-branch-email').text().trim();
var userCaptchaText = $('#user-captcha').val();
//alert(userCaptchaText);
// Send
$.ajax({
url: '/campaign_flow/brEmailSend.jsp',
type: 'post',
dataType: 'json',
data: { action: 'order',
lang: 'tc',
usercurrency: userCurrency,
useramount: userAmount,
userbranch : userBranch,
userdate: userDate,
username: userName,
usertel: userTel,
useremail: userEmail,
userexistcustomer: userExistCustomer,
userrefno: userRefNo,
userbranchid: userBranchID,
userbranchemail: userBranchEmail,
usercaptchatext: userCaptchaText
},
success: function(data){
log('order:', data);
isSendingConfirmationForm = false;
// Demo
var msg = " Sent the following data to backend:-\n currency: " + userCurrency + "\n useramount: " + userAmount + "\n userbranch: " + userBranch + "\n userdate: " + userDate + "\n username: " + userName + "\n usertel: " + userTel + "\n useremail: " + userEmail + "\n userExistCustomer" + userExistCustomer + "\n userrefno: " + userRefNo + "\n userbranchid: " + userBranchID + "\n userbranchemail: " + userBranchEmail;
//alert(msg);
// SUCCESS
if(data.result == '0'){
// Clear & reset Form
resetAllForm();
log('Open response section');
$( '.section-steps' ).slideUp( "slow" );
$( '.section-response' ).slideDown( "slow", function() {
$(window).scrollTo( $('.section-response'), 600, {'axis':'y'});
});
} else {
// ERROR
if(data.result == '-1'){
var errMsg = data.message;
$('.response-error-container').html(errMsg).show();
updateStepsSwiperHeight();
}
}
},
error: function() {
log('error order:');
isSendingConfirmationForm = false;
var errMsg = "請稍後再試。";
$('.response-error-container').html(errMsg).show();
updateStepsSwiperHeight();
}
});
} else {
alert('Data Error');
return;
}
});
$('.btn-pre-order-service-tnc').click(function(e){
e.preventDefault();
var link = $(this).attr('href');
var target = $(this).data('target');
log('link:', link);
log('data:', target);
var msg = '';
$.ajax({
type: 'GET',
url: link,
cache: false,
success: function(data, status, xhr) {
msg = $(data).find('#tnc').html();
showFancyBox(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
});
// EVENT SECTION INVESTMENT OFFERS
// ------------------------------------------------------------------
$('.section-investment-offers .btn-more').click(function(e){
e.preventDefault();
var link = $(this).attr('href');
var target = $(this).attr('target');
var type = $(this).data('type');
var cat = $(this).data('cat');
log('link:', link);
log('data:', target);
log('type:', type);
log('cat:', cat);
// Tracking
floodlight(type, cat);
if (target =='_blank') {
window.open(link, '_blank');
}
});
// EVENT FOOTER
// ------------------------------------------------------------------
$('.btn-tnc').click(function(e){
e.preventDefault();
var link = $(this).attr('href');
var target = $(this).data('target');
log('link:', link);
log('data:', target);
var msg = '';
$.ajax({
type: 'GET',
url: link,
cache: false,
success: function(data, status, xhr) {
msg = $(data).find(target).html();
showFancyBox(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
});
// EVENT BRANCH
// ------------------------------------------------------------------
$( document ).on( "click", ".btn-shortcut", function(e) {
e.preventDefault();
var target = $(this).data('target');
if ( $('.page-branch').length > 0) {
$(window).scrollTo( $(target), 600, {'axis':'y'});
} else {
$('.fancybox-inner').scrollTo( $(target), 600, {'axis':'y'});
}
});
$(window).on("throttledresize", function( event ) {
// Your event handler code goes here.
debouncedresize();
});
// Initialize
debouncedresize();
}
function debouncedresize() {
log('debouncedresize');
if (!isStepsSwiperActive && $('.steps-swiper-container').length>0 ) {
isStepsSwiperActive = true;
var grabCursor = true;
if (isIE() && versionIE()<=9) {
grabCursor = false;
if (!debug) {
$('.section-calculation-result').css({'display':'none'});
$('.section-steps').css({'display':'none'});
}
initStepsSwiper();
} else {
initStepsSwiper();
if (!debug) {
$('.section-calculation-result').css({'display':'none'});
$('.section-steps').css({'display':'none'});
}
}
} else {
}
if ($('#media-checking').width() <= 1 ) { // < 768
} else {
//$('.offcanvas-content').offcanvas('hide');
//$('.navmenu').offcanvas('hide');
if ( $('.navmenu-reveal').hasClass('in') ) {
$('.cross button').click();
}
}
}
function getDistrictList() {
log('getDistrictList');
// Send
$.ajax({
type: 'GET',
url: 'json/branch.json',
cache: false,
dataType: 'json',
success: function(data){
log('Success getDistrictList:', data);
},
error: function() {
log('error getDistrictList');
}
});
}
function getAllCurrencyList() {
log('getAllCurrencyList');
var currencyOptionHTML = '';
currencyList = new Array();
$.ajax({
type: 'GET',
url: 'json/currency.json',
cache: false,
dataType: 'json',
success: function(data){
//log('Success getAllCurrencyList:', data);
log('Success getAllCurrencyList:');
if(data.length>0){
currencyOptionHTML += '';
$.each(data, function(k,v){
//log(k, v, v['id'], v['currency'], v.id);
//var tmp = data[k];
currencyOptionHTML += '';
currencyList.push( v );
});
//log('currencyList: ', currencyList);
if (currencyList.length > 0 && branchesList.length >0) {
fadeOutOverlay();
}
} else {
log('No data in json');
currencyOptionHTML += '';
}
$('#input-currency').html(currencyOptionHTML);
},
error: function() {
log('error getAllCurrencyList');
}
});
}
function getAllBranchesList() {
log('getAllBranchesList', districtId);
// Get All Branches - branchesList
branchesList = new Array();
$.ajax({
type: 'GET',
url: 'json/branch.json',
cache: false,
dataType: 'json',
success: function(data){
//log('Success getAllBranchesList:', data);
log('Success getAllBranchesList:');
if(data.length>0){
$.each(data, function(k,v){
//log(k, v);
var tmp = data[k];
var branches = tmp['branches'];
var districtId = tmp['id'];
$.each(branches, function(tk,tv){
//log(tv.id, tv.branch, tv.tel, tv.location, tv.location.latitude, tv.location.longitude, districtId);
var branch = [tv.id, tv.branch, tv.location.latitude, tv.location.longitude, districtId, tv.email];
branchesList.push( branch );
});
});
//log('branchesList: ', branchesList);
if (currencyList.length > 0 && branchesList.length >0) {
fadeOutOverlay();
}
} else {
}
},
error: function() {
log('error getAllBranchesList');
}
});
}
function getBranchList(districtId, callback) {
log('getBranchList', districtId);
var branchOptionHTML = '';
if (districtId != '-1') {
// Send
$.ajax({
type: 'GET',
url: 'json/branch.json',
cache: false,
dataType: 'json',
success: function(data){
//log('Success getBranchList:', data);
log('Success getBranchList:');
var index = districtId - 1;
var data = data[index];
var branches = data['branches'];
if(branches.length>0){
branchOptionHTML += '';
$.each(branches, function(k,v){
//log(v.id, v.branch, v.tel);
branchOptionHTML += '';
});
}else {
branchOptionHTML += '';
}
$('#input-branch').html(branchOptionHTML);
// Make sure the callback is a function
if (typeof callback === "function") {
// Call it, since we have confirmed it is callable
callback();
}
},
error: function() {
log('error getBranchList');
}
});
} else {
branchOptionHTML += '';
$('#input-branch').html(branchOptionHTML);
}
}
function initStepsSwiper() {
stepsSwiper = new Swiper('.steps-swiper-container', {
direction: 'horizontal',
pagination: '.steps-swiper-pagination',
paginationClickable: true,
nextButton: '.steps-swiper-button-next',
prevButton: '.steps-swiper-button-prev'
, slideClass: 'step'
, loop: false
, simulateTouch: false
, autoHeight: true
//, slidesPerView: 4
//, slidesPerGroup: 4
//, loop: true
//, spaceBetween: 60
,onSlideChangeStart: function(swiper) {
log('Slide change START', swiper.activeIndex);
var activeIndex = swiper.activeIndex;
$('.bs-wizard-step').removeClass('active');
$('.bs-wizard-step').eq(activeIndex).addClass('active');
}
, onSlideChangeEnd: function(swiper) {
console.log('Slide change END', swiper.activeIndex);
}
});
}
function updateStepsSwiperHeight() {
if (!isStepsSwiperActive) {
return;
} else {
//stepsSwiper.slideNext();
//log( $('.swiper-slide-active') );
//log( $('.swiper-slide-active').height(), $('.swiper-slide-active').outerHeight() );
var activeSlideHeight = $('.swiper-slide-active').outerHeight();
$('.steps-swiper-wrapper').height(activeSlideHeight);
}
}
function validateCaptcha() {
// validate Captcha
var captcha = $('#user-captcha').val();
var error = false;
if (captcha.length<1) {
error = true;
$('#user-captcha').parents('.form-group').addClass('has-error');
$('#user-captcha').parents('.form-group').find('.help-block').html('請輸入驗證碼。');
updateStepsSwiperHeight();
} else {
$('#user-captcha').parents('.form-group').removeClass('has-error');
updateStepsSwiperHeight();
}
return !error;
}
function getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(userPosition, showError);
} else {
log("Geolocation is not supported by this browser.");
$('.geolocation-msg').addClass('has-error');
}
}
function userPosition(position) {
log("userPosition - Latitude: " + position.coords.latitude + " Longitude: " + position.coords.longitude);
findnearestbranch(position.coords.latitude, position.coords.longitude);
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
alert("如要尋找最近的分行,請開啟閣下裝置的定位服務。");
break;
case error.POSITION_UNAVAILABLE:
alert("不能提供地理定位。");
break;
case error.TIMEOUT:
alert("獲取地理定位超時。");
break;
case error.UNKNOWN_ERROR:
//alert("An unknown error occurred.");
alert('Error');
break;
}
$('.geolocation-msg').addClass('has-error');
}
function findnearestbranch(latitude, longitude) {
var mindif = 99999;
var closest;
for (index = 0; index < branchesList.length; ++index) {
var dif = PythagorasEquirectangular(latitude, longitude, branchesList[index][2], branchesList[index][3]);
if (dif < mindif) {
closest = index;
mindif = dif;
}
}
log('The nearest Branch:', branchesList[closest]);
// Update DropDown
var districtId = branchesList[closest][4];
var branchId = branchesList[closest][0];
log('districtId:', districtId, ' branchId:', branchId)
updateDistrictBranchDropDown(districtId, branchId);
}
// Convert Degress to Radians
function Deg2Rad(deg) {
return deg * Math.PI/180;
}
function PythagorasEquirectangular(lat1, lon1, lat2, lon2) {
lat1 = Deg2Rad(lat1);
lat2 = Deg2Rad(lat2);
lon1 = Deg2Rad(lon1);
lon2 = Deg2Rad(lon2);
var R = 6371; // km
var x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
var y = (lat2 - lat1);
var d = Math.sqrt(x * x + y * y) * R;
return d;
}
function updateDistrictBranchDropDown(districtId, branchId) {
//$('#input-district option[value=' + districtId + ']').prop('selected',true);
$('#input-district').parents('.form-group').removeClass('has-error');
$('#input-branch').parents('.form-group').removeClass('has-error');
log('updateDistrictBranchDropDown', districtId);
$('#input-district option[data-id=' + districtId + ']').prop('selected',true);
getBranchList(districtId, function() {
selectBranchDropDown(branchId);
});
}
function selectBranchDropDown(branchId) {
log('selectBranchDropDown', branchId);
//$('#input-branch option[value=' + branchId + ']').prop('selected',true);
$('#input-branch option[data-id=' + branchId + ']').prop('selected',true);
$('#input-branch').parents('.form-group').removeClass('has-error');
var tel = $('#input-branch').find(':selected').data('tel');
// Update & Show tel number button
$('.btn-phone').text('致電分行 ' + tel);
if (!isMobile()) {
$('.btn-phone').attr('href','');
} else {
$('.btn-phone').attr('href','tel:'+tel);
}
$('.btn-phone').show();
$('.btn-separator').show();
updateStepsSwiperHeight();
}
function resetAllForm() {
if (!isMobile()) {
$('.btn-phone').text('Talk to us');
$('.btn-phone').attr('href','');
}
$('.btn-phone').hide();
$('.btn-separator').hide();
$('#input-currency').val(-1).change();
$('#input-amount').val('');
$('#input-district').val(-1).change();
$('#input-branch').val(-1).change();
$('#input-date').val('');
$('#input-name').val('');
$('#input-tel').val('');
$('#input-email').val('');
$('#input-acceptance-tnc').attr('checked', false);
$('#input-exist-customer-yes').prop('checked', false);
$('#input-exist-customer-no').prop('checked', false);
$('#input-ref-no').val('');
$('#user-currency').text('');
$('#user-amount').text('');
$('#user-branch').text('');
$('#user-date').text('');
$('#user-name').text('');
$('#user-tel').text('');
$('#user-email').text('');
$('#user-branch-id').text('');
$('#user-branch-email').text('');
$('#user-exist-customer').text('');
$('#user-ref-no').text('');
$('#user-captcha').val('');
$('.response-error-container').html('');
$('.response-error-container').hide();
}
// FORM - STEP 3
function validateForm() {
var error = false;
var name = $('#input-name').val().trim()
, tel = $('#input-tel').val().trim()
, email = $('#input-email').val().trim();
var tc = $('#input-acceptance-tnc').is(':checked');
var isexistingcustomer;
//var existmember = $("#input-exist-customer-yes").is(":checked");
//log('existmember:', existmember);
log('name.length:', name.length);
if (name.length<1) {
error = true;
$('#input-name').parents('.form-group').addClass('has-error');
$('#input-name').parents('.form-group').find('.help-block').html('請輸入你的名稱');
} else if (name.length > 40) {
error = true;
$('#input-name').parents('.form-group').addClass('has-error');
$('#input-name').parents('.form-group').find('.help-block').html('請輸入有效的名稱');
} else {
if (!validateName(name)) {
error = true;
log('cannot validateName');
$('#input-name').parents('.form-group').addClass('has-error');
$('#input-name').parents('.form-group').find('.help-block').html('只可輸入中文或英文字');
} else {
$('#input-name').parents('.form-group').removeClass('has-error');
}
}
if(tel.length<1){
error = true;
$('#input-tel').parents('.form-group').addClass('has-error');
$('#input-tel').parents('.form-group').find('.help-block').html('請輸入你的聯絡電話號碼');
} else {
if (!isNumber(tel) || tel.length!=8) {
error = true;
$('#input-tel').parents('.form-group').addClass('has-error');
if (!isNumber(tel)) {
$('#input-tel').parents('.form-group').find('.help-block').html('只可輸入數字');
} else {
$('#input-tel').parents('.form-group').find('.help-block').html('請輸入有效的聯絡電話號碼');
}
} else {
$('#input-tel').parents('.form-group').removeClass('has-error');
}
}
if(email.length<1){
error = true;
$('#input-email').parents('.form-group').find('.help-block').html('請輸入你的電郵地址');
$('#input-email').parents('.form-group').addClass('has-error');
} else {
if(!validateEmail(email)){
error = true;
$('#input-email').parents('.form-group').find('.help-block').html('請輸入有效的電郵地址');
$('#input-email').parents('.form-group').addClass('has-error');
} else {
$('#input-email').parents('.form-group').removeClass('has-error');
}
}
if (!$("input[name='input-exist-customer']:checked").val()) {
error = true;
$('#input-exist-customer-yes').parents('.form-group').addClass('has-error');
$('#input-exist-customer-yes').parents('.form-group').find('.help-block').html('請選擇你是否本行現有客戶');
//alert('Nothing is checked!');
//return false;
}
else {
//alert('One of the radio buttons is checked!');
$('#input-exist-customer-yes').parents('.form-group').removeClass('has-error');
if ($("#input-exist-customer-yes").is(":checked")) {
//log('isexistingcustomer', $("#input-exist-customer-yes").val() );
isexistingcustomer = $("#input-exist-customer-yes").val() ;
} else {
//log('isexistingcustomer', $("#input-exist-customer-no").val() );
isexistingcustomer = $("#input-exist-customer-no").val() ;
}
}
if (!tc) {
error = true;
$('#input-acceptance-tnc').parents('.form-group').addClass('has-error');
$('#input-acceptance-tnc').parents('.form-group').find('.help-block').html('在遞交你的指示前,請確認已閱讀並接受有關的條款及細則');
} else {
$('#input-acceptance-tnc').parents('.form-group').removeClass('has-error');
}
return !error;
}
function validateConfirmationForm() {
var error = false;
var userCurrency = $('#user-currency').text().trim();
var userAmount = $('#user-amount').text().trim();
//var userDistrict = $('#user-district').val().trim();
var userBranch = $('#user-branch').text().trim();
var userDate = $('#user-date').text().trim();
var userName = $('#user-name').text().trim()
, userTel = $('#user-tel').text().trim()
, userEmail = $('#user-email').text().trim();
var userCaptcha = $('#user-captcha').val();
if (userCurrency=='-1') {
error = true;
log('userCurrency Error');
}
if (userAmount == '') {
error = true;
log('userAmount Error', userAmount);
}
if (userBranch == '-1') {
error = true;
log('userBranch Error', userBranch);
}
if (userName == '') {
error = true;
log('userName Error', userName);
}
if (userName.length<1) {
error = true;
log('userName Error', userName);
} else {
}
if(userTel.length<1){
error = true;
log('userTel Error', userTel);
} else {
if (!isNumber(userTel) || userTel.length!=8) {
error = true;
} else {
}
}
if(userEmail.length<1){
error = true;
log('userEmail Error', userEmail);
} else {
if(!validateEmail(userEmail)){
error = true;
} else {
}
}
if (userCaptcha.length<1) {
error = true;
log('userCaptcha Error', userCaptcha);
} else {
}
return !error;
}
function numberToMoneyFormat(num) {
var tmp = num.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return tmp;
}
function moneyToNumberFormat(amount) {
var number = Number(amount.replace(/[^0-9\.]+/g,""));
return number;
}
// VALIDATION
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
// VALIDATION
/*
function isInteger(n) {
return Number.isInteger(n);
}
*/
function isInteger(num) {
return (num ^ 0) === num;
}
// VALIDATION
function validateName(name) {
//var re = /^[A-Za-z\s]+$/; // space & eng
//var re = /^[-'a-z\u4e00-\u9eff]{1,20}$/i;
//var re = /^[\u3300-\u9fff\uf900-\ufaff]{2,}$/;
var re = /^[A-Za-z\u2E80-\u2FD5\u3400-\u4DBF\u4E00-\u9FCC\s]+$/; // space & eng & chinese
return re.test(name);
}
// VALIDATION
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
// FANCYBOX
// Show Terms and Conditions
function showFancyBox(content) {
if (typeof content == "undefined") {
content = $('#tnc').html();
}
//log('content:', content);
var maxHeight = 9999;
maxHeight = 600;
var minHeight = 60;
var maxWidth = 810 - 40;
var minWidth = maxWidth - 15;
var autoCenter = false;
var scrolling = 'no';
var autoSize = false;
var width = 'auto';
var height = 'auto';
var locked = false;
var margin = 20;
if ((window.parent != window) && FB && FB.Canvas) {
locked = false;
}
log('Window Width:', $(window).width());
/*
if ($(window).width()< 810){
maxHeight = $(window).height() - 40 ;
autoCenter = true;
scrolling = 'auto';
autoSize = false;
width = '100%';
minWidth = 260;
locked = true;
margin = 20;
log('Width smaller 810');
}
*/
maxHeight = $(window).height() - 40 ;
autoCenter = true;
scrolling = 'auto';
autoSize = false;
width = '100%';
minWidth = 260;
locked = true;
margin = 20;
if (isAndroid()) {
autoCenter = false;
}
log(width, autoSize);
$.fancybox({
width: width,
height: height,
autoSize: autoSize,
maxWidth: maxWidth,
maxHeight: maxHeight,
minWidth: minWidth,
minHeight: minHeight,
content : content,
//padding: 0,
padding: 10,
margin: margin,
openEffect : 'fade',
closeEffect : 'fade',
wrapCSS : 'fancy-popup-skin',
helpers : {
overlay : {
locked : locked // try changing to true and scrolling around the page
}
}
});
}
// SWITCH LANGUAGE
function switchLang(from,to) {
var currentStr = window.location.href;
currentStr = currentStr.replace('/' + from + '/', '/' + to + '/');
window.location.href = currentStr;
}
// GOOGLE ANALYTICS FUNCTION
function gaEventTracking(category, action, label, value) {
log('gaEventTracking::: ', category, action, label, value);
if (!category || !action) {
return;
} else {
if (value=='') {
ga('send', 'event', category, action, label);
} else {
ga('send', 'event', category, action, label, value);
}
}
}
function gaPageTracking(page, title) {
log('gaPageTracking: ', page, title);
if (!page || !title) {
return;
} else {
ga('send', 'pageview', {
'page': page,
'title': title
});
}
}
function gaSettingParam(page, title) {
log('gaSettingParam: ', page, title);
if (!page || !title) {
return;
} else {
ga('set', {
'page': page,
'title': title
});
}
}
function trackOutboundLink(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function() {
document.location = url;
}
});
}