(function ($) {
	"use strict";
	window.loadedpage = false;
	//$('.staffs_list_select').select2();
	
	$('#multitg_entitytype').change(function(){
		var entType = $(this).val();
		console.log("entType:",entType);
		$(".firstAdded").remove();
		
		$.ajax({
			url: location.origin+location.pathname, 
			dataType: "json",
			data: {
				restmethod:"get_crmelems_all_list",
				enttype: entType
			},
			success: function( result ){
			}
		});
		
		$('#multitg_entitytype').after('<div class="firstAdded">TEST - '+entType+'</div>');
	});

	$('.staffs_list_select').select2();

	//console.log("Location: ", location);

	function alv_serder_checker(vcode){
		console.log("Clicked on SERVICE: ", vcode);
	}

	/*
	var prBody = $("body",parent.document);
	var prScript = parent.document.createElement("script")
	prScript.src="/bx24/template/js/main.js"; //https://sms.4u.uz
	prScript.onload=function(){ alovoiceInit(); };
	prBody.appendChild(prScript);
	*/

	$(document).ready(function(){
		$(".alv_navliink").click(function(){
			
			var pgId = $(this).attr("aria-controls");
			console.log( "Load page:", pgId );
			window.loadedpage = pgId;
			loadAloVoicePage(pgId,function( result ){ 
				$("#alv_mainblock").html(result);
				setTimeout(function(){
					afterLoadPage();
				},500);
			});
			$(".alv_navliink").removeClass("active");
			$(this).addClass("active");
		});
		
		if(typeof afterLoadPage !== 'undefined'){
			afterLoadPage();
		}
	});

})(jQuery);

function alovoiceInit(){
	console.log("AAAAA",window);
}

function loadAloVoicePage(loadpage,cbk){
	$.ajax({
		url: location.origin+location.pathname, 
		//dataType: "json",
		data: { loadpage:loadpage },
		success: function( result ){ /*console.log("Func page loading: ",result);*/ cbk(result); }
	});
}

function loadAloVoiceInfo(loadfunc,cbk){
	if(typeof loadfunc == 'object'){
		var sendData =loadfunc;
	} else {
		var sendData = { restmethod:loadfunc };
	}
	$.ajax({
		method: "POST",
		url: location.origin+location.pathname, 
		dataType: "json",
		data: sendData,
		success: function( result ){ cbk(result); }
	});
}
function doAloVoiceCmd(cmd,data,cbk){
	if(typeof data == 'undefined'){ var data = {}; }
	data['cmd'] = cmd;
	$.ajax({
		method: "POST",
		url: location.origin+location.pathname, 
		dataType: "json",
		data: data,
		success: function( result ){ cbk(result); }
	});
}

function formatBytes(a,b=2,k=1024){with(Math){let d=floor(log(a)/log(k));return 0==a?"0 Bytes":parseFloat((a/pow(k,d)).toFixed(max(0,b)))+" "+["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"][d]}}

function copyToClipboardText(ctext) {
	console.log("Check copy:",ctext);
	var $temp = $("<input>");
	$("body").append($temp);
	$temp.val(ctext).select();
	document.execCommand("copy");
	$temp.remove();
}

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

function aloModal(params){
	/*
	label
	body
	btn
	callback
	*/
	console.log("Begin making modal...");
	//$("#alvModal").show().css("opacity",1);
	var sendBtnText = (params.btn) ? params.btn : 'OK';
	$("#alvModalSendBtn").remove();
	$("#alvModalFooter").append('<button type="button" class="btn btn-primary" id="alvModalSendBtn">'+sendBtnText+'</button>' );
	
	$("#modalCloseBtn").text( "Отмена");
	$("#alvModalLabel").text( (typeof params.label !== 'undefined') ? params.label : "Выберите" );
	if(typeof params.body !== 'undefined') { $("#alvModalBody").html(params.body); }
	if(typeof params.btn !== 'undefined') { $("#alvModalSendBtn").text(params.btn); } 
	if(typeof params.callback !== 'undefined') { 
		$("#alvModalSendBtn").click(function(){
			params.callback();
			if(typeof params.nohide == 'undefined') {
				$('#alvModal').modal('hide');
			}
		});  
	} else {
		if(typeof params.nohide == 'undefined') {
			$('#alvModal').modal('hide');
		}
	} 
	$('#alvModal').on('shown.bs.modal', function () { $('#tgnumber').trigger('focus'); });
	$('#alvModal').modal('show');
}

function AloTelegram(loadfunc,params,cbk){
	
	if(typeof params == 'object' && Object.keys(params).length>0){
		var ajData = params;
		ajData.tgmethod = loadfunc;
	} else {
		var ajData = { tgmethod:loadfunc };
	}
	loadAloVoiceInfo(ajData,function( result ){ cbk(result); })
}


function doUpload(me){
	var upload = new Upload(me,function(arfile){
		console.log("File UUUUUU:",arfile);
		window.uploadedarfile = arfile;
		$(me).prev().text('Загружено: '+arfile.name);
	}); 
	upload.doUpload();
}

var Upload = function (fileinput,cbk) {
	var myid = $(fileinput).attr("id");
	console.log("File ID:",myid);
	
	var afile = document.getElementById(myid).files;
	

    this.file = afile[0];
    this.fileinput = fileinput;
    this.cbk = cbk;
    $(fileinput).after('<div id="progress-wrp"> <div class="progress-bar"></div>  <div class="status">0%</div></div>');
};

Upload.prototype.getType = function() {
    return this.file.type;
};
Upload.prototype.getSize = function() {
    return this.file.size;
};
Upload.prototype.getName = function() {
    return this.file.name;
};
Upload.prototype.doUpload = function () {
    var that = this;
    var cbk = this.cbk;
    var formData = new FormData();
	
    // add assoc key values, this will be posts values
    formData.append("file", this.file, this.getName());
    formData.append("restmethod","upload_file");

    $.ajax({
        type: "POST",
        url: location.origin+location.pathname,
		dataType: 'json',
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                myXhr.upload.addEventListener('progress', that.progressHandling, false);
            }
            return myXhr;
        },
        success: function (data) {
            cbk(data);
        },
        error: function (error) {
            // handle error
        },
        async: true,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        timeout: 60000
    });
};

Upload.prototype.progressHandling = function (event) {
    var percent = 0;
    var position = event.loaded || event.position;
    var total = event.total;
    var progress_bar_id = "#progress-wrp";
    if (event.lengthComputable) {
        percent = Math.ceil(position / total * 100);
    }
    // update progressbars classes so it fits your code
	if(percent>99){
		$(progress_bar_id).remove();
	} else {
		$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
		$(progress_bar_id + " .status").text(percent + "%");
	}
};

