let zoomIndex = 0;

var UNumber=0;
var UNInfo=new Array();
var UNChecker=new Array();
var nicknameexecuter=false;
var LanguageLoad = false;
var toastList = new Array();
var script = document.createElement("script");  // create a script DOM node
script.src = '/api/translater';  // set its src to the provided URL
document.head.appendChild(script);
script.onload = langcall;
function langcall(){
	LanguageLoad = true;
}

function nl2br(str) {
    str = str.replace(/\r\n/g, "<br />");
    str = str.replace(/(\n|\r)/g, "<br />");
    return str;
}
function lw(url){
	if(parseInt(window.innerWidth)<=993){
		location.href=url;
	}
}

function nicknameCaller(){
	var ids=document.getElementsByClassName("UNICKCLASS");
	for(var ii=0;ii<ids.length;ii++){
		if(ids[ii].getAttribute('data-execeed')!='complete'){
			idx=ids[ii].getAttribute('data-ids');
			ids[ii].setAttribute('id',"UN_"+UNumber);
			ids[ii].id="UN_"+UNumber;
			status = UNChecker[idx];
			if(status!='ready'){
				if(idx!=''){
					UNChecker[idx]='ready';
					if(UNInfo[idx]){
						UNIPrint();
					}else{
						$.ajax({
							type: 'POST',
							url: '/member/api/getuserinfo',
							data: {
								idx:idx,
								num:1,
							},
							dataType:"JSON",
							error: function(){},
							success: function(response){
								// console.log(response);
								// console.log(UNumber);
								UNInfo[response.result.idx]=response;
								UNIPrint();
							},
						});
					}
				}
			}else{
				UNIPrint();				
			}
			UNumber++;
		}
	}
}

function UNIPrint(){
	if(LanguageLoad == false){
		setTimeout(function(){ UNIPrint(); },100);
		return false;
	}
	var ids=document.getElementsByClassName("UNICKCLASS");
	for(var ii=0;ii<ids.length;ii++){
		idx_now = ids[ii].getAttribute('data-ids');
		response = UNInfo[idx_now];
		if(UNInfo[idx_now]){
			if(ids[ii].getAttribute('data-execeed')!='complete'){
				ids[ii].setAttribute('data-execeed','complete');
				innerdata = '<a tabindex="0" role="button"'+
					' data-bs-allowlist="button"'+
					' style="font-weight:bold;"'+
					' class="UNICLI"'+
					' data-bs-toggle="popover"'+
					' onclick="'+
						'var x=document.getElementsByClassName(\'popover\');'+
						'for(var xi=0;xi<x.length;xi++){'+
							'bootstrap.Popover.getInstance(x[xi]).hide();'+
						'}'+
						'var x=document.getElementsByClassName(\'UNICLI\');'+
						'for(var xi=0;xi<x.length;xi++){'+
							'x[xi].ovisible=false;'+
						'}'+
						'if(this.ovisible!=true){'+
							'this.ovisible=true; bootstrap.Popover.getInstance(this).show();'+
						'}else{ '+
							'this.ovisible=false; bootstrap.Popover.getInstance(this).hide();'+
						'}"'+

					' data-bs-sanitizeFn=null'+
					' data-bs-sanitize="false"'+
					' data-bs-trigger="manual"'+
					' data-bs-html="true"'+
					' data-bs-template=\''+
						'<div class="popover" role="tooltip">'+
							'<div class="popover-arrow"></div>'+
							'<h3 class="popover-header" style="color:black;text-align:center;"></h3>'+
							'<div class="popover-body" style="color:black;text-align:center;"></div>'+
							'<div class="popover-footer"></div>'+
						'</div>\''+
					' data-bs-content=\''+
						'<b>'+response.result.nickname+'</b> ('+response.result.user_id+')<br/>'+
						'<img src="/user_img/'+response.result.user_id.toUpperCase().substring(0,1)+'/'+response.result.user_id+'"/><br/>'+
						// ''+LANG['language']+' <img src="/img/flag/'+response.result.use_lang.toLowerCase()+'.png" alt="'+response.result.use_lang+'"/> '+
						// ''+LANG['country']+' <img src="/img/flag/'+response.result.country.toLowerCase()+'.png" alt="'+response.result.country+'"/><br/>'+
						'<a href="#makefriends#'+response.result.idx+'#'+response.result.user_id+'#'+response.result.nickname+'" class="btn btn-danger btn-sm">'+LANG['make_friend']+'</a> '+
						'<a href="https://'+response.result.user_id+'.kishe.com" class="btn btn-secondary btn-sm"><i class="bi bi-book-half"></i> '+LANG['Diary']+'</a> '+
						'<a href="#sendmessage#'+response.result.idx+'#'+response.result.user_id+'#'+response.result.nickname+'" class="btn btn-warning btn-sm"><i class="bi bi-envelope"></i> '+LANG['sendmessage']+'</a> '+

						''+'\'>';
					if(ids[ii].getAttribute('data-flag')==undefined || ids[ii].getAttribute('data-flag')==''){
						innerdata += '<img src="/img/flag/'+response.result.country.toLowerCase()+'.png" alt=" CONNECT:'+response.result.country+'"/>'
					}else{
						innerdata += '<img src="/img/flag/'+ids[ii].getAttribute('data-flag').toLowerCase()+'.png" alt=" CONNECT:'+ids[ii].getAttribute('data-flag')+'"/>'

					}
					innerdata += ' '+response.result.nickname+''+
				'</a>';
				ids[ii].innerHTML=innerdata;
				var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'))
				var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
					return new bootstrap.Popover(popoverTriggerEl)
				});
			}
		}
	}
}
window.onpopstate = function(event) {
	url = document.location.toString();
	urls = url.split("#");
	if(urls[1]=='makefriends'){
		idx = urls[2];
		user_id = urls[3];
		nickname = urls[4];
		var x=document.getElementsByClassName('popover');
		for(var xi=0;xi<x.length;xi++){
			bootstrap.Popover.getInstance(x[xi]).hide();
		}
		history.go(-1);
		makefriends(idx,user_id,nickname);
	}else if(urls[1]=='sendmessage'){
		idx = urls[2];
		user_id = urls[3];
		nickname = urls[4];
		var x=document.getElementsByClassName('popover');
		for(var xi=0;xi<x.length;xi++){
			bootstrap.Popover.getInstance(x[xi]).hide();
		}
		history.go(-1);
		sendmessage(idx,user_id,nickname);
	}
};
window.onclick = function(event) {
	var x=document.getElementsByClassName('popover');
	poclode = true;
	for(var xi=0;xi<x.length;xi++){
		if(bootstrap.Popover.getInstance(x[xi]).tip.classList.contains('show') == false){
			poclode = false;
		}
	}
	if(poclode == false){
		setTimeout(function(){
			var x=document.getElementsByClassName('popover');
			for(var xi=0;xi<x.length;xi++){
				bootstrap.Popover.getInstance(x[xi]).hide();
			}
		},1000);
	}
};


function disnone(ids){
	console.log('a');
	ids.style.display='none';
}
function makefriends(id,user_id,nickname){
	if(document.getElementById("friendsModald")){
	}else{
		var fmodal = document.createElement("div");
		fmodal.setAttribute('id','friendsModald');
		fmodal.setAttribute('class','modal fade');
		fmodal.setAttribute('tabindex','-1');
		fmodal.setAttribute('role','dialog');
		fmodal.innerHTML='<div class="modal-dialog" role="document">\
		    <div class="modal-content">\
		    <input type="hidden" id="add_friend_user_idx"/>\
		      <div class="modal-header">\
		        <h5 class="modal-title">'+LANG['add_friend_title']+'</h5>\
		        <button type="button" style="border:0;background-color:white;" class="close" onclick=\'$("#friendsModald").modal("hide");return false;\' aria-label="Close">\
		          <span aria-hidden="true">&times;</span>\
		        </button>\
		      </div>\
		      <div class="modal-body">\
		        <p>'+LANG['add_friend_comment']+'</p>\
		        <p>'+LANG['add_friend_to']+' : <span id="afnickname"></span> (<span id="afuser_id"></span>)</p>\
		        <input type="text" id="add_friend_comments" class="form-control"/>\
		      </div>\
		      <div class="modal-footer">\
		        <button type="button" class="btn btn-primary" onclick="SendFriendRequest();return false;">'+LANG['add_friend_btn']+'</button>\
		        <button type="button" class="btn btn-secondary" onclick=\'$("#friendsModald").modal("hide");return false;\'>'+LANG['Close']+'</button>\
		      </div>\
		    </div>\
		  </div>';
		document.body.appendChild(fmodal);
		$('#friendsModald').modal({
		  backdrop: 'static',
		  keyboard: false
		});
	}

	$.ajax({
		type: 'POST',
		url: '/api/checkfriend',
		data: {
			user_idx:id,
		},
		dataType:"JSON",
		error: function(){},
		success: function(response){
			console.log(response);
			switch(response.result){
				case"itsme":alert(LANG['add_friend_itsme']);break;
				case"login":
					location.href='/member/loginstart?rurl='+location.href.toString();
					break;
				case"aleady":alert(LANG['add_friend_aleady']);break;
				case"add_ok":
					$('#add_friend_comments').attr("style","");
					$('#add_friend_comments').val("");
					$('#afnickname').html(decodeURI(nickname));
					$('#afuser_id').html(decodeURI(user_id));
					$('#add_friend_user_idx').val(decodeURI(id));
					$('#friendsModald').modal('show');
					setTimeout("$('#add_friend_comments').focus();",500);
				break;
			}

		},
	});
}
function SendFriendRequest(){
	if($('#add_friend_comments').val()==''){
		$('#add_friend_comments').attr("style","border-color:red");
		$('#add_friend_comments').focus();
	}else{
		$.ajax({
			type: 'POST',
			url: '/api/addfriend',
			data: {
				user_idx:$('#add_friend_user_idx').val(),
				comment:$('#add_friend_comments').val(),
			},
			dataType:"JSON",
			error: function(){},
			success: function(response){
				console.log(response);
				switch(response.result){
					case"itsme":alert(LANG['add_friend_itsme']);break;
					case"login":
						location.href='/member/loginstart?rurl='+location.href.toString();
						break;
					case"aleady":alert(LANG['add_friend_aleady']);break;
					case"invited":
					case"aleady_invite":
						if(document.getElementById("friendinvitetoast")){

						}else{
							var fmodal = document.createElement("div");
							fmodal.setAttribute('id','friendinvitetoast');
							fmodal.setAttribute('class','position-fixed justify-content-center align-items-center w-100');
							fmodal.setAttribute('aria-live','polite');
							fmodal.setAttribute('aria-atomic','true');
							fmodal.innerHTML='<div class="modal-dialog" role="document">\
							  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true">\
							    <div class="toast-header">\
							      <strong class="me-auto">'+LANG['add_friend_title']+'</strong>\
							      <button type="button" class="btn-close" onclick="toastList[0].hide();" aria-label="Close"></button>\
							    </div>\
							    <div class="toast-body" id="InviteToastBody">'+LANG['add_friend_invited']+'</div>\
							  </div>';
							document.body.appendChild(fmodal);
							var toastElList = [].slice.call(document.querySelectorAll(".toast"));
							toastList = toastElList.map(function (toastEl) {
							  return new bootstrap.Toast(toastEl, {});
							});
						}
						if(response.result == 'invited'){
							$('#InviteToastBody').html(LANG['add_friend_invited']);
						}else{
							$('#InviteToastBody').html(LANG['add_friend_aleady_invited']);
						}

						$('#friendsModald').modal('hide');
						setTimeout("toastList[0].show();",300);
					break;
				}
			},
		});
	}

}

function sendmessage(id,user_id,nickname){
	if(document.getElementById("sendMessageBox")){
	}else{
		var fmodal = document.createElement("div");
		fmodal.setAttribute('id','sendMessageBox');
		fmodal.setAttribute('class','modal fade');
		fmodal.setAttribute('tabindex','-1');
		fmodal.setAttribute('role','dialog');
		fmodal.innerHTML='<div class="modal-dialog" role="document">\
		    <div class="modal-content">\
		    <input type="hidden" id="add_friend_user_idx"/>\
		      <div class="modal-header">\
		        <h5 class="modal-title">'+LANG['sendmessage']+'</h5>\
		        <button type="button" style="border:0;background-color:white;" class="close" onclick=\'$("#sendMessageBox").modal("hide");return false;\' aria-label="Close">\
		          <span aria-hidden="true">&times;</span>\
		        </button>\
		      </div>\
		      <div class="modal-body">\
		        <p>'+LANG['add_friend_to']+' : <span id="afnickname"></span> (<span id="afuser_id"></span>)</p>\
		        <textarea id="send_msg_comments" rows="4" class="form-control"/></textarea>\
		      </div>\
		      <div class="modal-footer">\
		        <button type="button" class="btn btn-danger" onclick="SendMessage(this);return false;">'+LANG['Send']+'</button>\
		        <button type="button" class="btn btn-secondary" onclick=\'$("#sendMessageBox").modal("hide");return false;\'>'+LANG['Close']+'</button>\
		      </div>\
		    </div>\
		  </div>';
		document.body.appendChild(fmodal);
		$('#sendMessageBox').modal({
		  backdrop: 'static',
		  keyboard: false
		});
	}
	$('#send_msg_comments').attr("style","");
	$('#send_msg_comments').val("");
	$('#afnickname').html(decodeURI(nickname));
	$('#afuser_id').html(decodeURI(user_id));
	$('#add_friend_user_idx').val(decodeURI(id));
	$('#sendMessageBox').modal('show');
	setTimeout("$('#send_msg_comments').focus();",500);
}
function SendMessage(ids){
	idsv = ids.parentNode.parentNode.getElementsByTagName("input")[0];
	if($('#send_msg_comments').val().length<1){
		alert('메세지를 입력해주세요');
		$('#send_msg_comments').focus();
	return false;
	}
	msglog = 'Msg|X|'+myIdx+'|'+idsv.value+'||memo||'+$('#send_msg_comments').val();
	conn.send(msglog);
	$('#sendMessageBox').modal('hide');

	  var divs = document.getElementsByTagName("div");
	  var tb = null;
	  for(var i=0; i<divs.length; i++){
	    if(divs[i].getAttribute('name') == 'msgToastBox'){
	      tb = divs[i];
	    }
	  }
	  if(tb == null){
	    tb = document.createElement("div");
	    tb.className="toast-container";
	    tb.setAttribute("name","msgToastBox");
	    tb.setAttribute("style","position:fixed;bottom:10px;right:10px;z-index:10000000;");
	    document.body.appendChild(tb);
	  }else{
	  }
	  var newMsg = document.createElement("div");
	  newMsg.className="toast";
	  newMsg.setAttribute("role","alert");
	  newMsg.setAttribute("aria-live","assertive");
	  newMsg.setAttribute("aria-atomic","true");
	  newMsg.setAttribute("style","z-index:10000000;");
	  newMsg.innerHTML='\
	    <div class="toast-header" style="background-color:white !important;">\
	      <strong class="me-auto">메세지 전송</strong>\
	      <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>\
	    </div>\
	    <div class="toast-body" style="background-color:white !important;">전송되었습니다.</div>\
	    <div class="toast-footer" style="background-color:white !important;padding:10px;">\
	    </div>\
	  ';
	  tb.appendChild(newMsg);

	  var toastElList = [].slice.call(document.querySelectorAll(".toast"));
	  var toastList = toastElList.map(function (toastEl) {
	    return new bootstrap.Toast(toastEl, {
	      delay : 2000,
	      autohide : true,
	    });
	  });
	  toastList[toastList.length-1].show();
	  document.getElementById('sent_sound').play();


}


function paste_translater(idx,vals){
	$.ajax({
		type: 'POST',
		url: '/translater',
		data: {
			idx:idx,
		},
		dataType:"JSON",
		error: function(){},
		success: function(response){
			$('#TRAN_'+idx).html(response['return'][vals]);
		},
	});
}


function getOriginalSize ( imgTag ){ 
    var width = 0, height = 0; 
    if ( "naturalWidth" in imgTag ){ 
            width = imgTag.naturalWidth; 
            height = imgTag.naturalHeight; 
    } 
    else { 
            var newImg = new Image(); 
            newImg.src = imgTag.src; 
            width = newImg.width; 
            height = newImg.height; 
    } 
    return { width: width, height: height }; 
}



var myOffcanvas = '';
var bsOffcanvas = '';
var dist = 100;
var s_X;
var e_X;
var s_Y;
var e_Y;
function setSwipe(elem) {
	document.addEventListener('touchstart', function(e) {
		s_X = e.touches[0].pageX;
		e_X = null;
		s_Y = e.touches[0].pageY;
		e_Y = null;
	});
	document.addEventListener('touchmove', function(e) {
		e_X = e.changedTouches[0].pageX;
		e_Y = e.changedTouches[0].pageY;
	});
	document.addEventListener('touchend', function(e) {
		if (s_X > e_X + dist && e_Y-s_Y < 50 && e_Y-s_Y > -50) {
			menu_close();
			s_X = null;
			e_X = null;
		} else if (s_X + dist < e_X && e_Y-s_Y < 50 && e_Y-s_Y > -50) {
			menu_open();
			s_X = null;
			e_X = null;
		}
	});
}
function menu_open(){
	try{
		document.getElementById("mobileMenuBox").style.width = "100%";
	}catch(e){}
}
function menu_close(){
	try{
		document.getElementById("mobileMenuBox").style.width = "0";
	}catch(e){}
}
$(function() {
	setSwipe('.swipearea');
});


function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

function number_format(num) {
  return num.toString().replace(
    /(\d+?)(?=(?:\d{3})+$)/g,
    function (x) {
      return x + ',';
    }
  );
}
