// Global Variales
var K_NewOffice = false; // Update the cookie anytime something is clicked

// function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
function formatMoney(amount, decimalCount, decimal, thousands) {
    try {
        if (typeof (decimalCount) == 'undefined') {
            decimalCount = 2;
        }
        if (typeof (decimal) == 'undefined') {
            decimal = ".";
        }
        if (typeof (thousands) == 'undefined') {
            thousands = ',';
        }

        decimalCount = Math.abs(decimalCount);
        decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

        const negativeSign = amount < 0 ? "-" : "";

        let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
        let j = (i.length > 3) ? i.length % 3 : 0;

        return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
    } catch (e) {
        console.log(e)
    }
}  // End of formatMoney ------------------------------------------------

function K_SetPopOffset(Class, nTop, nLeft) {
    $(Class).each(function (i) {
        var Myoffset = $(this).position();
        var MyY = Myoffset.top;
        var MyX = Myoffset.left;

        $($(this).attr("data-ref")).css({top: MyY - nTop, left: MyX + nLeft});

        $(this).on({
            mouseover: function () {
                $($(this).attr("data-ref")).show();
            },
            mouseout: function () {
                $($(this).attr("data-ref")).hide();
            }
        });
    });
}  // End of K_SetPopOffset ------------------------------------------------

function K_PopupCenter(url, title, options, w, h) {
    // Fixes dual-screen position                         Most browsers      Firefox
    var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : window.screenX;
    var dualScreenTop = window.screenTop != undefined ? window.screenTop : window.screenY;

    var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
    var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

    var systemZoom = width / window.screen.availWidth;
    var left = (width - w) / 2 / systemZoom + dualScreenLeft
    var top = (height - h) / 2 / systemZoom + dualScreenTop
    if (options.length) {
        options += ','
    }
    //var newWindow = window.open(url, title, options + ' width=' + w / systemZoom + ', height=' + h / systemZoom + ', top=' + top + ', left=' + left);
    var newWindow = window.open(url, title, options + ' width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

    // Puts focus on the newWindow
    if (window.focus) newWindow.focus();
    return newWindow;
}

function K_ConfirmDialog(message, YesCallback, YesCBArg, cWidth) {
    let callType = typeof YesCallback ;
    let Width = 'auto' ;
    if ( typeof cWidth !== "undefined") { Width = cWidth }
	if (callType === 'function') {
        $('<div style="line-height: 22px; text-align:center;"></div>').appendTo('body')
            .html('<div><h6>' + message + '</h6></div>')
            .dialog({
                modal: true,
                title: 'Confirmation',
                zIndex: 10000,
                autoOpen: true,
                width: Width,
                resizable: false,
                buttons: {
                    Yes: function () {
                        YesCallback(YesCBArg);
                        $(this).dialog("close");
                    },
                    No: function () {
                        $(this).dialog("close");
                    }
                },
                close: function (event, ui) {
                    $(this).remove();
                }
            });
		
	} else {
        $('<div></div>').appendTo('body')
            .html('<div><h6>' + message + '</h6></div>')
            .dialog({
                modal: true,
                title: 'Information',
                zIndex: 10000,
                autoOpen: true,
                width: Width,
                resizable: false,
                buttons: {
                    OK: function () {
                        $(this).dialog("close");
                    },
                },
                close: function (event, ui) {
                    $(this).remove();
                }
            });
		
	}
};

function K_CopyClasses(eFrom, eTo, aBaseClasses, aNotClasses) {
    // Copy all the classes from one element to another - except NotClasses
    var classList = $(eFrom).attr('class').split(/\s+/);
    var i;
    $(eTo).removeClass() ;  // Remove all classes
    for (i = 0; i < aBaseClasses.length; ++i) {
        // Add BaseClasses
        $(eTo).addClass(aBaseClasses[i]) ;
    }
    $.each(classList, function(index, item) {
        if ((aNotClasses == null) || (jQuery.inArray(item, aNotClasses) === -1)) {
            eTo.addClass(item) ;
        }
    });
    return eTo ;
}

function K_QRCode(cId, nWidth, cURL, cLabel){
    // Make sure you include K_QRCode.CSS
	// You must have a Div to contain the code
    // Clear Previous QR Code
    // 0: normal
    // 1: label strip
    // 2: label box
	
	let nMode = 0  ;
	if (cLabel &&(cLabel.length > 0)) {nMode = 1;}
    $('#'+cId).empty();
    
    // Set Size to Match User Input
    $('#'+cId).css({
	  'display': 'flex', 
      'width'  : nWidth,
      'height' : nWidth
    })
    
    // Generate and Output QR Code
    $('#'+cId).qrcode({mode: nMode, 'width': nWidth, 'height': nWidth,'url': cURL,'text': cURL,'label': cLabel, 'qrsize':5});

}

// K_isNumber - Usage
//  <input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return K_isNumber(event)" />
function K_isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

// K_ValidateEMail(email) - Usage
//
//     if (K_ValidateEMail( $("#EMail").val() )) {
//        $("#btnSignIn").show();
//     } else { $("#btnSignIn").hide(); }
//
function K_ValidateEMail(email) {
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}
function K_AddMinutesToDate(date, minutes) {
    return new Date(date.getTime() + minutes * 60000);
}

function K_FormatDate(date, cFmt) {
    var cResult = "";
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0'+minutes : minutes;
    var strTime = hours + ':' + minutes + ' ' + ampm;

    if (cFmt = 'Time') {
        cResult = strTime ;
    } else {
        cResult = (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + "  " + strTime
    }
    return (cResult);
}

// K_PasteHTMLAtCaretJS() -------------------------------------------
function K_InsertAtCaret(areaId,text) {   // K_DBDocAdminJS()
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == "0") ?
        "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ("character", -txtarea.value.length);
        strPos = range.text.length;
    }
    else if (br == "ff") strPos = txtarea.selectionStart;

    var front = (txtarea.value).substring(0,strPos);
    var back = (txtarea.value).substring(strPos,txtarea.value.length);
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") {
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ("character", -txtarea.value.length);
        range.moveStart ("character", strPos);
        range.moveEnd ("character", 0);
        range.select();
    }
    else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}
// End - K_PasteHTMLAtCaretJS() -----------------------------------

function K_SaveSelection() {
    console.log("Save Selection");
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function K_RestoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}

// Delete Element Function ------------------------------------------
function DeleteElement(Elem){    // K_DBDocAdminJS()
    let Id = $(Elem).attr("data-docid");
    var formval  = {Id: Id};
    $.ajax(
        {
            type: "POST",
            url: "GetXML?FID=DeleteElement",
            dataType: "xml",
            data: formval,
            success: function(response)
            {
                ShowXMLError(response) ;
                if ($(response).find("Status" ).text() == "Success"){
                    $(Elem).remove();
                }
            },
            error:function (xhr, ajaxOptions, thrownError){
                ShowXMLError("XML Error: ("+xhr.status+") "+thrownError) ;
            }
        });

}

// K_PasteHTMLAtCaret() ---------------------------------------------
function K_PasteHTMLAtCaret(ContainerId, html) {
    let element = document.getElementById(ContainerId);
    element.focus();
    let doc     = element.ownerDocument || element.document ;
    let Window  = doc.defaultView       || doc.parentWindow ;
    let sel = Window.getSelection()
    let range = null ;
    if (sel) {
        sel = Window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            $("#"+ContainerId).attr("data-changed", "Y");

            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
        else {
            console.log("   *** ERROR - No RangeCount.");
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}
// End of K_PasteHTMLAtCaretJS() ------------------------------------

function K_GetSelectedText() {
    return window.getSelection().anchorNode.data.substring( window.getSelection().anchorOffset,window.getSelection().extentOffset )
}

function K_ReplaceSelectedHTML(replacementText) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        //range.text = replacementText;
        range.html = replacementText;
    }
}

function K_FormatPhone( key, PhoneNum ){
    // Example Use
    //      $("input[name=''Telephone'']").keyup(function(e) {
    //          ph = K_FormatPhone( e, $(this).val() );
    //          $(this).val(ph);
    //      });

    var ph = PhoneNum.replace(/\D/g,'').substring(0,10);
    // Backspace and Delete keys
    var deleteKey = (key.keyCode == 8 || key.keyCode == 46);
    var len = ph.length;
    if(len==0){
        ph=ph;
    }else if(len<3){
        ph='('+ph;
    }else if(len==3){
        ph = '('+ph + (deleteKey ? '' : ') ');
    }else if(len<6){
        ph='('+ph.substring(0,3)+') '+ph.substring(3,6);
    }else if(len==6){
        ph='('+ph.substring(0,3)+') '+ph.substring(3,6)+ (deleteKey ? '' : '-');
    }else{
        ph='('+ph.substring(0,3)+') '+ph.substring(3,6)+'-'+ph.substring(6,10);
    }
    return ph;
}

function K_ShowXMLError(response)
{
  var cType = typeof response ;
  if (cType == "string")
  { var cError = response }
  else{ var cError = $(response).find("XMLError").text() }
  if (cError == "")  // Clear the error
  {
    $("#XMLErrorDetail").html(""); 
    $("#XMLErrorDetail").hide(); 
  }
  else
  {
    $("#XMLErrorDetail").html(cError); 
    $("#XMLErrorDetail").show(); 
  }
  K_ShowXMLDebug($(response).find("XMLDebug").text())

}
function K_ShowXMLDebug(cDebug)
{
  $("#XMLDebug").html(cDebug); 
}

