window.controlKeys = {
	8 : 'backspace',
	9 : 'tab',
	13 : 'enter',
	16 : 'shift',
	17 : 'ctrl',
	18 : 'alt',
	19 : 'pause/break',
	20 : 'caps lock',
	27 : 'escape',
	32 : 'pause',
	33 : 'page up',
	34 : 'page down',
	35 : 'end',
	36 : 'home',
	37 : 'left arrow',
	38 : 'up arrow',
	39 : 'right arrow',
	40 : 'down arrow',
	45 : 'insert',
	46 : 'delete',
	144 : 'num lock',
	145 : 'scroll lock'
};

window.allowFloatKeys = {
	8 : 'backspace',
	9 : 'tab',
	13 : 'enter',
	16 : 'shift',
	17 : 'ctrl',
	18 : 'alt',
	19 : 'pause/break',
	20 : 'caps lock',
	27 : 'escape',
	32 : 'pause',
	33 : 'page up',
	34 : 'page down',
	35 : 'end',
	36 : 'home',
	37 : 'left arrow',
	38 : 'up arrow',
	39 : 'right arrow',
	40 : 'down arrow',
	45 : 'insert',
	46 : 'delete',
	48 : '0',
	49 : '1',
	50 : '2',
	51 : '3',
	52 : '4',
	53 : '5',
	54 : '6',
	55 : '7',
	56 : '8',
	57 : '9',
	96 : 'numpad 0',
	97 : 'numpad 1',
	98 : 'numpad 2',
	99 : 'numpad 3',
	100 : 'numpad 4',
	101 : 'numpad 5',
	102 : 'numpad 6',
	103 : 'numpad 7',
	104 : 'numpad 8',
	105 : 'numpad 9',
	144 : 'num lock',
	145 : 'scroll lock',
	110 : 'decimal point',
	188 : 'comma',
	190 : 'period'
};

function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate();
		r.moveEnd('character', o.value.length);
		if (r.text == '')
			return o.value.length;
		return o.value.lastIndexOf(r.text);
	} else
		return o.selectionStart;
}

function doGetCaretPosition (o) {
	var caretPos = 0;	// IE Support
	if (document.selection) {
		o.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -o.value.length);
		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (o.selectionStart || o.selectionStart == '0')
		CaretPos = o.selectionStart;
	return (CaretPos);
}

function hasClass(el, cl) {
	if ((el.className === null) || (typeof el == 'undefined'))
		return false;
	var classes = el.className.split(" ");
	for (i in classes) {
		if (classes[i] == cl)
			return true;
	}
	return false;
}

function removeTraingZeros(num_str) {
	return num_str.replace(/0+$/, '');
}

function convertToInt_v(val_) {
    var val = parseInt(val_);
    if (isNaN(val)) {
        val = 0;
    }
    return val.toString();
}

function convertToInt(field) {
    field.value = convertToInt_v(field.value);
}


function convertToDouble_v(val_, precision) {
	var val = val_;
	val = val.replace(/,/g, ".").replace("-", "").replace(/ /g, '');
	var pos = val.indexOf(".");
	if (pos > -1) {
		var substr = val.substring(pos + 1);
		var pos2 = substr.indexOf(".");
		if (pos2 > -1) {
			var pos3 = parseInt(pos) + parseInt(pos2);
			pos3 = parseInt(pos3) + 1;
			val = val.substring(0, pos3);
		}
	} else if (val.length > 15) {
		val = val.substring(0, 15);
	}
	val = Number(val);
	if (isNaN(val)) {
		val = 0;
	}
	var decimals = 2;
	if (typeof precision === 'number') {
		decimals = precision;
	}

	val = roundScaled(val, decimals);
	val = val.toString();

	var newPos = val.indexOf(".");
	if (newPos > -1) {
		var newSubstr = val.substring(newPos + 1);
		if (newSubstr.length == 1) {
			val = val + "0";
		}
	} else {
		val = val + "." + Array.prototype.join.call({
			length : Math.min(decimals + 1, 2 + 1)
		}, "0");
	}

	return val;
}

function convertToDouble(field, precision) {
	field.value = convertToDouble_v(field.value, precision);
}

function convertOrAddPlaceholder(field, placeholder, convert, placeholderClass) {
    var val = field.value.replace(/,/g, ".").replace("-", "").replace(/ /g, '');
    val = Number(val);
    if (isNaN(val) || ! val) {
        field.className = placeholderClass;
        field.value = placeholder;
        field.removeAttribute("maxlength");
    }
    else {
    	if (convert != null) {
            convert(field);
		}
    }
}

function addjQueryFieldPlaceholder(field, placeholder, placeholderClass) {
	if (field.hasClass(placeholderClass) || ! field.val().trim()) {
        field.addClass(placeholderClass);
        field.val(placeholder);
        field.removeAttr("maxlength");
    }
}

function removejQueryFieldPlaceholder(field, placeholderClass, maxLength) {
    if (field.hasClass(placeholderClass)) {
        field.removeClass(placeholderClass);
        field.val('');
        if (!isNaN(maxLength)) {
            field.attr("maxlength", maxLength);
        }
    }
}

function removePlaceholder(field, elementClass, maxLength) {
    var val = Number(field.value);
    if (isNaN(val)) {
        field.className = elementClass;
        field.value = '';
        if (!isNaN(maxLength)) {
            field.setAttribute("maxlength", maxLength);
        }
    }
}

function ensure2DecimalPlacesAfterComma(val) {
	var decimals = 2;
	var newPos = val.indexOf(".");
	if (newPos > -1) {
		var newSubstr = val.substring(newPos + 1);
		if (newSubstr.length == 1) {
			val = val + "0";
		} else if (newSubstr.length == 0) {
			val = val + "00";
		}
	} else {
		val = val + ".00";
	}
	return val;
}

function validateAccount(id, e) {
	var expression = /^[0-9a-zA-Z\/\-\(\)\.]+$/;
	if (document.getElementById(id)) {
		var value = document.getElementById(id).value;
		var key;
		var keychar;
		if (window.event)
			key = window.event.keyCode;
		else if (e)
			key = e.which;
		else
			return true;
		keychar = String.fromCharCode(key);
		if ((key == null) || (key == 0) || (key == 8) || (key == 9)
				|| (key == 13) || (key == 27)) {
			return true;
		} else if (keychar.match(expression)) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

function processAccount(id) {
	if (document.getElementById(id)) {
		var el = document.getElementById(id);
		el.value = el.value.toUpperCase();
		el.value = el.value.replace(/\s/g, '');
	}
}

function validateVO(e) {
	var key;
	var keychar;
	if (window.event) {
		key = window.event.keyCode;
	} else if (e) {
		key = e.which;
	} else {
		return true;
	}
	keychar = String.fromCharCode(key);
	var refrenceString = "0123456789vVcC";
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13)
			|| (key == 27)) {
		return true;
	} else if ((key > 95) && (key < 106)) {
		return true;
	} else if ((refrenceString.indexOf(keychar) > -1)) {
		return true;
	} else {
		return false;
	}
}

function popupForm(formId) {
	if (id = document.getElementById(formId)) {
		id.target = '_blank';
		setTimeout("completeForm('" + formId + "')", 100);
	}
}

function completeForm(formId) {
	if (id = document.getElementById(formId)) {
		id.target = '';
	}
}

function validateFloat(params) {
	var key;
	var e;
	var obj;
	var prec = 2;
	if (params.hasOwnProperty('event')) {
		e = params.event;
	}
	if (!e) {
		e = window.event;
	}
	if (e.keyCode) {
		key = e.keyCode;
	} else if (e.which) {
		key = e.which;
	} else {
		return true;
	}
	if (window.controlKeys.hasOwnProperty(key)) {
		return true;
	}

	// copy paste
	if (e.ctrlKey && (key == 67 || key == 86 || key == 88))
		return true;

	if (params.hasOwnProperty('obj')) {
		obj = params.obj;
	}
	if (typeof obj === 'object') {
		if (params.hasOwnProperty('prec')) {
			prec = params.prec;
		}
		if (window.allowFloatKeys.hasOwnProperty(key) || event.key === '.') {
			if (key == 190 || key == 188 || key == 110 || event.key === '.') {
				var amount = obj.value;
				var lastDot = amount.lastIndexOf('.');
				lastDot = lastDot == -1 ? amount.lastIndexOf(',') : lastDot;
				lastDot = lastDot == -1 ? amount.lastIndexOf(String
						.fromCharCode(110)) : lastDot;

				if (lastDot >= 0)
					return false;
			}

			return true;
		} else {
			return false;
		}
	}
}

function formatAmount(event, input) {
	var keynum;
	var keychar;
	var numcheck;

	if (window.event) {// IE
		keynum = event.keyCode;
	} else if (event.which) { // Netscape/Firefox/Opera
		keynum = event.which;
	}


	keychar = String.fromCharCode(keynum);

	numcheck = /\d/;

	var amount = input.value;
	// if dot already entered
	var lastDot = amount.lastIndexOf('.');
	lastDot = lastDot == -1 ? amount.lastIndexOf(',') : lastDot;
	lastDot = lastDot == -1 ? amount.lastIndexOf(String.fromCharCode(110))
			: lastDot;
	String.fromCharCode(keynum)
	if (keynum == 190 || keynum == 188 || keynum == 110 || event.key === '.') {

		if (lastDot >= 0)
			return false;
	}

        if (event.key === 'ю' || event.key === 'б'){
		return false;
	}

	// if control key, comma, period or decimal point
	if (controlKeys.hasOwnProperty(keynum) || keynum == 188 || keynum == 190
			|| keynum == 110 || event.key === '.') {
		return true;
	}

	// copy paste
	if (event.ctrlKey && (keynum == 67 || keynum == 86 || keynum == 88))
		return true;

	// not keyboard digits and numpad digits
	if (!numcheck.test(keychar) && !(keynum >= 96 && keynum <= 105)) {
		return false;
	}

	// if amount not empty
	if (amount) {
		var cursorPos = getSelectionStart(input);
		// if dot exists in amount
		if (lastDot > -1) {
			var digitsAfterDot = amount.length - (lastDot + 1);
			if (digitsAfterDot >= 2 && cursorPos > lastDot) {
				return false;
			}
		}
	}
}

$(document).on('keypress keyup blur', '.allownumericonly', function (event) {
    if (event.which === 8 || ((event.keyCode >= 37 & event.keyCode <= 39) && event.key != '&' && event.key != '%' && event.key != "'") || (event.keyCode === 46 && event.key != '.')) { //FireFox control nums
        return;
    }

    if ((event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }

});

$(document).on('paste blur', '.nospaces', function (event) {
    this.value = this.value.replace(/\s/g, '');
});

$(document).on('keypress keyup blur', '.allownumericwithdecimal', function (event) {
	var val = jQuery(this).val();
	// var reg = /^\d{0,}[\,\.]{1}\d{2,}/;

	if (event.which === 8 || ((event.keyCode >= 37 & event.keyCode <= 39) && event.key != '&' && event.key != '%' && event.key != "'") || (event.keyCode === 46 && event.key != '.')) { //FireFox control nums
		return;
	}
	//this.value = this.value.replace(/[^0-9\.]/g,'');
	//jQuery(this).val(jQuery(this).val().replace(/[^0-9\.\,]/g,''));

	var amount = this.value;
	// if dot already entered
	var lastDot = amount.lastIndexOf('.');
	lastDot = lastDot == -1 ? amount.lastIndexOf(',') : lastDot;
	lastDot = lastDot == -1 ? amount.lastIndexOf(String.fromCharCode(110))
		: lastDot;



	if ((event.which != 44 || jQuery(this).val().indexOf(',') != -1 || jQuery(this).val().indexOf('.') != -1) && (event.which != 46 || jQuery(this).val().indexOf('.') != -1 || jQuery(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
		event.preventDefault();
	}

	if (amount) {

		var cursorPos = doGetCaretPosition(this);
		// if dot exists in amount
		if (lastDot > -1) {
			var digitsAfterDot = amount.length - (lastDot + 1);
			if (digitsAfterDot >= 2 && cursorPos > lastDot) {
				return false;
			}
		}
	}
});

function onlyNumericWithDecimal(field, event) {
    var key = event.which ? event.which : event.keyCode;

    if (key === 8 || (key >= 35 & key <= 39) || key === 46 || key === 45) {
        return true;
    }

    if (event.shiftKey) {
        return false;
    }

    var amount = field.value;
    var lastDot = amount.indexOf('.');
    lastDot = lastDot == -1 ? amount.lastIndexOf(',') : lastDot;
    lastDot = lastDot == -1 ? amount.lastIndexOf(String.fromCharCode(110)) : lastDot;

    var dot = key == 110 || key == 188 || key == 190;

    if (dot && lastDot > -1) {
        return false;
    }
    else if (! dot && (key < 48 || key > 57) && (key < 96 || key > 105) && ! event.ctrlKey) {
        return false;
    }

    if (amount) {
        var cursorPos = doGetCaretPosition(field);
        if (lastDot > -1) {
            var digitsAfterDot = amount.length - (lastDot + 1);
            if (digitsAfterDot >= 2 && cursorPos > lastDot) {
                return false;
            }
        }
    }

    return true;
}

function amountKeydown(event) {
	return formatAmount(event, this) && validateFloat({
		event : event,
		obj : this
	});
}

function normalizeStrAsNumber(field, allowZero) {
	if (typeof allowZero == "undefined") {
		allowZero = true;
	}
	field.value = parseInt(field.value, 10);
	if ((field.value == 0 && !allowZero) || isNaN(field.value)) {
		field.value = "";
	}
}

function numericOrDash(field) {
	var i = 0;
	for (i; i < field.value.length; i++) {
		if(field.value[i] !== '-'&& field.value[i] !== '0' && !parseInt(field.value[i], 10)) {
			field.value = "";
			break;
		}
	}
}

function numberInputKeydown(event) {
	return formatNumberInputField(event, this);
}
function formatNumberInputField(event, input) {
	var keynum;
	var keychar;
	var numcheck;

	if (window.event) {// IE
		keynum = event.keyCode;
	} else if (event.which) { // Netscape/Firefox/Opera
		keynum = event.which;
	}
	if ($.inArray(keynum, [ 46, 8, 9, 27, 13 ]) !== -1 ||
	// Allow: Ctrl+A
	(keynum == 65 && event.ctrlKey === true) ||
	// Allow: Ctrl+C
	(keynum == 67 && event.ctrlKey === true) ||
	// Allow: Ctrl+X
	(keynum == 88 && event.ctrlKey === true) ||
	// Allow: home, end, left, right
	(keynum >= 35 && keynum <= 39)) {
		// let it happen, don't do anything
		return;
	}
	// Ensure that it is a number and stop the keypress
	if ((event.shiftKey || (keynum < 48 || keynum > 57))
			&& (keynum < 96 || keynum > 105)) {
		event.preventDefault ? event.preventDefault() : (event.returnValue = false);
	}
}
// =================================================
// =========== DEBUGGING

// UI functions (based on jQuery)

jQuery(document).ready(
		function() {
			ClientsDropdown();

			// jQuery(document).on("paste",".jsPasteModifier", function(e){
			jQuery(".jsPasteModifier").bind(
					"paste",
					function(e) {
						var clipped = 'undefined;'
						if (window.clipboardData
								&& window.clipboardData.getData) { // IE
							clipped = window.clipboardData.getData('Text');
						} else if (e.originalEvent.clipboardData
								&& e.originalEvent.clipboardData.getData) {
							clipped = e.originalEvent.clipboardData
									.getData('text');
						}
						clipped = clipped.replace(/(\r\n|\n|\r)/gm, " ");
						jQuery(this).val(clipped);
						e.preventDefault();
					});
		});

function ClientsDropdown(s) {
	jQuery(document).bind('click', function(e) {
		if (!jQuery(e.target).parents().hasClass('profile2')) {
			jQuery('.profile2 ul', s).hide();
			jQuery('.profile2').removeClass('focus');
		}
	});
	if (jQuery('.profile2', s).length) {
		jQuery('.profile2 .bullet', s).click(function() {
			jQuery('.profile2 ul', s).slideToggle(100);
			jQuery('.profile2').toggleClass('focus');
		});
		jQuery('.profile2 ul a', s).click(function() {
			jQuery('.profile2 ul', s).hide();
			jQuery('.profile2').removeClass('focus');
		});
	}
}

function show(obj) {
	var el = document.getElementById(obj);
	el.style.display = '';
}
function hide(obj) {
	var el = document.getElementById(obj);
	el.style.display = 'none';
}

function loginSubmit(event) {
    return submitOnEnter(event);
}

function loginSubmitWithSelector(event, selector) {
	return submitOnEnterWithSelector(event, selector);
}

function submitOnEnterWithSelector(event, selector) {
    if (isEnter(event)) {
        if (typeof Loader !== 'undefined') {
            Loader.init();
        }
		if(selector !== undefined){
			jQuery(selector).click();
			return false;
		}
    }
    return true;
}

function submitOnEnter(event) {
	if (isEnter(event)) {
		if (typeof Loader !== 'undefined') {
			Loader.init();
		}
		jQuery('.submit_hook').click();
		return false;
	}
	return true;
}

function isEnter(event) {
	var keynum;

	if (window.event) {// IE
		keynum = event.keyCode;
	} else if (event.which) { // Netscape/Firefox/Opera
		keynum = event.which;
	}

	if (keynum == 13) {
		return true;
	} else {
		return false;
	}
}

function confirmationDialog(title, content, maxLength, targetClass, yesMsg, noMsg, placeholderMsg, errorMsg, confirmMsgClass) {
    var content_val = content;
    content_val +=
		'<div style="padding-top: 15px;">' +
			'<textarea id="confirm_text" rows="4" cols="47" maxlength="' + maxLength + '" placeholder="' + placeholderMsg +'" style="resize: none; width: 100%;"></textarea>' +
			'<p id="dialog_error_text" class="text-danger" style="display:none"> ' +
        		errorMsg +
			'</p> '
		'</div>';

    $.confirm({
        title: title,
        content: content_val,
        confirmButton: yesMsg,
        cancelButton: noMsg,
        confirm: function(){
            var confirm_txt = $('#confirm_text');
            if (confirm_txt.val() == '') {
                $('#dialog_error_text').show();

                return false;
            }else{
                $(confirmMsgClass).val(confirm_txt.val());
                $(targetClass).click();

                return true;
            }
        }
    });
}

function toggleCheckBoxes() {
	var attr = jQuery('.table_all_checkboxes').is(':checked');
	var newWal = typeof attr !== 'undefined' && attr !== false;
	jQuery('.table_checkbox').each(function(i, e) {
		jQuery(e).prop('checked', newWal);
	});

    //for News
    if (document.getElementById("newsMailTableForm-markAll") ) {
	    if (attr == true) {
	        document.getElementById("newsMailTableForm-markAll").style.setProperty("visibility","visible");
	        document.getElementById("newsMailTableForm-markAllButton").style.setProperty("visibility","visible");
	        }
	    else {
	        document.getElementById("newsMailTableForm-markAll").style.setProperty("visibility","hidden");
	        document.getElementById("newsMailTableForm-markAllButton").style.setProperty("visibility","hidden");
	        }
	    }
}

function toggleRowCheckBox(checked) {
    if (document.getElementById("newsMailTableForm-markAll") ) {
        var total_checked = jQuery('.table_all_checkboxes').is(':checked');

        if (total_checked == true) {
            var checkedAllRows = true;
            	jQuery('.table_checkbox').each(function(i, e) {
            		if (jQuery(e).prop('checked') == false)
            		checkedAllRows = false;
            	});

            if (checked == false) {
                document.getElementById("newsMailTableForm-markAll").style.setProperty("visibility","hidden");
                }
            else if (checkedAllRows == true) {
                document.getElementById("newsMailTableForm-markAll").style.setProperty("visibility","visible");
                }
        }


        //checked at least one
        if (checked == true) {
                document.getElementById("newsMailTableForm-markAllButton").style.setProperty("visibility","visible");
                }
        else {
            var checkedOneRow = false;
                jQuery('.table_checkbox').each(function(i, e) {
                    if (jQuery(e).prop('checked') == true) {
                    checkedOneRow = true;
                    }
                });
            if (checkedOneRow == true) {
                document.getElementById("newsMailTableForm-markAllButton").style.setProperty("visibility","visible");
                }
            else {
                document.getElementById("newsMailTableForm-markAllButton").style.setProperty("visibility","hidden");
                }
        }

    }
}

function getUnixTime() {
	var curTime = new Date();
	return curTime.getTime();
}

function isNumber(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

function replaceSymbols(id) {
	var patWS = /\s{2,}/g;
	var patWQ = /\'{2}/g;
	var patWW = /\;/g;
	var patWH = /\–/g;
	var patNL = /\n/g;

	var $elem = jQuery('#' + id);
	$elem.val($elem.val().replace(patWS, " ").replace(patWQ, '\"').replace(
			patWH, "-").replace(patNL, " ").replace(patWW, '\,'));
}


function replaceSpaces(id) {
	var patWS = /\s{2,}/g;

	var $elem = jQuery('#' + id);
	$elem.val($elem.val().replace(patWS, " ").trim());
}

function replaceSpacesAndUppercase(id) {
	if (document.getElementById(id)) {
		var el = document.getElementById(id);
		var patWS = /\s{2,}/g;
		el.value = el.value.replace(patWS, " ").trim();
		el.value = el.value.toUpperCase();
	}
}

function replaceSimicol(id) {
	var patWW = /\;/g;
	var $elem = jQuery('#' + id);
	$elem.val($elem.val().replace(patWW, '\,'));
}

// safe rounding
function roundScaled(num, scale) {
	var numParsed = parseFloat(num);
	var numPowed = parseFloat(double_mul10_toString(numParsed, scale));

	var smallPart = Math.round(numPowed % 1);
	var bigPart = Math.floor(numPowed);
	return ensure2DecimalPlacesAfterComma(removeTraingZeros(double_div10_toString(
			bigPart + smallPart, scale)));
}

function double_mul10_toString(num, scale) {
	var numStr = num.toFixed(20).toString();
	var ret = '';
	var commaPassed = false;
	var afterComma = 0;
	for (var i = 0; i < numStr.length; i++) {
		var char_ = numStr.charAt(i);
		if (!isNaN(char_)) {
			if (commaPassed)
				afterComma++;
			if (afterComma === scale + 1)
				ret += '.';
			ret += char_;
		} else if (char_ === '.' || char_ === ',')
			commaPassed = true;
	}
	while (afterComma < scale) {
		afterComma++;
		ret += '0';
	}

	return ret;
}

function double_div10_toString(num, scale) {
	var numStr = num.toString();
	if (scale <= 0)
		return numStr;
	var ret = '';
	var commaPos = Math.max(numStr.indexOf('.'), numStr.indexOf(','));
	var containsComma = commaPos !== -1;
	var commaNewPos = containsComma ? (numStr.length - 1) - commaPos + scale
			: scale; // s konca kolvo cifr, posle skolki postavitj kommu
	var afterComma = 0;
	var digitsStarted = !containsComma;
	var i;
	for (i = 0; i < numStr.length; i++) {
		var char_ = numStr.charAt(numStr.length - 1 - i);

		if (!isNaN(char_)) {
			if (!digitsStarted) {
				if (char_ === '0')
					continue;
				else
					digitsStarted = true;
			}

			if (commaNewPos === (i - (containsComma ? 1 : 0)))
				ret = '.' + ret;
			ret = char_ + ret;
		} else if (!digitsStarted) {
			if (char_ === '.' || char_ === ',')
				continue;
			else
				digitsStarted = true;
		}
	}

	var zerosToAdd = numStr.length - (containsComma ? 1 : 0) - commaNewPos;
	if (zerosToAdd <= 0) {
		zerosToAdd = zerosToAdd < 0 ? Math.abs(zerosToAdd) : 0;
		i = 0;
		while (i < zerosToAdd) {
			i++;
			ret = '0' + ret;
		}
		ret = '0.' + ret;
	}

	return ret;
}

function filterDelimiters(input) {
	var $input = jQuery(input);
	var newVal = $input.val().replace(/\s/g, "").replace(",", ".");
	$input.val(newVal);
}

function clickBankSearchIfNeeded(bankType, useCode, useName, part) {
	if (typeof bankPopupOpened === 'undefined' || !bankPopupOpened) {
		bankPopupOpened = true;
		var bankCode = '';
        var bankCodeValue = '';
		if (useCode) {
			bankCode = document.getElementById('new_paymentForm-' + bankType
					+ 'BankSwiftCode_' + part);

			//we sometimes have no inputSwiftName generated by currency value, in that case it is INT
			if(bankCode === null){
                bankCode = document.getElementById('new_paymentForm-' + bankType
                    + 'BankSwiftCode_' + 'INT');
			}

			if(bankCode === null){
				return;
			}

			bankCodeValue = bankCode.value;
			//bankCode = bankCode.substring(0, 6);
		}
		var bankName = '';
		if (useName) {
			bankName = document.getElementById('new_paymentForm-' + bankType
			+ 'BankSwiftName_' + part).value;
		}
		preparePopupWithData(part.toLowerCase(), bankType, bankCodeValue, bankName, '');
	}
}

function deselectAllCheckboxes() {
	jQuery('input:checked').each(function() {
		jQuery(this).prop('checked', false);
	});
}

function selectAndView(idx) {
	deselectAllCheckboxes();
	jQuery('table#mailOutTable input#selectedRow' + idx).prop('checked', true);
	jQuery('.hook-viewButton')[0].click();
}


function toggleMustReadCheckbox(){
    if(document.getElementById('fileupload-fMustRead').checked){
       document.getElementById('fileupload-fMustAgree').checked = false;
    }
}
function toggleMustAgreeCheckbox(){
    if(document.getElementById('fileupload-fMustAgree').checked){
        document.getElementById('fileupload-fMustRead').checked = false;
    }
}

/**
 * isIntersect() returns the intersecting status between two elements
 * based on the passed in Element objects
 *
 * @param {Element, Element} Element object of DOM
 * @return {Boolean|null} intersect status or null if native objet not received
 */
function isIntersect(e1, e2) {
	let rect1 = e1 instanceof Element ? e1.getBoundingClientRect() : false;
	let rect2 = e2 instanceof Element ? e2.getBoundingClientRect() : false;

	let intersect = null;
	if (rect1 && rect2) {
		intersect = !(rect1.right < rect2.left
			|| rect1.left > rect2.right
			|| rect1.bottom < rect2.top
			|| rect1.top > rect2.bottom);
	}
	return intersect;
}

/**
 * intersectByXAxis() returns the intersecting in pixels between two elements by X Axis
 * based on the passed in Element objects
 *
 * @param {Element, Element} Element object of DOM
 * @return {int|null} intersect pixels count or null if native objet not received
 */
function intersectByXAxis(e1, e2){
	let rect1 = e1 instanceof Element ? e1.getBoundingClientRect() : false;
	let rect2 = e2 instanceof Element ? e2.getBoundingClientRect() : false;
	if (rect1 && rect2) {
		return rect1.right - rect2.left;
	}else {
		window.console ? console.warn('Please pass native Element object') : null;
		return 0;
	}
}

/**
 * setLeftMenuStyle() set left menu display style depended
 * by external email link lenght
 */
function setLeftMenuStyle(){
	jQuery(document).ready(function(){
		jQuery('.leftMenu').css('display', 'inline-block');
	});
}
/**
 * getLeftMenuStyle() get left menu display style depended
 * by external email link length
 */
function getLeftMenuStyle(){
	let style = 'block';
	$('.ext_email').each(function( index, element ){
		let parentLen = element.offsetParent().offsetWidth;
		let emailLen = element.offsetWidth;
		if (parentLen < emailLen || parentLen === emailLen){
			style = 'inline-block';
			return false;
		}
	});
	return style;
}

function hidePopup() {
	bankPopupOpened = false;
	jQuery('#popup_frame').attr('src', '');
	jQuery.unblockUI();
}

function showPopup(src) {
	jQuery('#popup_frame').attr('src', encodeURI(src));
	jQuery.blockUI({
		message: jQuery('#popup'),
		css: {
			border: 'none',
			width: '50%',
			top:  '50%',
			left: '50%',
			'transform': 'translate(-50%, -50%)',
			cursor:'default'
		},
		overlayCSS: {
			cursor:'default'
		},
		baseZ: 999999
	});
	jQuery('.blockOverlay').click(function() {
		hidePopup();
	});
}

function showPopupTP(src) {
	jQuery('#popup_frame').attr('src', encodeURI(src));
	jQuery('#popup').attr('id','popup2');
	jQuery.blockUI({
		message: jQuery('#popup2'),
		css: {
			border: 'none',
			top:  '50%',
			left: '50%',
			width: '50%',
			'transform': 'translate(-50%, -50%)',
			'min-width': '39rem',
			cursor:'default'
		},
		overlayCSS: {
			cursor:'default'
		},
		baseZ: 999999
	});
	jQuery('.blockOverlay').click(function() {
		hidePopup();
	});
}

function showPopup(src, popup_header, header_details) {
	jQuery('#popup_frame').attr('src', encodeURI(src));
	jQuery('#popup_header').text(popup_header);
	jQuery('#popup_header').append('<span id="popup_header_details"></span>');
	jQuery('#popup_header_details').text(header_details);
	jQuery.blockUI({
		message: jQuery('#popup'),
		css: {
			border: 'none',
			top:  '50%',
			left: '50%',
			'transform': 'translate(-50%, -50%)',
			width: '50%',
			cursor:'default'
		},
		overlayCSS: {
			cursor:'default'
		},
		baseZ: 999999
	});
	jQuery('.blockOverlay').click(function() {
		hidePopup();
	});
}

function showCardPopup(src, popup_header, header_details) {
	jQuery('#popup_frame').attr('src', encodeURI(src));
	jQuery('#popup_header').text(popup_header);
	jQuery('#popup_header').append('<span id="popup_header_details"></span>');
	jQuery('#popup_header_details').text(header_details);
	jQuery.blockUI({
		message: jQuery('#popup'),
		css: {
			border: 'none',
			top:  '50%',
			left: '50%',
			'transform': 'translate(-50%, -50%)',
			width: '50%',
			cursor:'default'
		},
		overlayCSS: {
			cursor:'default'
		},
		baseZ: 999999
	});
	jQuery('.blockOverlay , .popupClose').click(function() {
		jQuery('#popup_frame').attr('src', '');
		jQuery.unblockUI();
	});
}

function resizeIframe(obj) {
	var srcStr = obj.src;
	if (srcStr.indexOf('tradeplatform_request')>=0 || srcStr.indexOf('fi_platforms')>=0) {
		obj.style.height = '35rem';
		if (obj.contentWindow.document.body.innerHTML.indexOf("tradeplatform_request_done") > 0){
			obj.style.height = '17rem'
		}
	}
}


/*
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing.
 */
function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};
