//////////////////////////////////////////////////////////////
// universal.js - Simple JS functions that make JS easy
// Inspired by Alons
// ----------------------------------------------------------
// Please Read the Terms of use at http://www.softaculous.com
// ----------------------------------------------------------
// (c)Softaculous Inc.
//////////////////////////////////////////////////////////////

ua = navigator.userAgent.toLowerCase();
isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
IE_version = 0;
if(isIE){
	var _match = /(msie) ([\w.]+)/.exec( ua );
	IE_version = parseInt(_match[2]);
}
isFF = (ua.indexOf("firefox") != -1);
isGecko = (ua.indexOf("gecko") != -1);
isSafari = (ua.indexOf("safari") != -1);
isKonqueror = (ua.indexOf("konqueror") != -1);
var task_status = '';
aefonload = '';

//Cipy Stuff
function copy(ele, copy_ele){
    var txt = document.getElementById(copy_ele).innerText || document.getElementById(copy_ele).textContent;
	
	if (navigator && navigator.clipboard && navigator.clipboard.writeText){
		navigator.clipboard.writeText(txt);
	}else{
		const el = document.createElement('textarea');
		el.value = txt;
		el.setAttribute('readonly', '');
		el.style.position = 'absolute';
		el.style.left = '-9999px';
		document.body.appendChild(el);
		el.select();
		document.execCommand('copy');
		document.body.removeChild(el);
	}
	
    $(ele).popover({
        content:'Copied!',
        placement:'top'
    })
    $(ele).popover('show')
    setTimeout(function(){
        $(ele).popover('hide')
    }, 700)
};
//Element referencer - We use $ because we love PHP
function $_(id){
	//DOM
	if(document.getElementById){
		return document.getElementById(id);
	//IE
	}else if(document.all){
		return document.all[id];
	//NS4
	}else if(document.layers){
		return document.layers[id];
	}
};

//Trims a string
function trim(str){
	return str.replace(/^[\s]+|[\s]+$/, "");
};

//Give a random integer
function AEFrand(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

//To clear a time out
function AEFclear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};

//Changes the opacity
function setopacity(el, opacity){
	el.style.opacity = (opacity/100);
	if(isIE){ el.style.zoom = 1; }
	el.style.filter = 'alpha(opacity=' + opacity + ')';
};

//Hides an element
function hideel(elid){
	$_(elid).style.visibility="hidden";
};

//Shows an element
function showel(elid){
	$_(elid).style.visibility="visible";
};

function isvisible(elid){
	if($_(elid).style.visibility == "visible"){
		return true;
	}else{
		return false;
	}
}

//Checks the entire range of checkboxes
function check(field, checker){
	if(checker.checked == true){
		for(i = 0; i < field.length; i++){
			field[i].checked = true;
		}
	}else{
		for(i = 0; i < field.length; i++){  
			field[i].checked = false;
		}
	}
};
//The page width
function getwidth(){
	return document.body.clientWidth;
};
//The page height
function getheight(){
	return document.body.clientHeight;
};

//Get the scrolled height
function scrolledy(){
	//Netscape compliant
	if(typeof(window.pageYOffset) == 'number'){
		return window.pageYOffset;
	//DOM compliant
	}else if(document.body && document.body.scrollTop){
		return document.body.scrollTop;
	//IE6 standards compliant mode
	}else if(document.documentElement && typeof(document.documentElement.scrollTop)!='undefined'){
		return document.documentElement.scrollTop;
	}else{
		return 0;	
	}
};

//Gradually increases the opacity
function smoothopaque(elid, startop, endop, inc){
	if(typeof(elid) == 'object'){
		var el = elid;
	}else{
		var el = $_(elid);
	}
	op = startop;
	//Initial opacity
	setopacity(el, op);
	//Start the opacity timeout that makes it more visible
	setTimeout(slowopacity, 1);
	function slowopacity(){
		if(startop < endop){
			op = op + inc;
			if(op < endop){
				setTimeout(slowopacity, 1);
			}
		}else{
			op = op - inc;
			if(op > endop){
				setTimeout(slowopacity, 1);
			}
		}
		setopacity(el, op);		
	};
};

//Cookie setter

function setcookie(name, value, duration){
	value = escape(value);
	if(duration){
		var date = new Date();
		date.setTime(date.getTime() + (duration * 86400000));
		value += "; expires=" + date.toGMTString();
	}
	document.cookie = name + "=" + value +";";
};

//Gets the cookie value
function getcookie(name){
	value = document.cookie.match('(?:^|;)\\s*'+name+'=([^;]*)');
	return value ? unescape(value[1]) : false;
};

//Removes the cookies
function removecookie(name){
	setcookie(name, '', -1);
};

function AJAX(url, evalthis, met, send){
	var send = (send || null);
	var met = (met || "GET");
	var req = false;
	var toeval = evalthis;
	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest){
		try{
			req = new XMLHttpRequest();
		}catch(e){
			req = false;
		}
	// branch for IE/Windows ActiveX version
	}else if(window.ActiveXObject){
	   	try{
			req = new ActiveXObject("Msxml2.XMLHTTP");
	  	}catch(e){
			try{
		  		req = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){
		  		req = false;
			}
		}
	}
	
	if(req){
		try{
			req.onreadystatechange = function(){				
				// only if req shows "loaded"
				if (req.readyState==4) {
					//only if OK
					if (req.status == 200) {
						// only if "OK"...processing statements go here..
						var re = req.responseText // result of the req object
						if(re.length > 0){
							return eval(toeval);
						}else{
							return false;
						}
					}
				}
			};
			req.open(met, url, true);
			if(met.toLowerCase() == "post"){req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); }
			req.send(send);
		}catch(e){
			return false;
		}
	}else{
		return false;
	}
	return true;
};

//Finds the position of the element
function findelpos(ele){
	var curleft = 0;
	var curtop = 0;
	if(ele.offsetParent){
		while(1){
			curleft += ele.offsetLeft;
			curtop += ele.offsetTop;
			if(!ele.offsetParent){
				break;
			}
			ele = ele.offsetParent;
		}
	}else if(ele.x){
		curleft += ele.x;
		curtop += ele.y;
	}
	return [curleft,curtop];
};

function getAttributeByName(node, attribute){
	if(typeof NamedNodeMap != "undefined"){
		if(node.attributes.getNamedItem(attribute)){
			return node.attributes.getNamedItem(attribute).value;
		}
	}else{
		return node.getAttribute(attribute);
	}
};

function AttributeByName(node, attribute){
	if(typeof NamedNodeMap != "undefined"){
		if(node.attributes.getNamedItem(attribute)){
			return node.attributes.getNamedItem(attribute);
		}
	}else{
		return node.getAttribute(attribute);
	}
};

//With ';'
function addonload(js){
	aefonload += js;
};

function randstr(length, special, strength){
	
	var special = special || 0;
	var strength = strength || 0;
	$randstr = "";
	$specialchars = new Array('&', '#', '$', '%', '@');
	//alert(special);
	for($i = 0; $i < length; $i++){	
		$randnum = Math.floor(Math.random()*61);
		if($randnum < 10){		
			$randstr = $randstr + String.fromCharCode($randnum+48);			
		}else if($randnum < 36){		
			$randstr = $randstr + String.fromCharCode($randnum+55);			
		}else if(special > 0){
			var tmp = Math.floor(Math.random() * $specialchars.length);
			$randstr = $randstr + $specialchars[tmp];
		}else{		
			$randstr = $randstr + String.fromCharCode($randnum+61);			
		}
	}
	
	// Do we have to meet the strength set by admin ?
	if(strength > 0){
		$cur_strength = passwordStrength($randstr);
		if($cur_strength[1] < strength){
			while ($cur_strength[1] < strength) {
				$randnum = Math.floor(Math.random()*61);
				$randstr = $randstr + String.fromCharCode($randnum+55);
				$cur_strength = passwordStrength($randstr);
			}
		}
	}
	
	if(special > 0){
		return $randstr;
	}else{
		return $randstr.toLowerCase();	
	}
};

// Random password String with Special characters
function rand_pass(length){

	var $string="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*";
	var $randpass = "";
	
	for ($i = 0; $i < length; $i++){
		
		$randpass += $string.charAt(Math.floor(Math.random() * $string.length));
	}
	
	return $randpass;

};

function sub_but(el, c){
	var oldclass = el.className;
	el.className = c || 'submiton';
	el.onmouseout= function(){
						el.className = oldclass;
					};
};

function getFormValues(id){
	var vals = new Array();
	var elem = $_(id).elements;
	for(var i = 0; i < elem.length; i++){
		vals[i] = elem[i].name+"="+escape(elem[i].value);
	}
	return vals.join('&');
};

function disable_submit(el){
	el.disabled = 1;
	el.className = 'submitoff';	
	tform = el.form;
	var thisname  = el.name;
	el.name = thisname+'_temp';
	var inp = document.createElement("INPUT");
	inp.type = "hidden";
	inp.value = "Sub";
	inp.name = thisname;
	tform.appendChild(inp);
	tform.submit();
};

// For showing the search form on page
function showsearch(){
	
	
	$("#showsearch").slideToggle("500");
	setTimeout(function() {
        $(".card2").toggleClass("search_");
    }, 100);

	
};

// For showing the show_sorting form on page
function show_sorting(){
	
	$("#show_sorting").slideToggle("500");
	setTimeout(function() {
        $(".card2").toggleClass("sorting_");
    }, 100);
	
};


$(document).ready(function() {
	
	$(".altrowstable tr").mouseover(function(){
		var old_class = $(this).attr("class");
		//alert(old_class);
		$(this).attr("class", "tr_bgcolor");
	
		$(this).mouseout(function(){
			$(this).attr("class", old_class);
		});
	});
	
	// MENU Hiding / Showing for screens
	var shown=false;
	$('#pull').on('click', function(e) {
		shown=$('#left-menu').is(':visible');
		e.preventDefault();
		$('#left-menu').toggle('1000');
		if(!shown){
			$('#pull').animate({
				left: '250px'
			},'1000');
		}else{
			$('#pull').animate({
				left: '0px'
			},'1000');
		}

	});

	$(window).resize(function(){
		var w = $(window).width();
		if(w >= 700 && $('#left-menu').is(':hidden')){
			$('#left-menu').toggle('1000');
		}
	});
	
	
	// Allow only numbers in a HTML Textbox
	$(".numbersonly").keydown(function(event){
		
		if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 
			|| event.keyCode == 27 || event.keyCode == 13 
			|| (event.keyCode == 65 && event.ctrlKey === true) 
			|| (event.keyCode >= 35 && event.keyCode <= 39)){
				return;
		}else {
			// If its not a number stop the keypress
			if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
				event.preventDefault(); 
			}   
		}
	});
	
	try{
	
		$('.select_all').on('change', function(){
			var checkAll = $('.select_all');
			var checkboxes = $('.ios');
	
			var is_checked = $_('select_all').checked;
			
			checkboxes.each(function(){
				
				if(is_checked){
					$(this).prop("checked", true);
				}else{
					$(this).prop("checked", false);
				}
			});
		});
	}catch(e){}

	show_tooltip();

});

// The page jumper box
function pagejump(ele, len, urlto, call_func){
	
	var offset = $(ele).offset();
	offset.left -= 5;
	offset.top += ele.offsetHeight + 2;
	//alert(offset.top+" - "+offset.left);
	call_func = call_func || 'loadpage';
	
	// Is there an ONSHOW function
	var isit_fn = window[call_func];
	
	var pageJumpTimer;
	
	$(ele).mouseout(function() {		
		pageJumpTimer = setTimeout("$('#pagejump').hide();", 100);
	});
	
	$("#pagejump :text").val('');
	
	$("#pagejump form").submit(function(event) {
		event.stopImmediatePropagation();
		val = $("#pagejump :text").val();
		val = parseInt(val);
		if(val > 0){
			
			if(typeof isit_fn === 'function'){
				isit_fn(urlto+(val-1));
			}else{
				loadpage(urlto+(val-1));
			}
			
			$('#pagejump').hide();
		}
		return false;	
	});
	
	$("#pagejump").mouseout(function() {		
		pageJumpTimer = setTimeout("$('#pagejump').hide();", 100);
	});
	
	$("#pagejump").mouseover(function() {		
		clearTimeout(pageJumpTimer);
	});
	
	// Set the offset
	$_('pagejump').style.left=Math.ceil(offset.left)+"px";
	$_('pagejump').style.top=Math.ceil(offset.top)+"px";
	
	$("#pagejump").show();
	return false;
};

// Builds the page links
function pageLinks(id, urlto, pages, call_func){
	
	$("#"+id+" .pagination-top").hide();
	$("#"+id+" .pagination-bottom").hide();
	
	pageInfo = pages || (typeof(N["page"]) == "undefined" ? false : N["page"]);
	call_func = call_func || 'loadpage';
	
	// Is there a pagination ?
	if(!pageInfo){
		return;
	}
	
	// Make the URL
	var urlto = (urlto || windowHASH()).toString();
	var final = urlto.replace(/(&?)start\=(\d{1,4})/gi,"")+"&page=";
	
	// Number of Pages
	var $pages = Math.ceil(pageInfo["maxNum"] / pageInfo["len"]);
	
	// Current Page
	var $pg = (pageInfo["start"]/pageInfo["len"]) + 1;
	
	var $_pages = new Object();
	
	if($pages > 1){
		
		// Show th Back Links if required
		if($pg != 1){
			$_pages['&lt;&lt;'] = 1;
			$_pages['&lt;'] = ($pg - 1);
		}
		
		for($i = ($pg - 4); $i < $pg; $i++){
			if($i >= 1){
				$_pages["i"+$i] = $i;
			}
		}
		
		$_pages["i"+$pg] = $pg;
				
		for($i = ($pg + 1); $i <= ($pg + 4); $i++){
			if($i <= $pages){
				$_pages["i"+$i] = $i;
			}
		}
		
		if($pg != $pages){
			$_pages['&gt;'] = ($pg + 1);
			$_pages['&gt;&gt;'] = $pages;
		}
		
	}
	
	// Make the table
	var str = '<div class="w-100"><table class="cbgbor" cellspacing="1" cellpadding="0" border="0" align="right">'+
'<tr>'+
'<td class="pagelinks"><a href="javascript:void(0)" onclick="'+call_func+'(\''+final+1+'\');" > '+ page_page +$pg+ page_of +$pages+'</a></td>';

	for(x in $_pages){
		var i = x.substring(0, 1) == "i" ? x.substring(1) : x;
		str += '<td class="' + (i == $pg ? 'activepage' : 'pagelinks' ) + '"><a href="javascript:void(0);" onclick="'+call_func+'(\''+final+$_pages[x]+'\');">'+i+'</a></td>';
	};
	
	str += '</tr>'+
'</table></div>';
	
	$("#"+id+" .pagination-top").html(str);
	$("#"+id+" .pagination-top").show();
	
	$("#"+id+" .pagination-bottom").html(str);
	$("#"+id+" .pagination-bottom").show();
	return false;
};

// Builds the page links
function pageLinks_search(id, pageInfo, call_func, keyword){

	$("#"+id+" .pagination-top").hide();
	$("#"+id+" .pagination-bottom").hide();

	// Is there a pagination ?
	if(!pageInfo){
		return;
	}

	// Number of Pages
	var $pages = Math.ceil(pageInfo["maxNum"] / pageInfo["len"]);

	// Current Page
	var $pg = (pageInfo["start"]/pageInfo["len"]) + 1;

	var $_pages = new Object();

	if($pages > 1){

		// Show th Back Links if required
		if($pg != 1){
			$_pages['&lt;&lt;'] = 1;
			$_pages['&lt;'] = ($pg - 1);
		}

		for($i = ($pg - 4); $i < $pg; $i++){
			if($i >= 1){
				$_pages["i"+$i] = $i;
			}
		}

		$_pages["i"+$pg] = $pg;

		for($i = ($pg + 1); $i <= ($pg + 4); $i++){
			if($i <= $pages){
				$_pages["i"+$i] = $i;
			}
		}

		if($pg != $pages){
			$_pages['&gt;'] = ($pg + 1);
			$_pages['&gt;&gt;'] = $pages;
		}

	}

	// Make the table
	var str = '<nav aria-label="Page navigation example">'+
'<ul class="pagination pagination-sm m-0">'+
'<li class="page-item"><a href="javascript:void(0)"  class="page-link" >Page '+$pg+' of '+$pages+'</a></li>';

	for(x in $_pages){
		var i = x.substring(0, 1) == "i" ? x.substring(1) : x;
		str += '<li class="' + (i == $pg ? 'page-item active' : 'page-item' ) + '"><a href="javascript:'+call_func+'(\''+keyword+'\',1,'+$_pages[x]+')" class="page-link">'+i+'</a></li>';
	};

	str += '</ul>'+
'</nav>';

	$("#"+id+" .pagination-top").html(str);
	$("#"+id+" .pagination-top").show();

	$("#"+id+" .pagination-bottom").html(str);
	$("#"+id+" .pagination-bottom").show();

};

//Get parameter from URL by name
function getParameterByName(name, inHash) {
	
	inHash = inHash || 0;
	name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
	var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
		results = regex.exec(inHash ? "?"+windowHASH() : location.search);
	return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};

function is_checked(id){
	
	if($("#"+ id).is(":checked")){
		return true;
	}else{
		return false;
	}
};

// PHP equivalent empty()
function empty(mixed_var) {

  var undef, key, i, len;
  var emptyValues = [undef, null, false, 0, '', '0'];

  for (i = 0, len = emptyValues.length; i < len; i++) {
	if (mixed_var === emptyValues[i]) {
	  return true;
	}
  }

  if (typeof mixed_var === 'object') {
	for (key in mixed_var) {
	  // TODO: should we check for own properties only?
	  //if (mixed_var.hasOwnProperty(key)) {
	  return false;
	  //}
	}
	return true;
  }

  return false;
}

function multiselect(id, num){
	try{
		for(i=0; i < num; i++) {
			$_(id).options[i].selected = true;
		}
	}catch(e){}
};

//field function to get/set input values of any type of input
(function () {
	$.fn.field = function (inputName, value){
		if (typeof inputName !== "string") return false;
		var $inputElement = $(this).find("[name='" + inputName + "']");
		// var $inputElement = $(this); //direct mapping with no form context
		
		if (typeof value === "undefined" && $inputElement.length >= 1){
			switch ($inputElement.prop("type")){
				case "checkbox":
					return $inputElement.is(":checked");
					break;
				case "radio":
					var result;
					$inputElement.each(function (i, val) {
						if ($(this).is(":checked")) result = $(this).val()
					});
					return result;
					break;
				default:
					return $inputElement.val();
					break;
			}
		}else{
			switch ($inputElement.prop("type")){
				case "checkbox":
					$inputElement.prop("checked", !empty(value) ? 1 : 0);
					break;
				case "radio":
					$inputElement.each(function (i) {
						if ($(this).val() == value) $(this).attr({
							checked: true
						})
					});
					break;
				/*case 'select-multiple':
					$.each(value, function( ind, val ){
						
						$(this).attr("selected", false);
						if($(this).val() == val){
							$(this).attr("selected", "selected");
						}
					});
					break;*/
				case undefined:
					$(this).append('');
					break;
				default:
					$inputElement.val(value);
					break;
			}
			return $inputElement;
		}
	}
})();

/* Monitor page related code*/

// Format the date
function nDate(timestamp, format){
	format = format || "";
	if(!timestamp){
		return "<i>Never</i>";
	}
	var d = new Date(timestamp * 1000);
	
	if(format == ""){
		var ret = d.toUTCString();
		return ret.replace(" GMT", "");
	}
	
	var ret = format;
	ret = ret.replace("Y", d.getUTCFullYear());
	ret = ret.replace("m", (d.getUTCMonth()+1).toString().pad(2, "0"));
	ret = ret.replace("d", d.getUTCDate().toString().pad(2, "0"));
	ret = ret.replace("H", d.getUTCHours().toString().pad(2, "0"));
	ret = ret.replace("i", d.getUTCMinutes().toString().pad(2, "0"));
	ret = ret.replace("s", d.getUTCSeconds().toString().pad(2, "0"));
	return ret;
};

// Show tooltip for graphs
function showTooltip(x, y, contents) {
	$('<div id="tooltip">' + contents + '</div>').css( {
		position: "absolute",
		display: "none",
		top: y ,
		left: x + 20,
		border: "1px solid #CCCCCC",
		padding: "2px",
		color: "var(--black)",
		"background-color": "var(--white)",
		opacity: 0.80
	}).appendTo("body").fadeIn(200);
};

String.prototype.pad = function(l, s, t){
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
		+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
		+ this + s.substr(0, l - t) : this;
};

// progress bar function
function makeProgress(target, start, stop, steps, hide_status_text){
	
	hide_status_text = hide_status_text || 0;

	if(isNaN(stop)){
		stop = 0;
	}
	
	var step = (stop - start)/steps;
	
	if(step < 0){
		step = 0;
	}
	
	var increment = function(){
		
		var val = target.progressbar("value");
		var increase = val + step;
		var parsed_increase = parseInt(val + Math.round(step));
		
		if(parsed_increase > stop){
			parsed_increase = stop;
		}
		
		
		if(empty(hide_status_text)){
			if(parsed_increase < 100){
				$("#pbar").html(progress_update + " (" + parsed_increase + "%) ");
			}else{
				$("#pbar").html(progress_update + " (100%) ");
			}
		}
		
		target.progressbar("option", "value", increase);
		
		if (increase < stop) {
			setTimeout(increment,1000);
		}
	};
	
	increment();
};

function get_progress(current_act){

	//current_act = current_act || "";
	var url_path = window.location.origin+window.location.pathname+"?act=";
	
	// We have to set it zero to complete the progress normally
	hide_status_text = 0;
	
	if(task_status == "-1"){
		setTimeout(function(){
			$.ajax({type: "GET",
				url: url_path + current_act + "&jsnohf=1",
				data: "error=1&actid="+actid,
				success: function(response){
					
					if(current_act == "vs"){
						action_by_id();
						//$("#softcontent").html(response);
					}else{
						var parsed_HTML = $(response);
						var error_box = parsed_HTML.filter("#error_box").add(parsed_HTML.find("#error_box"));
						if(current_act == "addvs"){
							$("#form-container").html(error_box);
						}else if(current_act == "rebuild"){
							var url = window.location.href;
							// If the current act is managevs
							if(url.match(/act=managevps/)){
								$("#rebuild_error_row").show();
								$("#rebuild_error").html(error_box);
								$("#rebuildmodal").on("hide.bs.modal", function (e) {
									// do something...
									location.reload(true);
								});
							}else{
								$("#form-container").prepend(error_box);
							}
						}else{
							$("#form-container").prepend(error_box);
						}
						$("#form-container").show();
						$("#progress-cont").hide();
						if(current_act == "migrate" || current_act == "clone" || current_act == "migrate_disk"){
							$("#running").hide();
						}
						if(current_act == "letsencrypt"){
							showalert(error_box.html() ,"1");
							if(!empty(dos)){
								for(x in dos){
									$("#"+dos[x]+"_id").removeAttr("disabled");
								}
							}
						}
					}
					
					if(current_act == "enable_rescuevs" || current_act == "disable_rescuevs") {
						rescuedonefunc(current_act, 1);
					}
					
					// Override status, once error processing is completed
					task_status = '';
				}
			});
		}, 1000);
	
	}else if(progress == 100){
		
		$("#pbar").html(progress_update + " (100%) ");
		$("#progressbar").progressbar("option", "value", 100);
		if(current_act == "letsencrypt"){
			setTimeout(donecert(), 3000);
			return;
		}

		setTimeout(function(){
			$.ajax({type: "GET",
				url: url_path+current_act+"&jsnohf=1",
				data:"done=1&actid="+actid,
				success:function(response){

					if(current_act == "vs"){
						//alert("progress 100 : "+ delvpsid)
						done_vps_list.push(delvpsid);
						action_by_id();
					}
					
					if(current_act == "migrate" || current_act == "clone" || current_act == "migrate_disk"){
					
						donefunc(1);
					}
					
					if(current_act == "createtemplate"){
						changeplan();
						showalert(response, '', true);
						$("#progress_onload").hide();
						$("#form-container").show();
					}

					if(current_act == "updates"){
						var header = $('#softcontent').html();
						$("#softcontent").html(header+response);
					}


					if(current_act == "rebuild"){
						let tmp_rootpass = newvs_rootpass;
						var url = window.location.href;				
						
						// If the current act is managevs
						if(url.match(/act=managevps/)){         
							$("#rebuild_content").html(response);
							$("#newvs_rootpass").html(newvs_rootpass);
							$("#rebuildmodal").on("hide.bs.modal", function (e) {
								// do something...
								location.reload(true);
							});
							return;
						}

						var header = $('#softcontent').html();

						$("#softcontent").html(header+response);
						$("#newvs_rootpass").html(tmp_rootpass);

					}

					
					
					if(current_act == "addvs"){
						let tmp_rootpass = newvs_rootpass;
						let tmp_vncpass = newvs_vncpass;

						if(ubc_redirect > 0){
							var header = $('#softcontent').html();
							$("#softcontent").html(header+response);
							setTimeout(function(){
								window.location  = url_path+"ubc&vpsid="+vpsid;
							}, 1000);
						}else{
							var header = $('#softcontent').html();
							$("#softcontent").html(header+response);
							$("#newvs_rootpass").html(tmp_rootpass);
							if(!empty(tmp_vncpass)){
								$("#newvs_vncpass").html(tmp_vncpass);
							}
						}
					}
					
					if(current_act == "enable_rescuevs" || current_act == "disable_rescuevs"){
						rescuedonefunc(current_act);
					}
					
				}
			});
		}, 1000);
	}else{
		
		$.ajax({
			type: "GET",
			url: url_path+"tasks",
			data:"api=json&actid="+actid,
			dataType : "json",
			success:function(response){
				var tasks = response.tasks;
				task_status = tasks[actid]["status"];
				progress = tasks[actid]["progress"];
				progress_update = tasks[actid]["status_txt"];
				vpsid = tasks[actid]["vpsid"];
				
				// We have to create the table in case of migrate and clone (make_mig_table is in migrate_theme)
				if(tasks[actid]["action"] == "migrate2" || tasks[actid]["action"] == "clone2" || tasks[actid]["action"] == "migrate_disk2"){
					hide_status_text = 1;
					make_mig_table("#pbar", tasks[actid]["status_txt"]);
				}
				
				makeProgress($("#progressbar"), $("#progressbar").progressbar("value"), progress, 20, hide_status_text);
				
				setTimeout(function(){
					get_progress(current_act);
				}, 1000);
			}
		});
	}
};

//load progress bar
function progress_onload(is_vs){
	
	is_vs = is_vs || 0;
	
	var for_vs = "";
	if(is_vs == 1){
		for_vs = "<div style='font-size:14px;text-align:center;' id='pbar_id'></div>";
	}
	
	document.getElementById("progress_onload").innerHTML = "<div style='display:none;' id='progress-cont'><br/><br/><center><div style='font-size:18px;text-align:center;' id='pbar'>0%</div>"+for_vs+"</center><br /><center><div style='max-width:600px;width:100%;height:18px;' id='progressbar'></div></center><br/><center>"+pbar_notice+" "+pbar_tip+"</center></div>";
};

function showalert(msg='',type='',callback, actid=''){

	gettaskscount();

	$(".confirm").css("display","none");
	$(".ok").css("display","flex");
	$("#alert-modal .modal-footer button").css("display","block"); 
	$("#alert-modal .modal-title i").removeClass("fa-times fa-exclamation");
	$("#alert-modal .modal-title i").addClass("fa-check");
	$("#alert-modal .modal-title.icon-box").removeClass("bg-danger bg-warning");
	$("#alert-modal .modal-title.icon-box").addClass("bg-success");
	$("#alert-modal .modal-title #success").css("display","inline");
	$("#alert-modal .modal-title #error").css("display","none");
	$("#alert-modal .modal-title #warning").css("display","none");
	$("#alert-modal .modal-title #confirmt").css("display","none");

	//error	
	if(type=="1"){
		$("#alert-modal .modal-title i").removeClass("fa-check fa-exclamation");
		$("#alert-modal .modal-title i").addClass("fa-times");
		$("#alert-modal .modal-title.icon-box").removeClass("bg-success bg-warning");
		$("#alert-modal .modal-title.icon-box").addClass("bg-danger");
		$("#alert-modal .modal-title #success").css("display","none");
		$("#alert-modal .modal-title #error").css("display","inline");
	}
	//warning
	if(type=="2"){
		$("#alert-modal .modal-title i").removeClass("fa-check fa-times");
		$("#alert-modal .modal-title i").addClass("fa-exclamation");
		$("#alert-modal .modal-title.icon-box").removeClass("bg-danger bg-success");
		$("#alert-modal .modal-title.icon-box").addClass("bg-warning");
		$("#alert-modal .modal-title #success").css("display","none");
		$("#alert-modal .modal-title #warning").css("display","inline");
		actid = '';
	}
	//confirm
	if(type=="3" || type=="4"){

		if(type=="3"){
			$("#alert-modal .modal-title i").removeClass("fa-check fa-times");
			$("#alert-modal .modal-title i").addClass("fa-exclamation");
			$("#alert-modal .modal-title.icon-box").removeClass("bg-danger bg-success");
			$("#alert-modal .modal-title.icon-box").addClass("bg-warning");
		}

		if(type=="4"){
			$("#alert-modal .modal-title i").removeClass("fa-check fa-exclamation");
			$("#alert-modal .modal-title i").addClass("fa-times");
			$("#alert-modal .modal-title.icon-box").removeClass("bg-warning bg-success");
			$("#alert-modal .modal-title.icon-box").addClass("bg-danger");
		}

		$("#alert-modal .modal-title #success").css("display","none");
		$("#alert-modal .modal-title #confirmt").css("display","inline");
		$("#alert-modal .modal-footer .ok").css("display","none");
		$(".confirm").css("display","flex");
		$("#confirm").show();

		$("#confirm").off().on("click", function(){
			setTimeout(() => {callback(true)}, 200);;
			$("#alert-modal").modal('hide');
		});
		
		$("#alert-modal .modal-footer #cancel").off().on("click", function(){
			callback(false);
			$("#alert-modal").modal('hide');
		});

		$("#alert-modal .modal-header .btn-close").off().on("click", function(){
            		callback(false);
			$("#alert-modal").modal('hide');
		});

		actid = '';
	}

	if(Array.isArray(msg)){
		let restruct_msg = msg.join("<br>");
		msg = restruct_msg;
	}

	$("#alert-modal .modal-body").html(msg);
	
	if(!empty(actid)){
		$("#alert-modal .modal-body").append('<br><a href="javascript:void(0)" onclick="loadlogs('+actid+');">show logs</a>');
	}
	
	$("#alert-modal").modal();
	
	$('#alert-modal').on('shown.bs.modal', function() {
		$("#alert-modal .modal-footer button").focus();
	});
}

// Function to show LOGS if any error occurs
function loadlogs(actid){
	
	actid = actid || 0;
	var url_path = window.location.origin+window.location.pathname+"?act=";
	$.ajax({
			
		url: url_path+"tasks&api=json",
		data: "show_logs="+actid,
		dataType : "json",
		method : "post",
		success:function(data){
			
			logs_tab_head = "";
			logs_tab_data = "";
			var j = 0;
			active = "";
			active_div = "";
			
			common_logs = data["logs_data"]["common_logs"] || "";
			if(typeof(data["logs_data"]["logs"]) === "object"){
				logs_tab_head += '<ul class="nav nav-tabs nav-justified" role="tablist">';
				logs_tab_data += '<div class="tab-content" id="myTabContent">';
				$.each(data["logs_data"]["logs"], function(i, item){
					
					if(j == 0){
						active = "active";
						active_div = "show";
					}else{
						active = "";
						active_div = "";
					}
					logs_tab_head += "<li class=\"nav-item\"><a  class=\"nav-link "+active+"\" data-toggle=\"tab\" role=\"tab\" href=\"#"+i+"_tab\">"+i+"</a></li>";
					logs_tab_data += "<div class=\"tab-pane "+active+" "+active_div+"\" id=\""+i+"_tab\"><pre style=\"max-height: 450px;padding-left:20px;\" >"+item+"</pre></div>";
					j++;
				});
				logs_tab_head += '</ul>';
				logs_tab_data += '</div>';
				
				common_logs_html = "";
				if(common_logs != ""){
					common_logs_html = "<div class=\"notice\"><b>NOTE : </b> &nbsp; "+data["l_common_logs"]+"</div>";
				}
				
				logs_html = "<h6 class=\"p-2\">"+logs_tab_head+"</h6><div>"+logs_tab_data+"</div>"+common_logs_html;
				
			}else{
				logs_html = "<div class=\"log_div\">"+data["logs_data"]["logs"]+"</div>";				
			}		
			$("#alert-modal").modal("hide");
			$("#logs_modal").modal("show");
			$("#logs_modal_body").css('padding', '3px');
			$("#logs_modal_body").html(logs_html);
			
			///////////////////////////////////////////////////////////////
			
			//header click event
			task_header();
			
			//button click event
			virt_load_task();
			
			//output button click event
			command_output();
			
			/////////////////////////////////////////////////////////////
			
		}
	});

}

function command_output(){
	$('.command_output').each(function(){
		$(this).unbind().click(function(){
			var id = $(this).attr('data-target');
			$(id).slideToggle();
			$(this).text(function(i,old){
				return (old == show_l ? hide_l : show_l);
			});
		});
	});
}

function task_header(){
		
	//default header
	$(".vexec_default_header").each(function(){
		//if next element is group task then we add vexec_task_header class
		if($(this).next('.grouped_task').length == 1){
			$(this).removeClass('vexec_default_header');
			$(this).addClass('vexec_task_header');
		}
		if(empty($(this).text())){
			$(this).remove();
		}
	});
	
	//toggle header 
	$(".vexec_task_header").each(function() {
		//if next element is group task then we add span style to the div
		if($(this).next('.grouped_task').length == 1 && $(this).find('.sign').length != 1 && $(this).find('.shw_txt').length != 1){
			$(this).css('cursor','pointer');
			$(this).prepend('<span class="sign" style="">+</span>');
			$(this).append('<span style="margin-left:20px;">(<span style="display: inline-block;" class="shw_txt">'+show_more_l+'</span>)</span>');
			$(this).next('.grouped_task').css('display','none');
		}
		
		if(empty($(this).text())){
			$(this).remove();
		}
	});
	
	$('.vexec_task_header').unbind().click(function() {
		//Get data from the button 
		var actid = $(this).next('.grouped_task').find('.virt-load-task').data('actid');
		var vpsid = $(this).next('.grouped_task').find('.virt-load-task').data('vpsid');
		var serid = $(this).next('.grouped_task').find('.virt-load-task').data('serid');
		var slaveactid = $(this).next('.grouped_task').find('.virt-load-task').data('slaveactid');
		var next_action = $(this).next('.grouped_task').find('.virt-load-task').data('op');
		
		actid = actid || '';
		vpsid = vpsid || '';
		serid = serid || '';
		slaveactid = slaveactid || '';
		next_action = next_action || '';

		if(empty(actid)){
			actid = slaveactid;
		}
		
		$(this).next('.grouped_task').slideToggle();
		
		//Perform ajax only if we get data-vpsid from the button inside grouped_task
		if(!empty($(this).next('.grouped_task').find('.virt-load-task').data('vpsid'))){
			$(this).next('.grouped_task').find('.virt-load-task').css('display','none');
			
			//only add the div if it is not present
			if($('#'+next_action+actid).length != 1){
				$(this).next('.grouped_task').find('button').after('<div id="'+next_action+actid+'"></div>');
			}
			
			var url_path = window.location.origin+window.location.pathname+"?act=";
			
			//perform ajax on when div when user want to see the div and when he clicks again to hide dont perform ajax.
			if($(this).find('.shw_txt').text() == show_more_l){
				$.ajax({
					url: url_path+'tasks&jsnohf=1',
					data: 'find_actid='+actid+'&find_action='+next_action+'&find_vps='+vpsid+'&serid='+serid+'&slaveactid='+slaveactid,
					method : 'post',
					beforeSend:function(){
						//By default show loading.
						$('#'+next_action+actid).html('<center><img src=\'../themes/default/images/admin/vpsloading.gif\' width="20px"/><center>');
					},
					success:function(data){
						$('#'+next_action+actid).html(data);
						$('#'+next_action+actid+' button').unbind().click(function(){
							$(this).text(function(i,old){
								return (old == show_l ? hide_l : show_l);
							});
						});
						virt_load_task();
						task_header();
						command_output();
					}
				});
			}
		}
		
		$(this).find('.sign').text(function(i,old){
			return (old == '+' ? '-' : '+');
		});
		$(this).find('.shw_txt').text(function(i,old){
			return (old == show_more_l ? show_less_l : show_more_l);
		});
	});
}

function virt_load_task(){
	$('.virt-load-task').unbind().click(function(){
		//Get data from the button
		var actid = $(this).data('actid');
		var vpsid = $(this).data('vpsid');
		var next_action = $(this).data('op');
		var serid = $(this).data('serid');
		serid = serid || '';
		
		//Add onclick attr so that div can be toggled
		$(this).attr('onclick','_slidetoggle(this,\''+next_action+actid+'\',\''+show_l+'\',\''+hide_l+'\');');
		
		//only add the div if it is not present
		if($('#'+next_action+actid).length != 1){
			//On first click we change text to hide
			$(this).text(hide_l);
			$(this).after('<div id="'+next_action+actid+'" style="display: block;border: 1px solid#868686;padding: 3px;background-color: #f7ffee;"></div>');
		}
		// show_l and hide_l is defined in hf_theme, its language so we will need to define in variable
		var url_path = window.location.origin+window.location.pathname+"?act=";
		$.ajax({
			url: url_path+'tasks&jsnohf=1',
			data: 'find_actid='+actid+'&find_action='+next_action+'&find_vps='+vpsid+'&serid='+serid,
			method : 'post',
			success:function(data){
				$('#'+next_action+actid).html(data);
				
				//if the button inside div have attr data-vpsid do not add onclick event.
				$('#'+next_action+actid+' button').each(function(){
					if($(this).data('vpsid') == ''){
						$(this).unbind().click(function(){
							$(this).text(function(i,old){
								return (old == show_l ? hide_l : show_l);
							});
						});
					}
				});
				// recursive call to again register the click events
				virt_load_task();
				task_header();
				command_output();
			}
		});
	});
}

//Toggle div 
function _slidetoggle(ele, id, show_l, hide_l){
	if(($('#'+id).css('display') === 'block')){
		if(!empty(show_l)) $(ele).text(show_l);
		$('#'+id).slideUp();
	}else if(($('#'+id).css('display') === 'none')){
		if(!empty(hide_l)) $(ele).text(hide_l);
		$('#'+id).slideDown();	
	}
}

// Password strentgh related functions
function passwordStrength(password1) {
	
	var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score = 0;
	var pass_strength = Array();
	//password < 4
	if ( password1.length < 4 ){
		score = 9;
		pass_strength = [shortPass, parseInt(score)];
		return pass_strength;
	}

	var strength = 0;
	
	if (password1.length > 7) strength += 1.5;
			
	//If password contains both lower and uppercase characters, increase strength value.
	if (password1.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  strength += 1.5;	
	
	//If it has numbers and characters, increase strength value.
	if (password1.match(/([a-zA-Z])/) && password1.match(/([0-9])/))  strength += 1.5;	
	
	//If it has one special character, increase strength value.
	if (password1.match(/([!,%,&,@,#,$,^,*,?,_,~])/) && password1.match(/([a-zA-Z])/))  strength += 1.5;
	
	//if it has two special characters, increase strength value.
	if (password1.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/) && password1.match(/([a-zA-Z])/)) strength += 1.5;
	
	//If value is less than 2
	if( strength < 2 ){
		pass_strength = [badPass, parseInt((strength/5)*100)];	
		return pass_strength;	
	}
	
	if (strength == 2 ){
		pass_strength = [goodPass, parseInt((strength/5)*100)];	
		return pass_strength;	
	}else{
		pass_strength = [strongPass, parseInt((strength/5)*100)];
		return pass_strength;	
	}
}


function check_pass_strength(id) {
	
	var pass = $("#"+id).val();
	var strength = Array();
	
	$("#"+id+"_pass-strength-result").removeClass("short bad good strong");
	
	if (!pass) {
		display_pass_strength("strength_indicator", 0, id);
		return;
	}
	
	try{
		
		strength = passwordStrength(pass);
		
		if(strength[1] > 100) strength[1] = 100;
		
		switch(strength[0]){
				case 1:
				score  = "bad";// For short password 
				display_pass_strength(score, strength[1], id);
				break;
			case 2:
				score = "bad"; // For bad password 
				display_pass_strength(score, strength[1], id);
				break;
			case 3:
				score = "good";// For good password 
				display_pass_strength(score, strength[1], id);
				break;
			case 4:	 		 
				score = "strong";// For Strong password 
				display_pass_strength(score, strength[1], id);
				break;
		}
		
	}catch(e){}
}

function display_pass_strength(score, per, id){
	
	if(typeof per == "undefined") per = 0;
	
	$("#"+id+"_pass-strength-result").addClass(score).html(lang[score] + " ("+per+"/100)");
}

function handle_capping(){
	$("#speed_cap_down").prop("min", 0);
	$("#speed_cap_up").prop("min", 0);
	
	var band_val = $("#band").val();
	if(empty(band_val)){
		band_val = $("#bandwidth").val();
	}
	
	if(!empty(band_val) && !$("#band_suspend").prop("checked")){
		$("#speed_cap_limit").css("display", "block");
		if($("#network_speed").val() > 0){
			$("#speed_cap_down").prop("max", $("#network_speed").val());
			$("#speed_cap_up").prop("max", $("#network_speed").val());
		}
		if($("#upload_speed").val() > 0){
			$("#speed_cap_up").prop("max", $("#upload_speed").val());
		}
	}else{
		$("#speed_cap_limit").css("display", "none");
		$("#speed_cap_down").val(0);
		$("#speed_cap_up").val(0);
	}
}	
// Speed KBps select options
function fillspeedkBps(){
	var str = "";
	str += '<option value="0" selected="selected">'+lang_no_limit+'</option>';
	for(var i = 1; i <= 10; i++){
		str += '<option value="'+(i*128)+'">'+(i*128)+' KB/s </option>';
	}
	str += '<option value="'+(15*128)+'">'+(15*128)+' KB/s </option>';
	
	for(var i = 20; i <= 100; i += 10){
		str += '<option value="'+(i*128)+'">'+(i*128)+' KB/s </option>';
	}
	str += '<option value="'+(1000*128)+'">'+(1000*128)+' KB/s </option>';
	str += '<option value="'+(10000*128)+'">'+(10000*128)+' KB/s </option>';
	$(".speedkBps").html(str);	
}


// Submits a FORM
function POST(obj, submitresponse){
	
	submitresponse = submitresponse || 'DOESNT_EXIST';
	
	//Loading(1); // Show the loading text
	
	obj['type'] = "POST";
	obj['dataType'] = "json";
	obj['success'] = function(data, textStatus, jqXHR) {
	
		//Loading(0); // Hide the loading text
				
		// Is there an submitresponse function
		var fn = (typeof submitresponse != 'function' ? window[submitresponse]: submitresponse);
		
		// If its there, then call it
		if(typeof fn === 'function'){
			if(fn(data) == -1){
				return;
			}
		}
		
		// Handles the responses
		handleResponseData(data, obj['extradata']);
		
	};
	
	obj['xhrFields'] = {
		withCredentials: true
	};
		
	obj['crossDomain'] = true;
	
	$.ajax(obj);
	
	return true;
	
};

function handleResponseData(data){	

	// Are there any errors ?
	if(typeof(data["error"]) != 'undefined'){
		error(data["error"]);
	}

	// Are we to show a success message ?
	if(typeof(data["done"]) != 'undefined'){
		done(data["done"]);
	}
	
};

// Shows the error
function error(er){
	
	var count = 0;
	for (k in er) count++;

	// If count is 0 then no error was there
	if(count < 1) return;
	
	var err_str = "";
	// Show the errors
	var count = 1;
	for (k in er) {
		err_str += count++ +") " + er[k] + "<br>";
	}

	showalert(err_str ,"1");
};

// Shows a success message
function done(success){

	var count = 0;
	var goto = "";
	for (k in success) count++;

	// If count is 0 then no success message was there
	if(count < 1) return;

	if(typeof(success["msg"]) != 'undefined'){
		setTimeout(function(){showalert(success["msg"])} ,200);
	}
	
};

// Creates the TABLE
function table(props, cols, data){

	var elid = props['id'];

	// Final Properties
	var fp = {"width" : '100%',
			"class" : 'table table-hover tablesorter', //shadow altrowstable gridtable
			"border" : '0',
			"cellspacing" : '1',
			"cellpadding" : '8',
			"align" : 'center',
			"tid" : ''
		};

	for (x in props){
		fp[x] = props[x];
	}

	// Create the TABLE
	var table = '<table id="'+fp["tid"]+'" border="'+fp["border"]+'" cellspacing="'+fp["cellspacing"]+'" cellpadding="'+fp["cellpadding"]+'" class="'+fp["class"]+'" align="'+fp["align"]+'" width="'+fp["width"]+'"><thead><tr>';

	// Add the headers
	for(x in cols){
		table += '<th '+(cols[x]["width"] ? 'width="'+cols[x]["width"]+'"' : '')+' '+(cols[x]["class"] ? 'class="'+cols[x]["class"]+'"' : '')+'>'+cols[x]["l"]+'</th>';
	}

	table += '</tr></thead>';

	var $i = 0; // For color

	for(d in data){
		$i++;
		table += '<tr>';

		for(x in cols){
			table += '<td '+(cols[x]["centered"] ? 'align="center"' : '')+'>'+data[d][x]+'</td>';
		}

		table += '</tr>';
	}

	table += '</table>';

	$('#'+elid).html(table);


};

// Auto select IPs from Pool if user specifies the number
function ipchoose(name="ips_int", num=0){
	var label = name;
	num = parseInt(num);
	if(name=="ipv6count"){
		label = "ipv6";
	}
	try{
		for(i=0; i < $_(label).options.length; i++) {
			if(num > 0){
				$_(label).options[i].selected = true;
				num = num - 1;
			}else{
				$_(label).options[i].selected = false;
			}
		}
	}catch(e){	}
}

function processing_symb(show){
	if(show == 1){
		$("#processing_symb").css('display','block');
	}else{
		$("#processing_symb").css('display','none');
	}
}

function uni_search(keyword, modal = 0, page = 0){
	
	// current url
	var url_path = window.location.origin+window.location.pathname;
	var res = "";
	
	// #searchdata is for modal and #search_results is for card
	var search_div = modal == 1 ? $("#searchdata") : $("#search_results"); 
	var loader = modal == 1 ? $("#searchdata_loader") : $("#loader"); 

	// make ajax call only if user entered atleast 2 letters
	if(keyword.length < 2){
		$("#search_results").fadeOut();
	}else{
		$.ajax({
			url: url_path+'?act=vs&page='+page+'&keyword='+keyword+'&adv_search=1&api=json',
			dataType : 'json',
			beforeSend: function() {
				loader.show();
				$('#searchdata_pagination').hide();
				$('.pagination-top').hide();
			},
			complete:function(){
				loader.hide();
				$('#searchdata_pagination').show();
				$('.pagination-top').show();
			},
			success:function(data){
				// Language used for universal search
				var lang_unis = data['global_search_res']['lang'];

				// search modal header will display the total number of the results.
				$("#search_header").text(l_unisear_hdr_res+" ("+data['global_search_res']['total']+") "+lang_unis['unisear_for']+" \""+keyword+"\"");

				// Result to be displayed
				var res = '';

				// Matched resources list received
				var links = data['global_search_res']['links'];
				data['global_search_res']['links'] = '';

				// Number for results
				var count = 0;

				// This variable is used to limit few results in card
				var exit_loop = false;

				// Process matched list
				for (var cat in links){
					// This variable holds resource wise result links
					var matched_arr = {};

					// This variable is used to know if we got any result after processing
					var matched_count = 0;

					// Loop through categories (like VPS, User, IP, etc)
					for(var catid in links[cat]){

						// Proccess if we got match in this category
						if(!empty(links[cat][catid]['matched_in'])){
							
							// This vairable used to hold temp index for array
							var tmpcount = 0;
							
							// Loop through resources (user, hostname, ip, vps_name etc) matched for category
							for(var match in links[cat][catid]['matched_in']){
								if(matched_arr[match] == undefined){
									matched_arr[match] = {};
								}
								if(matched_arr[match][catid] == undefined){
									matched_arr[match][catid] = {};
								}
								matched_count++;

								// Prpare links to be displayed for matches
								// Since there can be multiple IP matches in VPS, handle it correctly
								if(match == 'ips' && cat == 'vps'){
									for(ip in links[cat][catid]['matched_in'][match])
									matched_arr[match][catid][tmpcount++] = '<b><a href="'+links[cat][catid]['link']+'" >'+links[cat][catid]['label']+'</a></b>'+(match == 'hostname' || cat == 'ips' || cat == 'user'? '' : ' <span>('+links[cat][catid]['matched_in'][match][ip]+')</span>');
								
								// For rest resource matches
								}else{
									if(match == 'ips' && !empty(links[cat][catid]['link']['ips'])){
										matched_arr[match][catid][tmpcount++] = '<b><a href="'+links[cat][catid]['link']['ips']+'" >'+links[cat][catid]['label']['ips']+'</a>&nbsp;&nbsp;&nbsp;<a href="'+links[cat][catid]['link']['ippool']+'" >('+links[cat][catid]['label']['ippool']+')</a></b>'+(match == 'hostname' || cat == 'ips' || cat == 'user' || cat == 'free_ips' ?  '' : ' <span>('+links[cat][catid]['matched_in'][match]+')</span>');
									}else if(match != 'ippool' && empty(links[cat][catid]['link']['ippool'])){
										matched_arr[match][catid][tmpcount++] = '<b><a href="'+links[cat][catid]['link']+'" >'+links[cat][catid]['label']+'</a></b>'+(match == 'hostname' || cat == 'storage' || cat == 'ips' || cat == 'user' || cat == 'free_ips' ?  '' : ' <span>('+links[cat][catid]['matched_in'][match]+')</span>');
									}
								}
							}
						}
					}
					
					// This vairable holds resource wise matched results
					var res2 = {};

					if(matched_count > 0){
						matched_count = 0;

						for(var match in matched_arr){
							if(res2[match] == undefined && match != 'ippool'){
								res2[match] = '<div class="result_header"><b>'+lang_unis['unisear_matched']+' '+lang_unis['unisear_'+match]+' '+lang_unis['unisear_in']+' '+lang_unis['unisear_'+cat]+' '+lang_unis['unisear_list']+'</b></div>';
								matched_count++;
							}

							for(var catid in matched_arr[match]){
								for(var mres in matched_arr[match][catid]){
									
									// show only 4 results in the card and make a link to see all the results.
									if(count >= 4 && modal == 0){
										exit_loop = true;
										break;
									}
									res2[match] += "<div class='search_link'><span class='uni_search_cat'>"+lang_unis['unisear_'+cat]+" </span>"+matched_arr[match][catid][mres]+"</div>";
									count++;
									
								}

								if(exit_loop){
									break;
								}
							}

							if(exit_loop){
								break;
							}
						}
						
						// Merge matched result, to be displayed
						if(matched_count > 0){
							for(match in res2){
								res += res2[match];
							}
						}
					}

					// If card was displayed, display link to show modal of result
					if(exit_loop){
						res += '<hr><a href="javascript:void(0)" onclick="uni_search(\''+keyword+'\',1)" style="padding-left:4px;">'+l_unisear_show_all+' '+data['global_search_res']['total']+' '+l_unisear_res+'</a>';			
						break;
					}
				}

				// res is not empty then only put the res inside the search_div.
				if(res != ""){
					search_div.html(res);
				}else{
					// reset the pagination for empty res.
					var pagination = new Array();
					pagination['start'] = 0;
					pagination['len'] = 50;
					pagination['maxNum'] = 0;
					pageLinks_search("searchdata_pagination", pagination, "uni_search", "");
					search_div.html("<div class='search_no_res'><b>"+l_unisear_no_res+"</b></div>");
				}

				if(modal == 1){
					var pglnks_data = data['global_search_res']['pagelinks_data'];
					// create pagination.
					pageLinks_search(pglnks_data['id'], pglnks_data['pageInfo'], pglnks_data['call_func'], pglnks_data['keyword']);
					$("#search_results").fadeOut();
					$("#search_modal").modal();
				}else{
					$("#search_results").fadeIn();
				}
			}
		});	
	}
	
	$(document).click(function() {
		// if clicked outside the search input, hide search card.
		if (!$("#uni_search").is(':focus')) {
			$("#search_results").fadeOut();
		}
	});
}

$(document).ready(function(){
	// if clicked on the search input
	$("#uni_search").on('keypress',function() {
		var keycode = (event.keyCode ? event.keyCode : event.which);
		// 13 is keycode for enter key of keyboard
		if(keycode == '13'){
			$("#uni_search").blur();
			keyword = $("#uni_search").val();
			// display the result in the modal.
			if(keyword.length >= 2){
				uni_search(keyword, 1);
				$("#search_modal").modal();
			}
		}
		$("#search_modal").on("hidden.bs.modal", function () {
			$("#search_results").fadeIn();
			$("#searchdata").empty();
		});
	});
});

function animate_task(title, toast_msg = ""){
	var title = title || '';

	if(empty(title)) return false;
	show_toast(title, toast_msg);
}

function del_dns_div(ele){
	$("."+ele).each(function(){
		$(this).unbind("click");
		$(this).click(function(){
			var parent = $(this).parent();
			var parent2 = $(this).parent().parent();
			parent.remove();
			parent2.remove();
		});
	});
}

function show_tooltip(delay_show, delay_hide){
	 var delay_show = delay_show || 200;
	 var delay_hide = delay_hide || 50;
	$("[tooltip]").tooltip({ 
		trigger: "manual, click" , 
		html: true, 
		animation:true,
		title: function(ele){
			return '<div class="w-100 text-left tooltip-div">'+$(this).attr("tooltip")+'</div>';
		}
	}).on("mouseenter", function () {
		var _this = this;
		setTimeout(function(){
			if ($(_this).is(":hover")) {
				$(_this).tooltip("show");
			}
		}, delay_show);
	}).on("mouseleave", function () {
		var _this = this;
		setTimeout(function () {
			$('.tooltip').each(function(){
				is_hover = 0;
				$(this).hover(function(){
					is_hover = 1;
					$(this).on("mouseleave", function(){
						$(this).tooltip("hide");
					});
				});
				if (!$(this).is(":hover") && !$(_this).is(":hover")) {
					$(this).tooltip("hide");
				}
			});
		}, delay_hide);
	});
}

$(document).ready(function(){
	$("[tooltip]").each(function(){
		var tooltip_text = $(this).attr("tooltip");
		if(tooltip_text.includes(global_docs)){
			var url = get_url(tooltip_text);
			var ele = '&nbsp;<a href="'+url+'" target="_blank" class="link_tooltip info" tooltip="'+open_guide_l+'"><i class="fas fa-external-link-alt"></i></a>';
			
			//check whether element already exist.
			if($(this).next('.link_tooltip').length < 1){
				$(this).after(ele);
			}
		}
	});
});

//fetch url from between ""
function get_url(url) {
	var url = url.match(/\s*(['"])(https?:\/\/.+?)\1/g);
	url = url[0].replace(/"/g, "");
	return url;
}

function check_logout_session(data){
	
	if($(data.reponseText).find('#only_login_page')){
		return true;
	}
	
	return false;
};

function load_ajax_user(ele_id, url){
	$("#"+ele_id).on("select2:close", function(event){
		ele = $("#select2-"+ele_id+"-results")
		.parent(".select2-results")
		.prev(".select2-search")
		.find(".select2-search__field");
		ele.unbind();
	});
	$("#"+ele_id).on("select2:open", function(){
		
		ele = $("#select2-"+ele_id+"-results")
		.parent(".select2-results")
		.prev(".select2-search")
		.find(".select2-search__field");
		var append_uid = getParameterByName('act');
		ele.on("keydown", function(event){
			var _this = $(this);

			setTimeout(function(){

				if(_this.val().length > 2){

					$("#ajax_user_loader").show();
					$.ajax({
						type: "POST",
						url: url,
						data: {
							email: _this.val()
						},
						dataType : "json",
						success: function(usr_data){
							var ajax_user = new Object();
							ajax_user = usr_data["ajax_user"];

							$("#ajax_user_loader").hide();

							if(empty(ajax_user)) return false;

							$.each(ajax_user, function(uid, u){

								// Set the value, creating a new option if necessary
								if (!$("#"+ele_id).find("option[value=\'" + uid + "\']").length) {

									var opt = (append_uid == 'addvs' ? uid+' - ' : '')+u["email"];
									if(!empty(u["parent"])){
										opt +=" ("+u["parent"]+")";
									}
									var newOption = new Option(opt, uid, false, false);
									$("#"+ele_id).append(newOption).trigger("change");

								}

								$("#select2-"+ele_id+"-results")
								.parent(".select2-results")
								.prev(".select2-search")
								.find(".select2-search__field")
								.each(function(){
									$(this).trigger("input");
								});

							});
						}
					});

				}

			}, 200);

		});

	});

}

function enable_vertical_scaling(dont_hide = 0){
	if(empty(dont_hide)){
		$(".ver_scale_settings").hide();
	}

	if($("#enable_ver_scaling").prop("checked")){
		$(".ver_scale_settings").show();
	}

	$("#enable_ver_scaling").unbind().click(function(){
		$(".ver_scale_settings").toggle();
	});
}

/*
vmodal function usage:
:html structure:
<div id="ID" class="vmodal shadow-lg show">
	<div class="vmodal-heading">
		<div class="vmodal-title">HEADING</div>
		<span class="vmodal-close"><i class="fas fa-times fa-2x"></i></span>
	</div>
	<div class="vmodal-body">
		
	</div>
</div>

To initiate the modal from js call it this way:
$("ELEMENT").vmodal(ZINDEX); where ZINDEX is the parent div zindex by default it is 6

:Event handlers:
There are four event handlers as follows:
before.show.vmodal	this event is triggered before showing modal
on.show.vmodal		this event is triggered after modal is visible 
before.hidden.vmodal	this event is triggered before closing modal
on.hidden.vmodal		this event is triggered after closing modal
*/
(function( $ ){
	$.fn.vmodal = function(_zindex) {
		
		$this = this;
		script_id = randstr(5);
		vmodal_back_id = randstr(5);

		var navbar = $("#navbar").outerHeight(true);
		var noti_heading = $this.find(".vmodal-heading").outerHeight(true);
		var body = $( window ).height();

		$this.find(".vmodal-body").css("height", (body - navbar - noti_heading));
		$this.css("top", (navbar));

		if(!empty(_zindex)) $this.css("z-index", _zindex);

		if(empty($this.next(".vmodal_back").length)){
			$this.after('<div class="vmodal_back" id="'+vmodal_back_id+'" style="display:none;"></div>');
		}
		
		setTimeout(function(){
			$this.trigger("before.show.vmodal");
			$('#'+vmodal_back_id).fadeIn(500);
			$this.addClass("show");
			$this.trigger("on.show.vmodal");
			if(empty($this.next(".vmodal_back").next('.vmodal_script').length)){

				$this.next(".vmodal_back").after('<script class="vmodal_script" id="#'+script_id+'">\
				$("'+$this['selector']+'").find(".vmodal-close").unbind().click(function(){\
					$("'+$this['selector']+'").close_vmodal();\
				})\
				</script>');

			}
		}, 100)

		return $this;
	};
})( jQuery );

(function($){
	$.fn.close_vmodal = function() {
		$this = this;
		$this.trigger('before.hidden.vmodal');
		$this.next('.vmodal_back').fadeOut(500);
		$this.removeClass("show");
		setTimeout(function(){
			$this.next('.vmodal_back').remove();
			$this.next('.vmodal_script').remove();
		}, 50)
		$this.trigger('on.hidden.vmodal');
		$this.unbind();
		return $this;
	};
})( jQuery );

$(document).ready(function() {
	$('.vmodal').each(function(){
		if($(this).hasClass('show')){
			$('#'+$(this).attr('id')).vmodal();
		}
	});
});

function basename(str){
	var base = new String(str).substring(str.lastIndexOf('/') + 1); 
	return base;
}

function timeConverter(UNIX_timestamp){
	var a = new Date(UNIX_timestamp * 1000);
	return a.toUTCString();
}

// to change url problem in manageserver
function replaceUrlParam(url, paramName, paramValue){
	if (paramValue == null) {
		paramValue = '';
	}
	var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
	if (url.search(pattern)>=0) {
		return url.replace(pattern,'$1' + paramValue + '$2');
	}
	
	return url;
}

function show_toast(toast_title, msg, err = 0, time_to_delay = 5000, show_logs = ""){

	let toast_type = "success";
	let icon = "fa-check-circle";
	let logs_data = "";

	if(err == '1'){
		toast_type = "warning";
		icon = "fa-exclamation-circle";
	}else if(err == '2'){
		toast_type = "info";
		icon = "fa-info-circle";
	}else if(!empty(err)){
		toast_type = "error";
		icon = "fa-times-circle";
		
		if(show_logs){
			logs_data = `<a href="javascript:void(0)" onclick="loadlogs(`+show_logs+`);">`+show_log_lang+`</a>`;
		}
	}
  toast_content = '';
	if(msg){
		toast_content = `<div class="toast_message pt-2">`+msg+`</br>`+logs_data+`</div>`;
	}

	var _htm = `<div class="toast_body">
					<div class="flex_vh_center">
						<div class="toast_icon">
							<div class="toast_sucess_icon">
								<i class="fas `+icon+`"></i>
							</div>
						</div>
					</div>
					<div class="toast_content">
						<div class="toast_title ${(msg) ? "" : "py-2"}">`+toast_title+`</div>`
						+toast_content+
						`</div>
				</div>`;

	toastr.options = {
		"closeButton": true,
		"debug": false,
		"newestOnTop": true,
		"progressBar": true,
		"positionClass": "toast-top-right",
		"preventDuplicates": false,
		"showDuration": "300",
		"hideDuration": "5000",
		"timeOut": time_to_delay,
		"extendedTimeOut": "5000",
		"showEasing": "swing",
		"hideEasing": "linear",
		"showMethod": "fadeIn",
		"hideMethod": "fadeOut",
	}

	if(logs_data){
		toastr.options.onclick = null;
    	toastr.options.tapToDismiss = false;
	}

	let new_msg = '';

	// toast calling
	toastr[toast_type](new_msg, _htm);
}

function wordwrapper(len, text){
	if(text.length > len){
		return text.substr(0,len)+"...";
	}else{
		return text;
	}
}

function show_virtname(virt, font_size = "13px"){
	let full_name = "";
	let full_name_tt = "";
	switch (virt) {
		case 'kvm':
			full_name = "KVM";
			full_name_tt = "KVM";
			break;
		case 'proxk':
			full_name = "KVM-PX";
			full_name_tt = '<span style="color:var(--yellow)">Proxmox</span> <span style="color:var(--black)">KVM</span>';
			break;
		case 'proxo':
			full_name = "KVM-PX";
			full_name_tt = '<span style="color:var(--yellow)">Proxmox</span> <span style="color:var(--green)"> OpenVZ</span>';
			break;
		case 'openvz':
			full_name = "OPENVZ";
			full_name_tt = '<span style="color:var(--green)">Openvz</span>';
			break;
		case 'proxl':
			full_name = "LXC-PX";
			full_name_tt = '<span style="color:var(--yellow)">Proxmox</span> LXC';
			break;
		case 'vzk':
			full_name = "Virtuozzo KVM";
			full_name_tt = full_name_tt = '<span style="color:var(--red)">Virtuozzo</span><span style="color:var(--black)"> KVM</span>';
			break;
		case 'vzo':
			full_name = "Virtuozzo OpenVZ";
			full_name_tt = '<span style="color:var(--red)">Virtuozzo</span><span style="color:var(--green)"> OpenVZ</span>';
			break;
		case 'xcp':
			full_name = "XCP";
			full_name_tt = "XCP";
			break;
		case 'xcphvm':
			full_name = "XCP-HVM";
			full_name_tt = "XCP HVM";
			break;
		case	'xen':
			full_name = "XEN";
			full_name_tt = "XEN";
			break;
		case	'xenhvm':
			full_name = "XEN";
			full_name_tt = "XEN HVM";
			break;
		case	'lxc':
			full_name = "LXC";
			full_name_tt = "LXC";
			break;
		case	'docker':
			full_name = "DOCKER";
			full_name_tt = "DOCKER";
		case	'baremetal':
			full_name = "BAREMETAL";
			full_name_tt = "BAREMETAL";
	}

	let ret = '<span class="flatflare text-admin" style="font-size:'+font_size+';">'+full_name_tt+'</span>';
	return ret;
}

function show_server_virtname(virt, font_size = "13px"){
	let full_name_tt = "";
	switch (virt) {
		case 'kvm':
			full_name_tt = "KVM";
			break;
		case 'kvm lxc':
			full_name_tt = "KVM + LXC";
			break;
		case 'proxk proxl':
			full_name_tt = '<span style="color:var(--yellow)">Proxmox</span>';
			break;
		case 'openvz':
			full_name_tt = '<span style="color:#42b355">Openvz</span>';
			break;
		case 'vzk vzo':
			full_name_tt = full_name_tt = '<span style="color:var(--red)">Virtuozzo</span>';
			break;
		case 'xcp':
			full_name_tt = "XCP";
			break;
		case 'xen':
			full_name_tt = "XEN";
			break;
		case 'lxc':
			full_name_tt = "LXC";
			break;
		case 'msonly':
			full_name_tt = '<span style="color:#42b355">Master Only</span>';
	}
	
	let ret = '<span class="p-0 px-1 mr-1 flatflare font-weight-bold" style="font-size:'+font_size+';">'+full_name_tt+'</span>';
	return ret;
}

function generateString(length){
	const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    const charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

function generateColorHex() {
	const randomColor = Math.floor(1+Math.random()*16777215).toString(16);
	return "#"+randomColor;
}

function protocol_check(el){

	let selected_id = el.id;
	let value = el.value;

	if(empty(selected_id)){
		selected_id = $(el).attr('id');
	}
	
	// selecting current id and removing the whole text from the id
	selected_id = selected_id.replace(/\D+/g, "");
	
	switch(value){
		case "ICMP":
		case "GRE":
		case "ESP":

			// disable port and set the value ALL in port
			$("#fwr_port_"+selected_id).val("ALL");
			$("#fwr_port_"+selected_id).attr('disabled', true)
			break;

		default:
			// remove disable from port
			$("#fwr_port_"+selected_id).attr('disabled', false);
		break;
	}
}

function check_ip_type(element){

	let selected_id = "";
	let element_id = element.id;
	
	if(empty(element_id)){
		element_id = $(element).attr('id');
	}

	let source_address = "#source_addr";
	let result = element_id.match(/fwr_iptype/);

	// for edit table rules
	if(result){
		selected_id = element_id.replace(/\D+/g, "");
		source_address = "#fwr_source_addr_"+selected_id;
	}
			
	if($(element).val() == "-1"){
		
		$(source_address).val("ALL");
		$(source_address).attr("disabled", "disabled");

	}else if($(element).val() == "4"){
		
		$(source_address).attr("placeholder", "0.0.0.0/0");
		$(source_address).removeAttr("disabled");
		
		if(empty(result)){
			$(source_address).val("");
		}

	}else if($(element).val() == "6"){
		
		$(source_address).attr("placeholder", "::/0");
		$(source_address).removeAttr("disabled");
		
		if(empty(result)){
			$(source_address).val("");
		}

	}
}

function getCurrentMonthDetails() {
    const date = new Date();
    const year = date.getFullYear();
    const month = date.getMonth(); // Get the current month index (0-11)

    // Array of month names
    const monthNames = [
        "January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
    ];

    // Get the name of the current month
    const monthName = monthNames[month];

    // Get the number of days in the current month
    const daysInMonth = new Date(year, month + 1, 0).getDate();

    // Create an array of days in the month
    const daysArray = Array.from({ length: daysInMonth }, (_, i) => i + 1);

    return {
        year: year,
        monthNumber: month + 1, // Adding 1 since months are zero-indexed
        monthName: monthName,
        days: daysArray
    };
}

var charts_rendered = {};
function live_resource_graph2(draw_chart = {}, id, inital_chart_options, updated_graph_data = {}, updated_graph_data_and_options ={}){
	
	if(empty(draw_chart)){
	   
		if(charts_rendered[id] != undefined){

			charts_rendered[id].destroy();
			delete charts_rendered[id];
		}

		draw_chart = new ApexCharts(document.querySelector("#"+id), inital_chart_options);
		draw_chart.render();
		charts_rendered[id] = draw_chart;

	}else if(!empty(draw_chart) && !empty(updated_graph_data)){
   
		draw_chart.updateSeries(updated_graph_data);

	}else if(!empty(draw_chart) && !empty(updated_graph_data_and_options)){

		draw_chart.updateOptions(updated_graph_data_and_options);
	}

	return draw_chart;
};


function convertToPercentages(dataArray) {
    // Step 1: Calculate the total sum of the array
    var total = 0;
    for (var i = 0; i < dataArray.length; i++) {
        total += dataArray[i];
    }

    // Step 2: Convert each value to a percentage of the total
    var percentages = [];
    var cumulativePercentage = 0;

    for (var j = 0; j < dataArray.length; j++) {
        var percentage = (dataArray[j] / total) * 100;
        percentage = parseFloat(percentage.toFixed(2)); // Round to 2 decimal places
        cumulativePercentage += percentage;
        percentages.push(parseFloat(percentage.toFixed(2)));
    }

    // Step 3: Adjust the last element to ensure total is exactly 100%
    var discrepancy = 100 - cumulativePercentage;
    percentages[percentages.length - 1] += discrepancy;

    return percentages;
}


function size_converter(size , input_unit = "MB") {

    units = ['MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

	// searching in $units if any custom input other than MB
	index_no = units.indexOf(input_unit);

	// checking any other input passing which not exist in $units array
	if(index_no === -1){
		return false;
	}

	// int conversion
    size_in_mb = parseFloat(size);

    //to convert MB to GB TB and more ahead conversion
    for(var i = index_no; size_in_mb >= 1024 && i < units.length - 1; i++){
        size_in_mb = size_in_mb / 1024;
    }

    return size_in_mb.toFixed(0)+ ' ' + units[i];
}

// for stepper form the code is
//DOM elements

function show_loader(ele){
	if($("#"+ele).css('display') === 'none'){
		$("#"+ele).fadeIn();
	}else{
		$("#"+ele).fadeOut();
	}
}

function tab_to_select(element) {
	if (!element || !element.value) return;

	let tabId = element.value;

	let $trigger = $('a[data-toggle="tab"][href="#' + tabId + '"], a[data-toggle="pill"][href="#' + tabId + '"]');

	if ($trigger.length) {
	  $trigger.first().tab('show');
	}
}


function dismiss_notice(ele){

	var data = $(ele).data();
	var url_path = window.location.origin+window.location.pathname+"?act=notice&dismiss_notice=1&api=json";
	
	$.ajax({
		url: url_path,
		type: "post",
		dataType: "JSON",
		data: data,
		success: function(response){
			handleResponseData(response);
			if("done" in response){
				$("#ndiv_"+data.nid).remove();
				$("#ndiv_del_"+data.nid).html('');
			}
		}
	});
}

function search_fields(query) {
	
	query = query.toLowerCase().trim();
	var resultsDiv = $("#tab_search_results");
	
	if (query == "") {
		resultsDiv.hide();
		$(".search-highlight").removeClass("search-highlight");
		return;
	}


	var matchingItems = [];
	
	$("[show]").each(function() {
		var tab = $(this).attr("show");
		var container = $(this);

		if (!tab) return; // skip fields hidden due to VPS config (show attr is empty)
		
		container.find("label").each(function() {
			var labelText = $(this).text().toLowerCase();
			if (labelText.indexOf(query) > -1) {
				matchingItems.push({
					element: this,
					tab: tab,
					label: $(this).text().trim()
				});
			}
		});
	});
	
	if (matchingItems.length > 0) {
		var html = "";
		html = html + '<div class="dropdown-item-text"><strong>Found ' + matchingItems.length + ' result(s)</strong></div>';
		html = html + '<div class="dropdown-divider"></div>';
		
		$.each(matchingItems.slice(0, 10), function(i, item) {
			html = html + '<a class="dropdown-item" href="javascript:void(0)" onclick="focusField(\'' + item.tab + '\', this)">' + item.label + "</a>";
		});
		
		if (matchingItems.length > 10) {
			html = html + '<div class="dropdown-item-text text-muted">' + (matchingItems.length - 10) + " more...</div>";
		}
		
		resultsDiv.html(html);
		resultsDiv.show();
	} else {
		resultsDiv.html('<div class="dropdown-item-text text-muted">No results found</div>');
		resultsDiv.show();
	}
}

function focusField(tabName, element) {
	$(".search-highlight").removeClass("search-highlight");
	$("#tab_search_results").hide();
	$("#tab_search").val("");
	
	var tabLink = $('.nav-tabs a[role="' + tabName + '"]');
	if (tabLink.length) {
		tabLink.trigger("click");
	}
	
	setTimeout(function() {
		// Find the label in the visible tab
		$('[show="' + tabName + '"] label').each(function() {
			if ($(this).text().trim() == $(element).text().trim()) {
				var row = $(this).closest(".row");
				if (row.length) {
					row.addClass("search-highlight");
					$("html, body").animate({
						scrollTop: row.offset().top - 100
					}, 300);
				}
				return false;
			}
		});
	}, 200);
}