/*!
 * CommonScript.js v1.0.1 - 2022-02-18  
 */

function hideElementById(fieldId, selectedValue, listOfIdsToHide) {
var fieldValue = $('#' + fieldId).val();
    if(fieldValue == selectedValue){
        if(listOfIdsToHide != null){
            for(let x = 0; x < listOfIdsToHide.length; x++)
	        {
	            $('#' + listOfIdsToHide[x]).hide();
	        }
        }
    }

}

function hideFields(fieldsToHide){
	for(let x = 0; x < fieldsToHide.length; x++)
	{
	    $('#' + fieldsToHide[x]).closest('td').hide();
	}
}

function showFields(fieldsToShow){
	for(let x = 0; x < fieldsToShow.length; x++)
	{
	    $('#' + fieldsToShow[x]).closest('td').show();
	}
}


function hideFieldsWhenChecked(checkboxId, fieldsToHide){
    if($('#' + checkboxId).is(':checked')){
	for(let x = 0; x < fieldsToHide.length; x++)
	{
	    $('#' + fieldsToHide[x]).closest('td').hide();
	}
    }	
    else{
	for(let x = 0; x < fieldsToHide.length; x++)
	{
	    $('#' + fieldsToHide[x]).closest('td').show();
	}
    }
}

function showFieldsWhenChecked(checkboxId, fieldsToShow){
    if($('#' + checkboxId).is(':checked')){
	for(let x = 0; x < fieldsToShow.length; x++)
	{
	    $('#' + fieldsToShow[x]).closest('td').show();
	}
    }	
    else{
	for(let x = 0; x < fieldsToShow.length; x++)
	{
	    $('#' + fieldsToShow[x]).closest('td').hide();
	}
    }
}

function hideAndShowFieldsWhenValueSelected(fieldId, selectedValue, fieldsToHide, fieldsToShow){
    var fieldValue = $('#' + fieldId).val();
    if(fieldValue == selectedValue){
        if(fieldsToHide != null){
            for(let x = 0; x < fieldsToHide.length; x++)
	        {
	            $('#' + fieldsToHide[x]).closest('td').hide();
	        }
        }

        if(fieldsToShow != null){
            for(let x = 0; x < fieldsToShow.length; x++)
	        {
	            $('#' + fieldsToShow[x]).closest('td').show();
	        }
        }
    }
}
function hideSectionForSpecifiedValue(fieldId, selectedValue, sectionsToHide){
	var fieldValue = $('#' + fieldId).val();
    	if(fieldValue == selectedValue){
        	if(sectionsToHide != null){
            		for(let x = 0; x < sectionsToHide.length; x++)
	        	{
	            		$("table[data-name='" + sectionsToHide[x] + "']").parent().hide();
	        	}
        	} 
	}
}

function hideSections(sectionsToHide){
     if(sectionsToHide != null){
            for(let x = 0; x < sectionsToHide.length; x++)
	    {
	        $("table[data-name='" + sectionsToHide[x] + "']").parent().hide();
	    }
     } 
}

function showSections(sectionsToShow){
    if(sectionsToShow != null){
           for(let x = 0; x < sectionsToShow.length; x++)
       {
           $("table[data-name='" + sectionsToShow[x] + "']").parent().show();
       }
    } 
}


function hideAndShowOptionSetValues(fieldId, listOfValuesToHide, listOfValuesToShow) {
    var fieldValue = $('#' + fieldId);
    if (fieldValue != undefined) {
        if (listOfValuesToHide != null) {
            for (let x = 0; x < listOfValuesToHide.length; x++) {
                if ($('#' + fieldId).is("select")) {
                    // is <select> dropdown
                    $('#' + fieldId + ' option[value=' + listOfValuesToHide[x] + ']').hide();
                }
                else if ($('#' + fieldId).is("span")) {
                    // handle vertical list metadata render
                    let $optionElement = $('#' + fieldId + ' [value=' + listOfValuesToHide[x] + ']')

                    // hide option
                    $optionElement.hide();

                    // hide label
                    $optionElement.next("label").hide();
                    $optionElement.next("label").next("br").hide();

                    // handle radio button metadata render
                    $optionElement.closest(".radio-container").hide();
                }
            }
        }
        if (listOfValuesToShow != null) {
            for (let x = 0; x < listOfValuesToShow.length; x++) {
                if ($('#' + fieldId).is("select")) {
                    // is <select> dropdown
                    $('#' + fieldId + ' option[value=' + listOfValuesToShow[x] + ']').show();
                }
                else if ($('#' + fieldId).is("span")) {
                    // handle vertical list metadata render

                    let $optionElement = $('#' + fieldId + ' [value=' + listOfValuesToShow[x] + ']')

                    // hide option
                    $optionElement.show();

                    // hide label
                    $optionElement.next("label").show();
                    $optionElement.next("label").next("br").show();

                    // handle radio button metadata render
                    $optionElement.closest(".radio-container").show();
                }
            }
        }
    }
}

function removeValidatorsForSpecifiedValue(fieldId, selectedValue, fieldNames) {
var fieldValue = $('#' + fieldId).val();
    	if(fieldValue == selectedValue){
    		for(let x = 0; x < fieldNames.length; x++)
    		{    
        		var fieldName = fieldNames[x];

        		if (typeof (Page_Validators) == 'undefined') return;
			if($("#RequiredFieldValidator" + fieldName) != undefined){
				$("#RequiredFieldValidator" + fieldName).remove();
			}
			if ($("#" + fieldName) != undefined) {
				$("#" + fieldName).closest(".control").prev().removeClass("required");
				$("#" + fieldName).prop('required', false);

				for (i = 0; i < Page_Validators.length; i++) {
					if (Page_Validators[i].id == "RequiredFieldValidator" + fieldName) {
						Page_Validators.splice(i, 1);
						
					}
				}
			}	
    	}
	}
}

function removeValidator(fieldNames) {
    for(let x = 0; x < fieldNames.length; x++)
    {    
        var fieldName = fieldNames[x];

	if (typeof (Page_Validators) == 'undefined') return;
	    if($("#RequiredFieldValidator" + fieldName) != undefined){
		    $("#RequiredFieldValidator" + fieldName).remove();
	    }
	    if ($("#" + fieldName) != undefined) {
		    $("#" + fieldName).closest(".control").prev().removeClass("required");
		    $("#" + fieldName).prop('required', false);

		    for (i = 0; i < Page_Validators.length; i++) {
			    if (Page_Validators[i].id == "RequiredFieldValidator" + fieldName ) {
				    Page_Validators.splice(i, 1);
			    }
		    }
	    }
    }
}


function addValidatorForSpecifiedValue(fieldId, selectedValue, fieldNamesAndLabels) {
    var fieldValue = $('#' + fieldId).val();
    	if(fieldValue == selectedValue){
            for(let x = 0; x < fieldNamesAndLabels.length; x++)
            {
                var fieldNameAndLabel = fieldNamesAndLabels[x];
                var fieldName = fieldNameAndLabel[0];
                var fieldLabel = fieldNameAndLabel[1];
		        var preCreatedValidator = false;

                    if (typeof (Page_Validators) == 'undefined') return;
                    for (i = 0; i < Page_Validators.length; i++) {
                        if (Page_Validators[i].id == "RequiredFieldValidator" + fieldName ) 
                        {
			                preCreatedValidator = true;
                            break;
                        }
                    }

		    if(preCreatedValidator == true){
			    continue;
		    }

                    // Create new validator
                    $("#" + fieldName + "_label").parent().addClass("required");

                    var newValidator = document.createElement('span');
                    newValidator.style.display = "none";
                    newValidator.id = "RequiredFieldValidator" + fieldName;
                    newValidator.controltovalidate = "casetypecode";
                    newValidator.errormessage = "<a href='#" + fieldName + "_label'>" + fieldLabel + " is a mandatory field.</a>";
                    newValidator.validationGroup = "";
                    newValidator.initialvalue = "";
                    newValidator.evaluationfunction = function (fieldName) {
			            var validatorId = fieldName.id;
			            validatorId = validatorId.replace("RequiredFieldValidator", "");
			            var value = GetValidatorValue(validatorId);
			            if (value == null || value == "") {
                            	return false;
                        } else {
                            	return true;
                        }
                        
                    };

                    // Add the new validator to the page validators array:
                    Page_Validators.push(newValidator);

                    // Wire-up the click event handler of the validation summary link
                    $("a[href='#" + fieldName + "_label']").on("click", function () { scrollToAndFocus(fieldName + '_label', fieldName); });
            }
        }
}



function addValidator(fieldNamesAndLabels) {
    	
            for(let x = 0; x < fieldNamesAndLabels.length; x++)
            {
                var fieldNameAndLabel = fieldNamesAndLabels[x];
                var fieldName = fieldNameAndLabel[0];
                var fieldLabel = fieldNameAndLabel[1];
		        var preCreatedValidator = false;

                    if (typeof (Page_Validators) == 'undefined')return;
                    for (i = 0; i < Page_Validators.length; i++) {
                        if (Page_Validators[i].id == "RequiredFieldValidator" + fieldName ) {
			                preCreatedValidator = true;
                            break;
                        }
                    }

		    if(preCreatedValidator == true){
			    continue;
		    }

                    // Create new validator
                    $("#" + fieldName + "_label").parent().addClass("required");

                    var newValidator = document.createElement('span');
                    newValidator.style.display = "none";
                    newValidator.id = "RequiredFieldValidator" + fieldName;
                    newValidator.controltovalidate = "casetypecode";
                    newValidator.errormessage = "<a href='#" + fieldName + "_label'>" + fieldLabel + " is a mandatory field.</a>";
                    newValidator.validationGroup = "";
                    newValidator.initialvalue = "";
                    newValidator.evaluationfunction = function (fieldName) {
                        var validatorId = fieldName.id;
			            validatorId  = validatorId.replace("RequiredFieldValidator", "");
			            var value = GetValidatorValue(validatorId);
			            if (value == null || value == "") {
                            	return false;
                        } else {
                            	return true;
                        }
                    };

                    // Add the new validator to the page validators array:
                    Page_Validators.push(newValidator);

                    // Wire-up the click event handler of the validation summary link
                    $("a[href='#" + fieldName + "_label']").on("click", function () { scrollToAndFocus(fieldName + '_label', fieldName); });
            }
     
}


// Add field requirement validator
function addValidatorNew(fieldName, fieldLabel, evaluationFunction, tabulated) {
    if (typeof (Page_Validators) == 'undefined') return;
        
    var isValidatorAlreadyAdded = Page_Validators.find(validator => validator.id == "RequiredFieldValidator" + fieldName);
	if (isValidatorAlreadyAdded != null) {
		return;
	}
    var defaultEvaluationFunction = function () {
        var value = $("#" + fieldName).val();
        if (value == null || value == "") {
            return false;
        } else {
            return true;
        }
    };
    evaluationFunction = evaluationFunction || defaultEvaluationFunction;
    // Create new validator
    $("#" + fieldName + "_label").parent().addClass("required");
    
    var newValidator = document.createElement('span');
    newValidator.style.display = "none";
    newValidator.id = "RequiredFieldValidator" + fieldName;
    // newValidator.controltovalidate = "casetypecode";
    if (tabulated) {
        // get tab this field is on and set tab a hash instead of field label
        console.log($("#" + fieldName).closest('.tab').data('name'));
        newValidator.errormessage = "<a onclick='scrollFocus(\"tabContent\")' href='#" + $("#" + fieldName).closest('.tab').data('name') +"'>" + fieldLabel + " is a required field.</a>";
    } else {
        newValidator.errormessage = "<a onclick='scrollToAndFocus("+fieldName + '_label,' +fieldName+")' href='#" + fieldName + "_label'>" + fieldLabel + " is a required field.</a>";
    }
    newValidator.validationGroup = "";
    newValidator.initialvalue = "";
    newValidator.controltovalidate = fieldName;
    newValidator.evaluationfunction = evaluationFunction;
    // Add the new validator to the page validators array:
    Page_Validators.push(newValidator);

    // Wire-up the click event handler of the validation summary link
    // if (tabulated) {
    //     console.log("a[href='#"+$("#" + fieldName).closest('.tab').data('name')+"']");
    //     // get tab this field is on and set tab a hash instead of field label
    //     $("a[href='#"+$("#" + fieldName).closest('.tab').data('name')+"']").on("click", function () { scrollFocus("tabContent"); });
    // } else {
    //     $("a[href='#" + fieldName + "_label']").on("click", function () { scrollToAndFocus(fieldName + '_label', fieldName); });
    // }
}

function scrollFocus(elementId) {
    const targetElement = document.getElementById(elementId);
    console.log(targetElement);
    if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth' });
        console.log("scrolling");
    }
  }

function GetValidatorValue(id) {
    var control;
    control = document.getElementById(id);
    if (typeof(control.value) == "string") {
        return control.value;
    }
    return GetValidatorValueRecursive(control);
}

function GetValidatorValueRecursive(control)
{
    if (typeof(control.value) == "string" && (control.type != "radio" || control.checked == true)) {
        return control.value;
    }
    var i, val;
    for (i = 0; i<control.childNodes.length; i++) {
        val = ValidatorGetValueRecursive(control.childNodes[i]);
        if (val != "") return val;
    }
    return "";
}

/**
 * Formats the given number into a '$x.xx' formatted string.
 * 
 * @param {number} amount The amount to format.
 */
function transformIntoCurrencyFormat(amount) {
    if (isNaN(amount)) {
        amount = 0;F
    }

    return '$' + amount.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

/**
 * Converts a Microsoft.Xrm.Sdk.Money data-type string into a number.
 * 
 * @param {string} value  The input to convert.
 */
function convertMoneyStringToNumber(value) {
    value = value.replace("$", "").replace(/,/g, ""); 

    if (value.indexOf("(") > -1) {
        // contains () which signifies a negative number
        value = value.replace("(", "").replace(")", "");
        value *= -1;
    }

    var amt = parseFloat(value);

    return !isNaN(amt) ? amt : 0;
}

function displayErrorAlert(errorMessage) {
    var $container = $(".notifications");
    if ($container.length == 0) {
        var $pageheader = $(".page-heading");
        if ($pageheader.length == 0) {
            $container = $("<div class='notifications'></div>").prependTo($("#content-container"));
        } else {
            $container = $("<div class='notifications'></div>").appendTo($pageheader);
        }
    }
    $container.find(".notification").slideUp().remove();
    var $alert = $(
        "<div class='notification alert alert-danger error alert-dismissible' role='alert'>" +
        "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>" +
        "<span aria-hidden='true'>&times;</span>" +
        "</button>" +
        "<span class='fa fa-exclamation-triangle' aria-hidden='true'></span> "
        + errorMessage +
        "</div > ")
        .on('closed.bs.alert', function () {
            if ($container.find(".notification").length == 0) {
                $container.hide();
            }
        }).prependTo($container);
    $container.show();
    $('html, body').animate({
        scrollTop: ($alert.offset().top - 20)
    }, 200);
}

function customValidator(id, control, errorMessage, evaluationFunction) {
    if (typeof(Page_Validators) == 'undefined') return;

    var newValidator = document.createElement('span');
    newValidator.style.display = "none";
    newValidator.id = id;
    newValidator.controltovalidate = control;
    newValidator.errormessage = "<a href='#previousApplication_label'>" + errorMessage + "</a>";
    newValidator.validationGroup = "";
    newValidator.initialvalue = "";
    newValidator.evaluationfunction = function(){
	var result = evaluationFunction();
	return result;
	};
    // Add the new validator to the page validators array:
    Page_Validators.push(newValidator);
}

function formatSSN(field){

    var fieldVal = $('#' + field).val();

	var ssnExpression =  new RegExp("^\d{3}-\d{2}-\d{4}$");
    var result = ssnExpression.test(fieldVal);

    if(result == false){
        if(fieldVal.length == 9){
            var formattedValue = fieldVal.substring(0,3) + "-" + fieldVal.substring(3,5) + "-" + fieldVal.substring(5,9);

            if(formattedValue != fieldVal){
                $('#' + field).val(formattedValue);
            } 
        }
    }
}

function prependSymbolToInput(inputId, symbol) {
    // Add Bootstrap classes for styling
  if (!$("#" + inputId).prev(".input-group-addon").length) {
      // Add Bootstrap classes for styling
      $("#" + inputId).closest("div").addClass("input-group");
  
      // Insert the specified symbol before the input field
      $('<span tabindex="0" class="input-group-addon">' + symbol + '</span>').insertBefore('#' + inputId);
      console.log("Concatenated Symbol: " + symbol);
    }
  }

  function appendSymbolToInput(inputId, symbol) {
    // Add Bootstrap classes for styling
    var inputField = $("#" + inputId);
    
    if (!inputField.prev(".input-group-addon").length) {
        // Add Bootstrap classes for styling
        inputField.closest("div").addClass("input-group");

        // Insert the specified symbol after the input field
        $('<span tabindex="0" class="input-group-addon">' + symbol + '</span>').insertAfter(inputField);
        console.log("Concatenated Symbol: " + symbol);
    }
    }

    function prependSymbolToCurrencyFields(symbol) {
        // Select all elements with the specified classes
        $(".text.money.form-control").each(function() {
            // Add Bootstrap classes for styling
            if (!$(this).prev(".input-group-addon").length) {
                // Add Bootstrap classes for styling
                $(this).closest("div").addClass("input-group");
    
                // Insert the specified symbol before the input field
                $('<span tabindex="0" class="input-group-addon">' + symbol + '</span>').insertBefore($(this));
                console.log("Concatenated Symbol: " + symbol);
            }
        });
    }

  function RenderTabs() {
    // get tab headers from form render
    var tabHeaders = [];
    $(".tab-title").each(function () {
        tabHeaders.push($(this));
    });

    // build tab components
    $("#EntityFormPanel .entity-form").prepend("<ul id='tabNav' class='nav nav-tabs'></ul>"); // add tab nav <ul> 
    //$(".validation-summary").append("<ul id='tabNav' class='nav nav-tabs'></ul>"); // add tab nav <ul> element
    $("#tabNav").after("<div id='tabContent' class='tab-content'></div>"); // add tab content container

    $.each(tabHeaders, function (index, value) {
        var tabId = value.text().replaceAll(" ", "").replaceAll("/", "");
        $("#tabNav").append("<li id='" + tabId + "TabHeader'><a data-toggle='tab' href='#" + tabId + "'>" + value.text() + "</a></li>"); // add tab header item
        $("#tabContent").append("<div id='" + tabId + "' class='tab-pane fade'></div>"); // add tab content item

        value.next("div.tab").detach().appendTo("#" + tabId + ""); // move form tab content to content container
        value.addClass("hide");// hide original form tab headers
    });

    // make first tab the active one
    $("#tabNav li a").first().click();

}

function radioButtonsStyling(){
    var radioButtons = document.querySelectorAll(".picklist.horizontal input[type='radio']");
    
    // Loop through each radio button and add margin to create spacing
    for (var i = 0; i < radioButtons.length; i++) {
        radioButtons[i].nextElementSibling.style.marginRight = "10px"; 
    }
      
}

function LoadAndSaveLastTabOpened() {
    
    // load and save last tab opened 
    if (location.hash) {
        $("a[href='" + location.hash + "']").tab("show");
    }
    $(document.body).on("click", "a[data-toggle='tab']", function (event) {
        location.hash = this.getAttribute("href");
    });

}

function showLastTabOpened(){
    var urlParams = new URLSearchParams(location.search);
	var tabParam = urlParams.get('tab');
	$("a[href='#" + tabParam + "']").tab("show");
	
    $(window).on("popstate", function () {
        var anchor = location.hash || $("a[data-toggle='tab']").first().attr("href");
        $("a[href='" + anchor + "']").tab("show");
    });
    
}

function hideTabs(tabNames) {
    tabNames.forEach(function(tabName) {
        $(".tab[data-name='" + tabName + "']").hide();
        $(".tab[data-name='" + tabName + "']").prev().hide(); 
        $("#" + tabName + "TabHeader").hide();
    });
  }
  
  function showTabs(tabNames) {
    tabNames.forEach(function(tabName) {
        $(".tab[data-name='" + tabName + "']").show();
        $(".tab[data-name='" + tabName + "']").prev().show(); 
        $("#" + tabName + "TabHeader").show();
    });
  }