closeElementOnMouseUp(".user-info-balance");
closeSelectDivOnMouseUp();
newPoolCategory();
//reelKingdomBaruTag();
//pragmaticOneTag();
jiliHotTag();
ptgHotTag();
afbHotTag();
//removeFooterLogo();
//copyInfiniLogo();
clearTempData();
getListProvider();

function jiliHotTag() {
	$(document).ready(function() {
		let dataMobile = $("body").data("mobile");
		let parentEl = $('li[class="slot"]').find('li[class="game sub jli"] > .icon-menu-wrapper');
		let tag = $('<img src="https://cdn.robotaset.com/assets/images/provider/jli-top-tag.gif" class="lobby-icon game-front-tag">');
		if( dataMobile ) {
			parentEl = $('.provider-item-list.slot').find('.jli');
		}
		parentEl.prepend(tag);
	});
}
function ptgHotTag() {
	$(document).ready(function() {
		let dataMobile = $("body").data("mobile");
		let parentEl = $('li[class="slot"]').find('li[class="game sub ptg"] > .icon-menu-wrapper');
		let tag = $('<img src="https://cdn.robotaset.com/assets/images/provider/hot-tag.gif" class="lobby-icon game-front-tag">');
		let label = $('<span class="label-new label-new-top-right blink">Baru</span>');
		if( dataMobile ) {
			parentEl = $('.provider-item-list.slot').find('.ptg');
			label = $('<span class="label-new blink" style="right:5px;">Baru</span>');
		}
		parentEl.prepend(tag);
		parentEl.prepend(label);
	});
}
function afbHotTag() {
	$(document).ready(function() {
		let dataMobile = $("body").data("mobile");
		let parentEl = $('li[class="sports"]').find('li[class="game  afb"] > .icon-menu-wrapper');
		let tag = $('<img src="https://cdn.robotaset.com/assets/images/provider/best-odds-tag.png" class="lobby-icon game-front-tag">');
		if( dataMobile ) {
			parentEl = $('.provider-item-list.sports').find('.afb');
		}
		parentEl.prepend(tag);
	});
}
function reelKingdomBaruTag() {
	$(document).ready(function() {
		let dataMobile = $("body").data("mobile");
		let parentEl = $('li[class="game sub prk"]');
		let tag = $('<span class="label-new blink" style="top:20px;margin-left:20px;">BARU</span>');
		if( dataMobile ) {
			parentEl = $('.provider-item-list').find('.prk');
			tag = $('<span class="label-new blink" style="left:5px">BARU</span>');
		}
		parentEl.prepend(tag);
	});
}
function pragmaticOneTag() {
	$(document).ready(function(){
		let parentEl = $('li[class="game sub pgr"]');
		var dataMobile = $("body").data("mobile");
		if( dataMobile ) {
			parentEl = $('ul[class="provider-item-list slot"]').find('.pgr');
		}
		var img = $(parentEl).find("img");
		var oldSrc = $(img).attr("src");
		var newSrc = oldSrc.replace("pp-hot-tag","pgr-no1");
		$('img[src="' + oldSrc + '"]').attr('src', newSrc).css('top','-5px');
	});
}
function removeFooterLogo() {
	$(document).ready(function() {
		let dataMobile = $("body").attr("data-mobile");
		if( dataMobile == "true" ) {
			$(".infini-logo").remove();
		} else {
			$(".rules-agreement").prev().remove();
		}
	});
}
function copyInfiniLogo() {
	$(document).ready(function() {
		let dataMobile = $("body").attr("data-mobile");
		if( dataMobile == "true" ) {
			var infLogo = $(".infini-logo").clone(true);
			$(infLogo).insertBefore(".asf-logo");
			$(".asf-logo").next('.infini-logo').remove();
		} else {
			var infLogo = $(".rules-agreement").prev().clone(true);
			$(infLogo).insertBefore(".asf-logo");
			$(".rules-agreement").prev().remove();
		}
	});
}

function initializeBankLimit() {
	if( localStorage.lastRequest ) {
		let now = Date.now();
		let lastRequest = Number(localStorage.lastRequest);
		if( (lastRequest - now) < 0 ) {
			localStorage.removeItem("lastRequest");
			getBankLimitTrx();
		}
	} else {
		if( !localStorage.bankLimit && !localStorage.bankList ) {
			getBankLimitTrx();
		}
	}
}

function getBankLimitTrx() {
	/*callApi("/api/bank/limitTrx", null, function(response) {
		let limitTrx = response.data.bankLimit;
		localStorage.bankLimit = JSON.stringify(limitTrx);

		let bankList = response.data.bankList;
		localStorage.bankList = JSON.stringify(bankList);

		let lastRequest = response.data.time;
		localStorage.lastRequest = lastRequest;
	});*/

	// return axios.get('/api/bank/limitTrx').then(function (response) {
	// 	let limitTrx = response.data.data.bankLimit;
	// 	localStorage.bankLimit = JSON.stringify(limitTrx);

	// 	let bankList = response.data.data.bankList;
	// 	localStorage.bankList = JSON.stringify(bankList);

	// 	let lastRequest = response.data.data.time;
	// 	localStorage.lastRequest = lastRequest;
	// })
	// .catch(function (error) {
	// 	console.log(error);
	// });
}

function confirm_signout() {
	if( confirm(alertMsg.confirmation_logout) ) {
		setLoading(true);
		callApi("/api/account/logout", null, function(resp) {
			alert(resp.data.message);

			if( resp.success == true ) {
				// clear all balance from local storage
				clearPvBalance();

				//remove pgs play token
				clearPgsToken();

				// remove list Favorite from localStorage
				localStorage.removeItem("listFavorite");

				// remove list Balance from session Storage
				sessionStorage.clear();

				// reload page
				window.location.reload();
			} else {
				setLoading(false);
			}
		});
	} else {
		return false;
	}
}

function clearBankList(key) {
	if( typeof key === "undefined" ) {
		localStorage.clear();
	} else {
		localStorage.removeItem(key);
	}
}

// checking balance each provider
$(document).on("click", "span.calibrate", function(e) {
	if( confirm(alertMsg.confirmation_calibrate) ) {
   		var _this = $(this);
   		var obj = _this.parent().prev("td").find('span');
   		var main = $("#creditBalance, #main-balance-holder");
   		var balance = 0;

   		var pvcd = _this.attr("data-id");
   		var targetEl = $('#game-balance-'+pvcd.toLowerCase());
		// check if provider has listed in the list provider or not
		var listPv = localStorage.getItem("listPv");
		if( listPv == null || JSON.parse(listPv).length == 0 || !JSON.parse(listPv).includes(pvcd.toUpperCase()) ) {
			alert(alertMsg.calibrate_not_process);
			return false;
		}

		// set loading bar
		targetEl.html('<i class="fa fa-spinner fa-pulse fa-fw"></i>');
		// set data
		var data = {"pvcd":pvcd};
		callApi("/api/wallet/calibrate/provider", data, function(resp) {
			alert(resp.data.message);
			main.html('<i class="fa fa-spinner fa-pulse fa-fw"></i>');
			setTimeout(function() {
				switch(resp.code) {
					case 7003:
					case 19175:
						targetEl.html(alertMsg.pv_locked);
						targetEl.removeAttr('id');
						targetEl.removeAttr('class');
						_this.remove();

						// remove from list provider
						let _listPv = JSON.parse(listPv);
						_listPv = _listPv.filter(item => item !== pvcd.toUpperCase());
						setListPvToSession(_listPv);

						// remove from session storage if exist
						if( sessionStorage.getItem(pvcd.toUpperCase()) != null ) {
							sessionStorage.removeItem(pvcd.toUpperCase());
						}

						if( resp.data.main ) {
							main.text(formatCurrency(resp.data.main, null, 2) + " K");
						}

						countAllBalance();
						break;
					default:
						if( resp.data.balance == null ) {
							obj.text(alertMsg.retry);
						} else {
							var listBalance = resp.data.hasOwnProperty('listBalance') ? resp.data.listBalance : [];
							setBalanceToSession(listBalance);

							$('#game-balance-'+pvcd.toLowerCase()).html(formatCurrency(resp.data.balance, null, 2) + " K");
						}
						if( resp.data.main ) {
							main.text(formatCurrency(resp.data.main, null, 2) + " K");
						}
				}

				countAllBalance();
			}, 1000);
		});
	} else {
		return;
	}
});

/* BALANCE STUFF */
var total = [];
var count = 0;
var clickable = 0;

$(document).on("click", "#creditBalance", function() {
	var target = $("#popover-balance-content");
	target.is(":hidden") ? target.show() : target.hide();
});

$(document).on("click", "#iconReload", function() {
	clickable++;
	if( clickable > 0 && clickable == 1 ) {
		var target = $("#popover-balance-content");
		if( target.is(":hidden") ) {
			$("#creditBalance").html('<i class="fa fa-spinner fa-pulse fa-fw"></i>');

			setTimeout(function() {
				var mainBalance = sessionStorage.getItem("MAIN");
				if( isBalanceExpired(mainBalance) ) {
					var getBalanceUrl = window.location.origin + "/api/wallet/main/getBalance";

					callApi3(getBalanceUrl, "GET", null).then(function(resp) {
						var listBalance = resp.data.hasOwnProperty('listBalance') ? resp.data.listBalance : [];
						setBalanceToSession(listBalance);

						var balance = listBalance[0]['MAIN'].balance;
						$("#creditBalance, .main-wallet").text(formatCurrency(balance, null, 2) + " K");
					});
				} else {
					$("#creditBalance, .main-wallet").text(formatCurrency(JSON.parse(mainBalance).balance, null, 2) + " K");
				}

				clickable = 0;
			}, 1000);
		} else {
			reload_wallet_2();
		}
	} else {
		alert(alertMsg.request_in_process);
	}
});

function reload_wallet_2() {
	$("#creditBalance, .main-wallet, .game-wallet, .totalWallet").html('<i class="fa fa-spinner fa-pulse fa-fw"></i>');

	setTimeout(function() {
		// get list provider
		if( localStorage.getItem("listPv") == null ) {
			var getListPvUrl = window.location.origin + "/api/wallet/calibrate/list";
			callApi3(getListPvUrl, "GET", null).then(function(resp) {
				var listPv = resp.data.hasOwnProperty('listPv') ? resp.data.listPv : [];
				setListPvToSession(listPv);
			});
		}

		// get main wallet
		var mainBalance = sessionStorage.getItem("MAIN");
		if( isBalanceExpired(mainBalance) ) {
			var getBalanceUrl = window.location.origin + "/api/wallet/main/getBalance";
			callApi3(getBalanceUrl, "GET", null).then(function(resp) {
				var listBalance = resp.data.hasOwnProperty('listBalance') ? resp.data.listBalance : [];
				setBalanceToSession(listBalance);

				var balance = listBalance[0]['MAIN'].balance;
				$("#creditBalance, .main-wallet").text(formatCurrency(balance, null, 2) + " K");
				if( JSON.parse(localStorage.getItem("listPv")).length == 0 ) {
					countAllBalance();
					return false;
				}
			}, errorHandler);
		} else {
			$("#creditBalance, .main-wallet").text(formatCurrency(JSON.parse(mainBalance).balance, null, 2) + " K");
			if( JSON.parse(localStorage.getItem("listPv")).length == 0 ) {
				countAllBalance();
				return false;
			}
		}
		//total.push({"pvcd": "MAIN", "balance": balance});

		//get provider balance
		if( pvls.length > 0) {
			for(var i = 0; i < pvls.length; i++) {
				var code = pvls[i].pvcode;
				if( pvls[i].isMaintenance == false && !disabledPv.includes(code) ) {
					var attrid = "game-balance-" + code.toLowerCase();

					if( pvls[i].pvst == 1 ) {
						var json = {"pvcd":code.toLowerCase()};
						getProviderBalance(json, attrid);
					}
				}
			}
		} else {
			$(".game-wallet").each(function(){
				var _this = $(this);
				if( _this.children().is('i') ) {
					_this.children("i").remove();
					_this.text(formatCurrency(0, null, 2) + " K");
				}
				
				counter = 0;
			});

			countAllBalance();
		}
	}, 1000);
}

function getProviderBalance(json, attrid) {
	var listProvider = localStorage.getItem("listPv");

	var pvcd = json.pvcd.toUpperCase();
	if( listProvider.includes(pvcd) ) {
		var pvBalance = sessionStorage.getItem(pvcd);
		if( isBalanceExpired(pvBalance) ) {
			var getPvBalUrl = window.location.origin + "/api/wallet/provider/getBalance";
			callApi3(getPvBalUrl, "POST", json).then(function(resp) {
				var listBalance = resp.data.hasOwnProperty('listBalance') ? resp.data.listBalance : [];
				setBalanceToSession(listBalance);

				if( resp.success == true ) {
					var balance = listBalance[0][pvcd];
					$("#" + attrid).text(formatCurrency(balance.balance, null, 2) + " K");
					total.push({"pvcd": pvcd, "balance": balance.balance});
				} else {
					$("#game-balance-" + pvcd.toLowerCase()).text(alertMsg.retry);
					total.push({"pvcd": pvcd, "balance": 0});
				}

				if( total.length == JSON.parse(listProvider).length ) {
					countAllBalance();
					total = [];
				}
			}, errorHandler);
		} else {
			var balance = JSON.parse(pvBalance);
			$("#" + attrid).text(formatCurrency(balance.balance, null, 2) + " K");
			total.push({"pvcd": pvcd, "balance": parseFloat(balance.balance)});

			if( total.length == JSON.parse(listProvider).length ) {
				countAllBalance();
				total = [];
			}
		}
	} else {
		var _this = $("#" + attrid);
		if( _this.children().is('i') ) {
			_this.children("i").remove();
			_this.text(formatCurrency(0, null, 2) + " K");
		}
	}
}

function calibrate() {
	if( confirm(alertMsg.confirmation_calibrate) ) {
		// show the loader
		$("#dialog-mask").show();

		var payload = {
			listPv: []
		};
		var listProvider = localStorage.getItem("listPv");
		if( listProvider != null ) {
			payload.listPv = JSON.parse(listProvider);
		}

		callApi("/api/wallet/calibrate", payload, function(resp) {
			alert(resp.data.message);
			if( resp.success == true ) {
				// update balance to session
				var listBalance = resp.data.hasOwnProperty('listBalance') ? resp.data.listBalance : [];
				setBalanceToSession(listBalance);

				// update main balance
				$("#creditBalance, .main-wallet").text(formatCurrency(resp.data.main, null, 2) + " K");

				// update provider balance
				var target = $("#popover-balance-content");
				if( !target.is(":hidden") ) {
					_setBalanceAfterCalibrate();
				}
			}

			setTimeout(function() {
				$("#dialog-mask").hide();
			}, 1000);
		});
	} else {
		return;
	}
}

/* Calibrate Mobile Version on sidenav */
$(".balance > .btn-withdraw").on("click", function(e) {
	e.preventDefault();
	if( confirm(alertMsg.confirmation_calibrate) ) {
		// show the loader
		$(".page-loader").show();

		var payload = {
			listPv: []
		};
		var listProvider = localStorage.getItem("listPv");
		if( listProvider != null ) {
			payload.listPv = JSON.parse(listProvider);
		}

		callApi("/api/wallet/calibrate", payload, function(resp) {
			alert(resp.data.message);
			if( resp.success == true ) {
				// update balance to session
				var listBalance = resp.data.hasOwnProperty('listBalance') ? resp.data.listBalance : [];
				setBalanceToSession(listBalance);

				// update main balance
				$("#mainamt").text(formatCurrency(resp.data.main, null, 2) + " K");
			}

			setTimeout(function() {
				$(".page-loader").hide();
			}, 1000);
		});
	} else {
		return;
	}
});

function renderMainBalance(isMobile) {
	$(document).ready(function() {
		let dataMobile = $("body").data("mobile");

		// is Mobile View is true
		if( dataMobile ) {
		} else {
			var el = ['#creditBalance', '.main-wallet'];
			var mainBalance = sessionStorage.getItem("MAIN");
			var balance = 0;
			if( !isBalanceExpired(mainBalance) ) {
				balance = JSON.parse(mainBalance).balance;
			}
			for(var i = 0; i < el.length; i++) {
				if( $(el[i]).length == 1 ) {
//					if( el[i] == '#CurrentBalance' ) {
//						$(el[i]).attr('data-balance', parseInt(balance));
//						$(el[i]).text(parseFloat(balance));
//					} else {
						$(el[i]).text(formatCurrency(balance, null, 2) + " K");
//					}
				}
			}
		}
	});
}

var click = 0;
$("#ReloadBalance").on("click", function() {
	$(".page-loader").show();

	var mainBalance = sessionStorage.getItem("MAIN");
	if( isBalanceExpired(mainBalance) ) {
		var getBalanceUrl = window.location.origin + "/api/wallet/main/getBalance";

		callApi3(getBalanceUrl, "GET", null).then(function(resp) {
			var listBalance = resp.data.hasOwnProperty('listBalance') ? resp.data.listBalance : [];
			setBalanceToSession(listBalance);

			var balance = listBalance[0]['MAIN'].balance;
			var amount = formatCurrency(balance, null, 2);
			$("#mainamt").text( amount + " K" );

			setTimeout(function() {
				$(".page-loader").hide();
			}, 1000);
		});
	} else {
		var amount = formatCurrency(JSON.parse(mainBalance).balance, null, 2);
		$("#mainamt").text( amount + " K" );

		setTimeout(function() {
			$(".page-loader").hide();
		}, 1000);
	}
});

function _setBalanceAfterCalibrate() {
	if( pvls.length > 0 ) {
		var listProvider = JSON.parse(localStorage.getItem("listPv"));

		for(var i = 0; i < pvls.length; i++) {
			var code = pvls[i].pvcode;
			var balance = null;
			if( listProvider.includes(code) ) {
				var obj = JSON.parse(sessionStorage.getItem(code));
				balance = obj != null && obj.hasOwnProperty("balance") ? obj.balance : null;
			}

			if( !pvls[i].isMaintenance && !disabledPv.includes(code) ) {
				var amount = formatCurrency(balance, null, 2);
				var ele = $("#game-balance-" + code.toLowerCase());
				if( ele.children().is('i') ) {
					ele.children("i").remove();
				}
				ele.text(amount + " K");
			}
		}

		countAllBalance();
	}
}

/* BANNER STUFF */
function closePopupBanner(ttlPopupBanner) {
	$(document).on("click", "#CloseBannerPop, .banner-popup-link", function(e) {
		e.preventDefault();

		$("#BannerPop").hide();
		hide_loader();

		if( $(this).hasClass("banner-popup-link") ) {
			window.open($(".banner-popup-link").attr('href'), '_blank').focus();
		}

		var ttl = new Date();
		ttl.setMinutes(ttl.getMinutes() + ttlPopupBanner);
		localStorage.setItem("ttlPopupBanner", ttl.getTime());
	});
}
function closePopupMobileBanner(ttlPopupBanner) {
	$(document).on("click", "#PopupBanner button.close, .banner-popup-link", function(e) {
		e.preventDefault();

		$("#PopupBanner").removeClass("show");
		$(".modal-backdrop").removeClass("show");
		$(".modal-backdrop").hide();

		if( $(this).hasClass("banner-popup-link") ) {
			window.open($(".banner-popup-link").attr('href'), '_blank').focus();
		}

		var ttl = new Date();
		ttl.setMinutes(ttl.getMinutes() + ttlPopupBanner);
		localStorage.setItem("ttlPopupBannerMobile", ttl.getTime());
	});
}
function popupBannerTimer() {
	$("#PopupBanner").ready(function () {
		let counter = new Date().getTime();

		const interval = setInterval(() => {
			counter = parseInt(counter) + parseInt(1000);

			let ttl = localStorage.getItem("ttlPopupBanner");
			if ( ttl != null ) {
				if( counter >= parseInt(ttl) ) {
					// Show the popup banner
					$("#loader").show();
					$("#dialog-mask").show();
					$("#BannerPop").show();

					// remove localstorage
					localStorage.removeItem("ttlPopupBanner");
				} else {
					$("#BannerPop").hide();
				}
			} else {
				$("#BannerPop").show();
				show_loader();
			}
		}, 1000);
	});
}
function popupBannerMobileTimer() {
	$("#PopupBanner").ready(function () {
		let counter = new Date().getTime();

		const interval = setInterval(() => {
			counter = parseInt(counter) + parseInt(1000);

			let ttl = localStorage.getItem("ttlPopupBannerMobile");
			if ( ttl != null ) {
				if( counter >= parseInt(ttl) ) {
					// Show the popup banner
					$("#PopupBanner").show();
					$(".modal-backdrop").show();

					// remove localstorage
					localStorage.removeItem("ttlPopupBannerMobile");
				} else {
					$("#PopupBanner").hide();
					$(".modal-backdrop").hide();
				}
			} else {
				// Show the popup banner
				$("#PopupBanner").show();
				$(".modal-backdrop").show();
			}
		}, 1000);
	});
}

/* GENERAL STUFF */
function errorHandler(statusCode){
	console.log("failed with status", statusCode);
}

function done_reload() {
	$(".game-wallet").each(function(){
		var _this = $(this);
		if( _this.children().is('i') ) {
			_this.children("i").remove();
			_this.text(formatCurrency(0, null, 2) + " K");
		}
		
		counter = 0;
	});
}

function countDown(i) {
    var counter = setInterval(function () {
        i--;
        if( i >= 0 && i < 3) {
        	$('#counter').html(i);
        }
        if( i == 0 ) {	//if i is 0, then stop the interval
        	clearInterval(counter);
        }
    }, 1000);
}

var hideAlert;
function hide_alert() {
	if( $("div.alert").text().length > 0 ) {
		hideAlert = setTimeout(function(){
			$("div.alert").removeClass("alert-danger alert-success alert-warning").html("").hide();
		}, 3000);
	}
}

function closeAlert() {
	setTimeout(function(){
		$("#Alert").html("")
		.removeClass("alert-success alert-danger alert-dismissible fade-in show")
		.hide();
	}, 3000);
}

function realDateTime(){
	setInterval(function(){
		var	d = new Date();
		var hour = d.getHours(); // Jumlah jam (0-23)
		var minute = d.getMinutes(); // Jumlah menit (0-59)
		var second = d.getSeconds(); // Jumlah menit (0-59)
		var month = d.getMonth(); // Jumlah bulan (0-11)
		var day = d.getDate(); // Hari dari bulan (0-31)
		var year = d.getFullYear(); // current year
		var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
		
		if(day < 10) day = '0'+day;
		if(hour < 10) hour = '0'+hour;
		if(minute < 10) minute = '0'+minute;
		if(second < 10) second = '0'+second;
		
		var datetime = day +' '+ months[month] +' '+ year+', '+hour+':'+minute+':'+second;
		
		$("#thedate").text(datetime);
	}, 1000); // 60 seconds
}

function popup(module, addr) {
	var hostname = window.location.href;
	var arr = hostname.split("/");
	var host = arr[0] + "//" + arr[2] + "/";
	var name = module;
	var url = addr == "" ? module : module + "/" + addr;
	var width, height;

	switch(module) {
		case "bank":
		case "bonus":
		case "report":
			width = 1100; height = 685;
			break;
		case "account":
			width = 1100; height = 600;
			break;
		case "common":
			width = 815; height = 800;
			name = "_blank";
			url = addr;
			break;
	}
	
    mywindow = window.open(host + url, name, "scrollbars=yes,resizable=yes,top=20,left=20,width=" + width + ",height=" + height);
    mywindow.focus();
}

function do_login(target/*, id*/) {
	$('#LoginPopupModal').modal({backdrop: 'static', keyboard: false});
	$('#target').val(target);
//	$('#gmsb').val(id);
}

function close_mask() {
	$("#LoginPopupModal").modal("hide").css({'z-index': ''});
	$('#target').val("");
}

function capitalize(str) {
   var splitStr = str.toLowerCase().split(' ');
   for (var i = 0; i < splitStr.length; i++) {
       // You do not need to check if i is larger than splitStr length, as your for does that for you
       // Assign it back to the array
       splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);     
   }
   // Directly return the joined string
   return splitStr.join(' '); 
}

function hide_loader() {
	$('#dialog-mask').hide();
}
function show_loader() {
	$('.page-loader').show();
}

function select_language() {
	if($(".dropMenu:visible").length == 0) {
		$(".dropMenu").show();
	} else {
		$(".dropMenu").hide();
	}
}

function redirectPage(path) {
	if( typeof path !== "undefined" ) {
		var target = baseUrl(path);
		window.location.replace(target);
	} else {
		location.reload();
	}
}

function baseUrl(path) {
	var object = window.location;
	var scheme = object.protocol;
	var host = object.hostname;
	var port = object.port;
	var baseUrl = scheme + "//" + host;
	if( port != "" ) {
		baseUrl = baseUrl + ":" + port
	}
//	var baseUrl = port == "" ? scheme + "//" + host : scheme + "//" + host + ":" + port;
	if( typeof path !== "undefined" ) {
		baseUrl = path.substring(0, 4) == "http" ? path : baseUrl + "/" + path;
	}

	return baseUrl;
}

function digits(e) {
	if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
		// Allow: Ctrl+A,Ctrl+C,Ctrl+V, Command+A
		((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||
		// Allow: home, end, left, right, down, up
		(e.keyCode >= 35 && e.keyCode <= 40)) {
		// let it happen, don't do anything
		return;
	}

	if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
		e.preventDefault();
	}
}

function closeElementOnMouseUp(element) {
	$(document).mouseup(function(e) {
		var container = $(element);
	
		if( $("#popover-balance-content").is(":visible") ) {
			// if the target of the click isn't the container nor a descendant of the container
			if (!container.is(e.target) && container.has(e.target).length === 0) {
				$("#popover-balance-content").hide();
			}
		}
	});
}
function closeSelectDivOnMouseUp() {
	$(document).mouseup(function(e) {
		var container = $(".conlist.active");
	
		// if the target of the click isn't the container nor a descendant of the container
		if (!container.is(e.target) && container.has(e.target).length === 0) {
			container.removeClass("active");
		}
	});
}

// SSE feature
// var MAIN_BALANCE = ["#creditBalance","#FromWallet","#ToWallet","#MainAmount > dd","#CurrentBalance","#MainWalletAmount","#mainamt"];
var MAIN_BALANCE = [
	{"name":"#creditBalance", "suffix":" K"},
	{"name":"#mainamt", "suffix":" K"},
	{"name":"#main-balance-holder", "suffix":" K"},
	// {"name":".totalWallet", "suffix":" K"},
	{"name":"#FromWallet", "suffix":""},
	{"name":"#ToWallet", "suffix":""},
	{"name":"#MainAmount > dd", "suffix":""},
	{"name":"#CurrentBalance", "suffix":""},
	{"name":"#MainWalletAmount", "suffix":""}
];
function _sseUpdateBalance(obj) {
	var data = JSON.parse(obj);
	if( data.act == "creditBalanceFeUp" ) {
		var balance = formatCurrency(data.balance, null, 2);

		for(var i = 0; i < MAIN_BALANCE.length; i++) {
			var el = MAIN_BALANCE[i];
			if( $(el.name).length == 1 ) {
				// set all
				$(el.name).text(balance + el.suffix);

				var tagName = $(el.name).prop("tagName").toLowerCase();
				if( tagName == "input" ) {
					$(el.name).val(formatCurrency(data.balance, null, 0));
					$(el.name).attr("data-balance", data.balance);
				} else {
					if( el.name.includes("CurrentBalance") ) {
						$(el.name).text(formatCurrency(data.balance, null, 0));
						$(el.name).attr("data-balance", data.balance);
					}

					// desktop
					// var popoverBal = $("#popover-balance-content");
					// if( popoverBal.is(":hidden") && el.name.includes("totalWallet") ) {
					// }
					var trFrom = $("#TransferFrom").find("li.selected").data("value");
					var trTo = $("#TransferTo").find("li.selected").data("value");
					if( trFrom != "" && trTo != "" ) {
						if( trFrom == "MAIN" && trTo != "MAIN" && el.name.includes("ToWallet") ) {
							$(el.name).text(formatCurrency(0, null, 2));
						}
						if( trFrom != "MAIN" && trTo == "MAIN" && el.name.includes("FromWallet") ) {
							$(el.name).text(formatCurrency(0, null, 2));
						}
					}

					// mobile
					var mtrFrom = $("#TransferFrom").find("option:selected").val();
					var mtrTo = $("#TransferTo").find("option:selected").val();
					if( mtrFrom != "" && mtrTo != "" ) {
						if( mtrFrom == "MAIN" && mtrTo != "MAIN" && el.name.includes("ToWallet") ) {
							$(el.name).text(formatCurrency(0, null, 2));
						}
						if( mtrFrom != "MAIN" && mtrTo == "MAIN" && el.name.includes("FromWallet") ) {
							$(el.name).text(formatCurrency(0, null, 2));
						}
					}
				}
			}
		}
	}
}

function newPoolCategory() {
	$(document).ready(function() {
		// check if4 element first
		var dataMobile = $("body").data("mobile");
		if( !dataMobile ) {
			var ifdWeb = $('a[data-provider="ifd"]');
			if( ifdWeb.length == 1 ) {
				var el = $("li.lottery");
				// add New elements
				el.prepend('<span class="label-new blink">PROMO</span>');
			}
		} else {
			var ifdMobile = $('ul[class="provider-item-list lottery"]');
			if( ifdMobile.length == 1 ) {
				var elMob = ifdMobile.find('.ifd');
				if( elMob.length == 1 ) {
					var el = $("i.lottery");
					// add New elements
					el.before('<span class="label-new blink">PROMO</span>');
					el.find("span:last-child");
				}
			}
		}
	});
}

function setLoading(isSet) {
	isSet == true ? $(".page-loader").show() : $(".page-loader").hide();
}

function clearTempData() {
	if( typeof getCookie("_cf_tkn") === "undefined" ) {
		// remove list Balance from session Storage
		sessionStorage.clear();

		//remove pgs play token
		clearPgsToken();

		// remove list Pv from localStorage
		localStorage.removeItem("listPv");

		// remove leftover data from localstorage
		clearLeftoverBalance();
	}
}

function setBalanceToSession(listBalance) {
	var balance = listBalance;
	if( balance.length > 0 ) {
		balance.forEach((row) => {
			for(var j in row){
				var k = j;
				var v = row[j];
				sessionStorage.setItem(k, JSON.stringify(v));
			}
		});
	}
}

function setListPvToSession(listPv) {
	localStorage.setItem("listPv", JSON.stringify(listPv));
}

function countAllBalance() {
	var _total = 0;
	let keys = Object.keys(sessionStorage);
	for(let key of keys) {
		var val = sessionStorage.getItem(key);
		if( val != null && JSON.parse(val).hasOwnProperty('balance') ) {
			_total = parseFloat(_total) + parseFloat(JSON.parse(val).balance);
		}
	}

	$(".totalWallet").html("<b>" + formatCurrency(_total, null, 2) + " K</b>");
	clickable = 0;
}

function getCookie(name) {
	const value = `; ${document.cookie}`;
	const parts = value.split(`; ${name}=`);
	if (parts.length === 2) return parts.pop().split(';').shift();
}

function isBalanceExpired(obj) {
	if ( obj == null ) {
		return true;
	} else {
		var arr = JSON.parse(obj);
		// check if object has 'balance' key
		if( !arr.hasOwnProperty('balance') ) {
			return true;
		}

		// check if object has 'hasTransfer' key
		if( arr.hasOwnProperty('hasTransfer') && arr.hasTransfer == 1 ) {
			return true;
		}

		// check if object has 'ts' key
		if( arr.hasOwnProperty('ts') && new Date().getTime() >= Number(arr.ts) ) {
			return true;
		}
	}

	return false;
}

function clearPgsToken() {
	for (var i = 0; i < localStorage.length; i++) {
		var key = localStorage.key(i);
		if (key != null && key.includes("playToken")) {
			localStorage.removeItem(key);
		}
	}
}

function clearPvBalance() {
	var listProvider = JSON.parse(localStorage.getItem("listPv"));
	if( listProvider != null && listProvider.length > 0 ) {
		listProvider.forEach((key) => {
			localStorage.removeItem(key);
		});
	}
	// clear main wallet
	localStorage.removeItem("MAIN");
	// clear listPv
	localStorage.removeItem("listPv");
}

function clearLeftoverBalance() {
	let keys = Object.keys(localStorage);
	for(let key of keys) {
		var val = localStorage.getItem(key);
		if( val != null && (JSON.parse(val).hasOwnProperty('balance') || JSON.parse(val).hasOwnProperty('ts')) ) {
			localStorage.removeItem(key);
		}
	}
}


function setListFavorite(listFavorite){
	localStorage.setItem("listFavorite", JSON.stringify(listFavorite));
}

function getListProvider() {
	if( document.cookie.indexOf('_cf_tkn=') != -1 ) {
		if( localStorage.getItem("listPv") == null ) {
			var getListPvUrl = window.location.origin + "/api/wallet/calibrate/list";
			callApi3(getListPvUrl, "GET", null).then(function(resp) {
				var listPv = resp.data.hasOwnProperty('listPv') ? resp.data.listPv : [];
				setListPvToSession(listPv);
			});
		}
	}
}
