$(function() {
	$("#intermediary_flg:checkbox").click(function() {
		toggleIntermediaries();
	});

	$('.btnNext').click(function() {

		if($('#withdraw_type').val() == '1') {
			$('#type').val('card_input');
		} else {
			$('#type').val('input');
		}

        $('#moneyoutSolution').val('International');

		submitForm();
	});

    $('.flat3_btnNext').click(function() {

		if($('#withdraw_flat3_type').val() == '1') {
			$('#type').val('card_input');
		} else {
			$('#type').val('input');
		}

        $('#moneyoutSolution').val('Flat3');

		submitForm();
	});

    $('.local_btnNext').click(function() {
        if ($('#withdraw_local_type').val() == '1') {
            $('#type').val('card_input');
        } else {
            $('#type').val('local_input');
        }

        $('#moneyoutSolution').val('SDPay');

        submitForm();
    });

	$('.h2p_btnNext').click(function() {
		if ($('#withdraw_h2p_type').val() == '1') {
			$('#type').val('card_input');
		} else {
			$('#type').val('withdraw_h2p_input');
		}

		$('#moneyoutSolution').val('H2P');

		submitForm();
	});

	$('#btnH2PConfirm').click(function() {
		$('#type').val('withdraw_h2p_confirm');
		submitForm();
	});

	$('#btnH2PBack').click(function() {
		$('#type').val('withdraw_h2p_back');
		submitForm();
	});

	$('#btnConfirm').click(function() {
		$('#type').val('confirm');
		submitForm();
	});
    $('#btnFlat3Confirm').click(function() {
		$('#type').val('flat3_confirm');
		submitForm();
	});
    $('#localBankConfirm').click(function() {
        $('#type').val('localBankConfirm');
        submitForm();
    });
	$('#btnBackInput').click(function() {
		$('#type').val('input');
		submitForm();
	});

	$('#btn2faSubmit').click(function() {
        if($('#terms').is(':visible')){
            if($('#terms').prop('checked') == true){
    		    $("#btn2faSubmit").attr("disabled", "disabled");
            }
        } else{
            $("#btn2faSubmit").attr("disabled", "disabled");
        }
	});

	$('#btnBack').click(function() {
		$('#type').val('back');
		submitForm();
	});

	$('#btnFlat3Back').click(function() {
		$('#type').val('flat3_back');
		submitForm();
	});

        $('#local_btnBack').click(function() {
            $('#type').val('local_back');
            submitForm();
        });
	$('#btnComplete').click(function() {
		$('#type').val('complete');
		submitForm();
	});
    $('#local_btnComplete').click(function() {
        $('#type').val('local_complete');
        submitForm();
    });
	$('#btnCardInput').click(function() {
		$('#type').val('card_input');
		submitForm();
	});

	$('#btnCardConfirm').click(function() {
		$('#type').val('card_confirm');
		submitForm();
	});

	$('#btnCardComplete').click(function() {
		$('#type').val('card_complete');
		submitForm();
	});

	$('#receipt_bank_country').change(function() {
		toggleRceiptBranch();
	});

	$('#withdraw_history').change(function() {
		dispHistory();
	});

	$('#withdraw_history_h2p').change(function() {
		dispH2PHistory();
	});

    $('#withdraw_history_local').change(function() {
        dispLocalHistory();
    });
	toggleIntermediaries();
	toggleRceiptBranch();

    $('#terms').click(function(){
        if($('#terms').prop('checked') != true){
            $('#terms').css('outline','2px solid #c00');
            $('#termsError').show();
        } else{
            $('#terms').css('outline','none');
            $('#termsError').hide();
        }
    });

});


/**
*  2FA 二次认证code
*/
function getbtnComplete(){
	$('#type').val('complete');
	submitForm();
}
function getbtnFlat3Complete(){
	$('#type').val('flat3_complete');
	submitForm();
}

function localbtnComplete(){
	$('#type').val('local_complete');
    submitForm();
}

function getbtnH2PComplete(){
	$('#type').val('withdraw_h2p_complete');
	submitForm();
}
/**
 * 中継銀行の表示の切り替え
 */
function toggleIntermediaries() {
	if($('#intermediary_flg:checked').val()) {
		$('#intermediaries').show();
	} else {
		$('#intermediaries').hide();
	}
}

/**
 * 支店名の表示の切り替え
 */
function toggleRceiptBranch() {
	if($('#receipt_bank_country').val() == 'JP') {
		$('#receiptBranchCode').show();
		$('#receiptBranch').show();
	} else {
		$('#receiptBranchCode').hide();
		$('#receiptBranch').hide();
	}
}

/**
 * 送金履歴の表示
 */
function dispHistory() {

	// ポストアクション
	postAction('../api/WithdrawHistory', {'w_id':$('#withdraw_history').val()})
	.done(function(data) {

		console.log(data);

		$('#account_name').val(data.account_name);
		$('#receipt_country').val(data.receipt_country);
		$('#receipt_address_1').val(data.receipt_address_1);
		$('#receipt_address_2').val(data.receipt_address_2);
		$('#tel').val(data.tel);
		$('#receipt_message').val(data.receipt_message);
		$('#receipt_bank_name').val(data.receipt_bank_name);
		$('#receipt_branch_name').val(data.receipt_branch_name);
		$('#receipt_bank_swift').val(data.receipt_bank_swift);
		$('#receipt_bank_country').val(data.receipt_bank_country);
		$('#receipt_bank_address_1').val(data.receipt_bank_address_1);
		$('#account_number').val(data.account_number);

		// 中継銀行
		if(data.intermediary_flg == '1') {
			$('#intermediaries').show();
			$('#intermediary_flg').prop('checked',true);
		} else {
			$('#intermediaries').hide();
			$('#intermediary_flg').prop('checked',false);
		}

		$('#intermediary_bank_name').val(data.intermediary_bank_name);
		$('#intermediary_bank_swift').val(data.intermediary_bank_swift);
		$('#intermediary_bank_country').val(data.intermediary_bank_country);
		$('#intermediary_bank_address_1').val(data.intermediary_bank_address_1);
		$('#intermediary_bank_message').val(data.intermediary_bank_message);
    }).fail(function(data) {
        console.log(data);
    });
}

function dispH2PHistory() {

	// ポストアクション
	postAction('../api/WithdrawHistory', {'w_id':$('#withdraw_history_h2p').val()})
	.done(function(data) {

		console.log(data);

		$('#account_name').val(data.account_name);
		$('#receipt_country').val(data.receipt_country);
		$('#receipt_address_1').val(data.receipt_address_1);
		$('#receipt_address_2').val(data.receipt_address_2);
		$('#tel').val(data.tel);
		$('#receipt_message').val(data.receipt_message);
		$('#receipt_bank_name').val(data.receipt_bank_name);
		$('#receipt_branch_name').val(data.receipt_branch_name);
		$('#receipt_bank_swift').val(data.receipt_bank_swift);
		$('#receipt_bank_address_1').val(data.receipt_bank_address_1);
		$('#account_number').val(data.account_number);

		// 中継銀行
		if(data.intermediary_flg == '1') {
			$('#intermediaries').show();
			$('#intermediary_flg').prop('checked',true);
		} else {
			$('#intermediaries').hide();
			$('#intermediary_flg').prop('checked',false);
		}

		$('#intermediary_bank_name').val(data.intermediary_bank_name);
		$('#intermediary_bank_swift').val(data.intermediary_bank_swift);
		$('#intermediary_bank_country').val(data.intermediary_bank_country);
		$('#intermediary_bank_address_1').val(data.intermediary_bank_address_1);
		$('#intermediary_bank_message').val(data.intermediary_bank_message);
    }).fail(function(data) {
        console.log(data);
    });
}
/**
 * 送金履歴の表示
 */
function dispLocalHistory() {
    // ポストアクション
    postAction('../api/WithdrawHistory', {
        'w_id': $('#withdraw_history_local').val()
    }).done(function(data) {
        console.log(data);
        $('#account_name').val(data.account_name);
        $('#receipt_country').val(data.receipt_country);
        $('#receipt_address_1').val(data.receipt_address_1);
        $('#receipt_address_2').val(data.receipt_address_2);
        $('#tel').val(data.tel);
        // $('#receipt_message').val(data.receipt_message);
        // $('#receipt_bank_name').val(data.receipt_bank_name);
        $('#receipt_branch_code').val(data.receipt_branch_code);
        $('#receipt_branch_name').val(data.receipt_branch_name);
        $('#receipt_bank_swift').val(data.receipt_bank_swift);
        $('#receipt_bank_country').val(data.receipt_bank_country);
        $('#receipt_bank_address_1').val(data.receipt_bank_address_1);
        $('#account_number').val(data.account_number);
        // 中継銀行
        if (data.intermediary_flg == '1') {
            $('#intermediaries').show();
            $('#intermediary_flg').prop('checked', true);
        } else {
            $('#intermediaries').hide();
            $('#intermediary_flg').prop('checked', false);
        }
        $('#intermediary_bank_name').val(data.intermediary_bank_name);
        $('#intermediary_bank_swift').val(data.intermediary_bank_swift);
        $('#intermediary_bank_country').val(data.intermediary_bank_country);
        $('#intermediary_bank_address_1').val(data.intermediary_bank_address_1);
        $('#intermediary_bank_message').val(data.intermediary_bank_message);
    }).fail(function(data) {
		console.log(data);
	});
}

function getExchangeMoney() {
    var params = {
        'from': 'CNY',
        'to': $("input[name='from_currency']:checked").val(),
        'amount': $('#amount').val()
    };
    postAction('../api/Exchange.php', params).done(function(data) {
        var num = data.publish_amount.toString();
        if (num != 0 && $("input[name='from_currency']:checked").val()) {
            $('#amount_bank_status').text($("input[name='from_currency']:checked").val() + " " + num);
            $('#amount_bank_status').show();
        }
    })
}

function getLBTCAreaData(areaData) {
	return areaData;
}

function loadLBTCProvinceData() {
	$.ajax({
		url: "../logic/withdraw/sdAreaList.txt",
		success: function(data) {
			var provinceData = null;
			var provinceOptions = '<option disabled value="Select" selected>Select Bank</option>';
			var cityData = '{';

			provinceData = JSON.parse(data);

			if(provinceData.province.length > 0) {
				for(i in provinceData.province) {
					provinceOptions += '<option value="'+provinceData.province[i].code+'">'+provinceData.province[i].name+'</option>'
					cityData += provinceData.province[i].code+':'+JSON.stringify(provinceData.province[i].city);
				}

				cityData += '}';
				$('#province').html(provinceOptions);
				getLBTCAreaData(cityData);
			}
		}
	});
}

$(function() {
	var lookup = [];
	//$.ajaxSetup({async: false});
	$.ajax({
	    type: "GET",
	    url: "../logic/withdraw/flat3BankList.txt",                 // or path to file
	    success: function(content) {
	        // parse the content (content is the file content)
			content = content.trim();
			var lines = content.split('\n');
			var splitlines = [];

				for ( var i = 0 ; i < lines.length ; i++ ) {

				    // take index1, index2, value and store them in a 2d array (parse lines[i])
					 splitlines [i] = lines[i].split(':');
				}
				for ( var i = 0 ; i < splitlines.length ; i++ ) {
						lookup [splitlines[i][0]] = splitlines[i][1].split(',');


				}
	    },
	    error: function() {
	        console.log('error');
	    }
	});
	var lookupBranchCode = [];


	$.ajax({
	    type: "GET",
	    url: "../logic/withdraw/flat3BranchCode.txt",                 // or path to file
	    success: function(content) {
	        // parse the content (content is the file content)
			content = content.trim();
			var lines = content.split('\n');
			var splitlines = [];

				for ( var i = 0 ; i < lines.length ; i++ ) {

					 splitlines [i] = lines[i].split(':');
				}
				for ( var i = 0 ; i < splitlines.length ; i++ ) {
						lookupBranchCode[splitlines[i][0]]=splitlines[i][1];
				}
	    },
	    error: function() {
	        console.log('error');
	    }
	});

	var h2pbank = [];
	$.ajax({
	    type: "GET",
	    url: "../logic/withdraw/H2PBankList.txt",                 // or path to file
	    success: function(content) {
	        // parse the content (content is the file content)
			content = content.trim();
			var lines = content.split('\n');
			var splitlines = [];

				for ( var i = 0 ; i < lines.length ; i++ ) {

				    // take index1, index2, value and store them in a 2d array (parse lines[i])
					 splitlines [i] = lines[i].split(':');
				}
				for ( var i = 0 ; i < splitlines.length ; i++ ) {
						h2pbank [splitlines[i][0]] = splitlines[i][1].split(',');


				}
	    },
	    error: function() {
	        console.log('error');
	    }
	});

	//$.ajaxSetup({async: true});

	if($('#btnFlat3Confirm').length){
		$('#receipt_bank_name').change(function() {
			var mybankCode = $('#receipt_bank_name option:selected').attr('code');
			if(mybankCode != 'others'){
				$('#receipt_bank_code').val(mybankCode);
				$('#receipt_bank_code').attr('value',mybankCode);
				$('#receipt_bank_code').attr('readonly',true);
				$('#receipt_branch_code').attr('readonly',true);
				$(this).parents('.checkselected').find($('.other_bank_container')).hide();
				$('.receiptBranchName').find('.other_bank_container').hide();
				$('#receipt_branch_name').show();
				$('#receipt_branch_name').empty();
				if($('#lang').attr('value')== 'en'){
					$('#receipt_branch_name').append("<option code='' value='' readonly disabled selected> Select Branch </option>");
				}else{
					$('#receipt_branch_name').append("<option code='' value='' readonly disabled selected> 支店を選択してください。 </option>");
				}


				if(mybankCode in lookup){
							for(var j in lookup[mybankCode]){
								if(lookup[mybankCode].hasOwnProperty(j)){
									 var branchCodeIndex = mybankCode+lookup[mybankCode][j];

									if(lookupBranchCode.hasOwnProperty(branchCodeIndex)){
										$('#receipt_branch_name').append("<option code='" + lookupBranchCode[branchCodeIndex] + "' value='"+ lookup[mybankCode][j] +"'>" + lookup[mybankCode][j] + "</option>");
									}

								}
							}
				}

			}else{
				$('#receipt_bank_code').val('');
				$('#receipt_branch_code').val('');
				$('#receipt_bank_code').attr('value','');
				$('#receipt_bank_code').attr('readonly',false);
				$('#receipt_branch_code').attr('readonly',false);
				$(this).parents('.checkselected').find($('.other_bank_container')).show();
				$('.receiptBranchName').find('.other_bank_container').show();
				$('#receipt_branch_name').append("<option code='others' value='others' selected></option>");
				$('#receipt_branch_name').hide();
			}

		});

		if($("#receipt_bank_name").val()){
			setTimeout(function(){
				$("#receipt_bank_name").change()
			}, 800)
		}

		$('#receipt_branch_name').change(function() {
			var mybranchCode = $('#receipt_branch_name option:selected').attr('code');
			if(mybranchCode != 'others'){
				$('#receipt_branch_code').val(mybranchCode);
				$('#receipt_branch_code').attr('value',mybranchCode);
				$('#receipt_branch_code').attr('readonly',true);
			}else{
				$('#receipt_branch_code').attr('readonly',false);
			}
		});

		$('#receipt_bank_name option').each(function() {
			if($(this).is(':selected')){
				var mybankCode = $('#receipt_bank_name option:selected').attr('code');
				if(mybankCode != 'others'){
					$('#receipt_bank_code').val(mybankCode);
					$('#receipt_bank_code').attr('value',mybankCode);
					$('#receipt_bank_code').attr('readonly',true);
					$(this).parents('.checkselected').find($('.other_bank_container')).hide();
					$('.receiptBranchName').find('.other_bank_container').hide();
					$('#receipt_branch_name').show();
					$('#receipt_branch_name').empty();
					if($('#lang').attr('value')== 'en'){
						$('#receipt_branch_name').append("<option code='' value='' readonly> Select Branch </option>");
					}else{
						$('#receipt_branch_name').append("<option code='' value='' readonly> 支店を選択してください。 </option>");
					}
					var branchName = $('#other_receipt_branch_name').attr('value');

					if(mybankCode in lookup){
								for(var j in lookup[mybankCode]){
									if(lookup[mybankCode].hasOwnProperty(j)){
										 var branchCodeIndex = mybankCode+lookup[mybankCode][j];

										if(lookupBranchCode.hasOwnProperty(branchCodeIndex)){
											if(lookup[mybankCode][j] == branchName){
												var selected = 'selected';
												var mybranchCode = lookupBranchCode[branchCodeIndex];
												if(mybranchCode != 'others'){
													$('#receipt_branch_code').val(mybranchCode);
													$('#receipt_branch_code').attr('value',mybranchCode);
													$('#receipt_branch_code').attr('readonly',true);
												}else{
													$('#receipt_branch_code').attr('readonly',false);
												}
											}else{
												selected = '';
											}
											$('#receipt_branch_name').append("<option code='" + lookupBranchCode[branchCodeIndex] + "' value='"+ lookup[mybankCode][j] +"'"+ selected +">" + lookup[mybankCode][j] + "</option>");
										}

									}
								}
					}

				}else{
					$('#receipt_bank_code').attr('readonly',false);
					$('#receipt_branch_code').attr('readonly',false);
					$(this).parents('.checkselected').find($('.other_bank_container')).show();
					$('.receiptBranchName').find('.other_bank_container').show();
					$('#receipt_branch_name').hide();
				}
			}
		});
	}

	if($('#btnH2PConfirm').length){

		$('#currency').change(function() {
			$('#receipt_bank_name').empty();
			$('#receipt_bank_name').append("<option disabled value='' selected>Select Bank</option>");
			var country = $('#currency option:selected').attr('country');
			var maxlength = "";

			if(country != ''){
				$('#receipt_bank_country').val(country);
				$('#receipt_bank_country').attr('value',country);
				if(country in h2pbank){
							for(var j in h2pbank[country]){
								if(h2pbank[country].hasOwnProperty(j)){
									 var bankNameIndex = country;

									if(h2pbank.hasOwnProperty(bankNameIndex)){
										var str = h2pbank[country][j].split('.');
										$('#receipt_bank_name').append("<option value='"+ str[1] +"'>" + str[0] + "</option>");
										//$('#receipt_bank_code').val(str[1]);
									}

								}
							}
				}
				var mybankCode = $('#receipt_bank_name option:selected').attr('value');
				if(mybankCode != 'others'){
					$('#receipt_bank_code').val(mybankCode);
				}

				if(country == 'Indonesia'){
					maxlength = 9;
				}else if(country == 'Malaysia'){
					maxlength = 5;
				}else if(country == 'Thailand'){
					maxlength = 6;
				}else if(country == 'Vietnam'){
					maxlength = 9;
				}
			}
			$('#currency option[value="select"]').removeAttr("selected");
			$('#amount').val('');
			$('#amount').attr("maxlength",maxlength);
		});

		$('#receipt_bank_name').change(function() {
			var mybankCode = $('#receipt_bank_name option:selected').attr('value');
			if(mybankCode != 'others'){
				$('#receipt_bank_code').val(mybankCode);
			}
		});
	}

	//check if the solution is SD
	if($('#localBankConfirm').length){
		//load and get province data

		$.ajax({
			url: "../logic/withdraw/sdAreaList.txt",
			success: function(data) {
				var provinceData = null;
				// var provinceOptions = '<option disabled value="" selected>Select Province</option>';
				var cityJSON = '{';

				provinceData = JSON.parse(data);

				if(provinceData.province.length > 0) {
					for(i in provinceData.province) {
						cityJSON += '"'+provinceData.province[i].code+'":'+JSON.stringify(provinceData.province[i].city);
						if(i < (provinceData.province.length - 1)) {
							//add comma after each data
							cityJSON += ',';
						}
					}

					cityJSON += '}';

					$('#province').change(function() {
						var cityOptions = '';
						var cityData = JSON.parse(cityJSON);
						var selectedVal = $('#province option:selected').val();
						selectedVal = selectedVal.split(',');
						selectedVal = selectedVal[0];
						for(i in cityData[selectedVal]) {
							cityOptions += '<option value="'+cityData[selectedVal][i].code+','+cityData[selectedVal][i].name+'">'+cityData[selectedVal][i].name+'</option>';
						}

						$('#selectCityLabel').after(cityOptions);
					});
				}
			}
		});
	}

});
