



// **********************************************************
function submitValidateFormAjaxNew5C(cntrl, form, target, action, tagger) {

   // alert( cntrl + "-" + form + "-" + target + "-" + action + "-" );
    block_screen('11');

    if ( form == '' ) {
        form = 'smart_form';
    }

    $("#" + form ).attr("action", "" + cntrl);


    if (( action != null ) && ( action != '' )) {
        $("#" + form + " #action").val(action);
    }
    if (( target != null ) && ( target != '' )) {
        $("#" + form + " #forward").val(target);
    }
    if (( tagger != null ) && ( tagger != '' )) {
        $("#" + form + " #tagger").val(tagger);
    }


    let serialized_form = $('#' + form).serialize();

    debugger;


    $.ajax(
        {
            type:"post",
            url: cntrl ,
            data:$('#' + form).serialize(),

            success:function (response) {

                unblock_screen('X');

                var result = response;

                debugger;

                if ( result == null ) {
                    form_set_message(form, "ERROR - #4876740 processing your request, please call (919) 948-0758", null);
                }

                else if ( result.status == 'ok' ) {

                    // alert("hello: 2121" + target);

                    $("#" + form + " #validate").val("off");

                    if ( target == "dialog2" ) {
                        if (( result.html_id != null ) && ( result.html_body != null )) {
                            $('#' + result.html_id).html(result.html_body);
                        }
                        hideDialog('dialog_generic');
                        submitFormForward(form, target);
                    } else if ( target == "dialog3" ) {
                        // alert("hello: 2122" + target + form);
                        hideDialog('dialog_generic');
                        submitFormForwardNoBlock(form, target);
                    } else {
                        submitFormForward(form, target);
                    }
                }  else {
                    form_set_message(form, result.message, result.msg);

                    //  WHAT DOES THIS DO...  set a field value
                    if ( result.field_id != null ) {
                        $("#" + form + " #" + result.field_id ).val(result.field_value);
                    }

                    //  NOTE: code to highlight "bad" field in red
                    if ( result.field != null ) {
                        $("#" + form + " #" + result.field).css('background-color', 'lightcoral');
                    }
                }
            },
            error:function (x, status, errorThrown) {
                unblock_screen('X');
                if (status == "error") {
                    form_set_message(form, "ERROR - #4876766 processing your request, please call (919) 948-0758", null);
                }
            }
        }
    );
    return true;
}

function form_set_message(form, message, msg) {

    if ( message != null ) {
        $('#' + form + ' #messagefieldtop').html(message);
        $('#' + form + ' #messagefieldbottom').html(message);
    } else if ( msg != null ) {
        $('#' + form + ' #messagefieldtop').html(msg);
        $('#' + form + ' #messagefieldbottom').html(msg);
    } else {
        $('#' + form + ' #messagefieldtop').html("ERROR - #4876750 processing your request, please call (919) 948-0758");
        $('#' + form + ' #messagefieldbottom').html("ERROR - #4876750 processing your request, please call (919) 948-0758");
    }

}

function submitForm(formId) {
    block_screen('12');
    //$.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 12</p></div>' });

    var theForm = $("#" + formId);
    if (theForm) {
        theForm.submit();
    }
    return false;
}

function submitFormTarget(formId) {
    var theForm = $("#" + formId);
    if (theForm) {
        theForm.submit();
    }
    hideDialog("dialog_generic");
}

function submitFormForward(formId, forward) {
    //block_screen('13');
    block_screen('Submitting');

    var theForm = $("#" + formId);
    $("#" + formId + " #forward").val(forward);
    if (theForm) {
        theForm.submit();
    }
    return false;
}

function submitFormForwardNoBlock(formId, forward) {
    var theForm = $("#" + formId);
    $("#" + formId + " #forward").val(forward);
    if (theForm) {
        theForm.submit();
    }
    return false;
}

function submitFormActionCntrl(formId, action, cntrl) {

    var y = $("#" + formId + " #action");
    var ylen = y.length;
    if (ylen == 0 ) {
        y = $("#action");
    }
    y.val(action);

    var y = $("#"+formId+"_action");
    var ylen = y.length;
    if (ylen == 0 ) {
    }
    y.val(action);

    $("#" + formId ).attr("action", cntrl);

    block_screen('14');
    //$.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 14</p></div>' });

    var theForm = $("#" + formId);
    if (theForm) {  theForm.submit(); }
    return false;
}

function submitFormAction(formId, action) {
    var y = $("#" + formId + " #action");
    var ylen = y.length;
    if ( ylen == 0 ) {
        y = $("#action");
    }
    y.val(action);

    var theForm = $("#" + formId);
    if (theForm) { theForm.submit(); }
    return false;
}

function submitFormActionBlock(formId, action) {
    var y = $('#' + formId + ' #action');
    var ylen = y.length;
    if ( ylen == 0 ) {
        y = $('#action');
    }
    y.val(action);

    var theForm = $('#' + formId);
    if (theForm) {
        //$.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 15</p></div>' });
        block_screen('15');
        theForm.submit();
    }
    return false;
}

function submitUrl(url) {
    window.location = url;
    return false;
}

function submitUrlTest(url) {
    window.location = url;
    return false;
}

function submitUrlBlock(url) {
block_screen('16');
    window.location = url;
    return false;
}

function submitUrlParent(url) {
    window.parent.location = url;
    return false;
}

function submitUrlTarget(url) {
    newwindow = window.open(url,'_blank', '');
    newwindow.focus();
    return false;
}

function submitUrlWithField(url, field) {
    var val = $("#" + field).val();
    window.location = url + '&' + field + '=' + val;
    return false;
}

function toggleReply(mid) {
    var ele = document.getElementById(mid);
    var reply = document.getElementById(mid.concat('_reply'));

    if (ele.style.display == 'block') {
        ele.style.display = 'none';
        reply.style.display = 'block';
    }
    else {
        ele.style.display = 'block';
        reply.style.display = 'none';
    }
}



function hideDiv(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "none";
    }
}

function showDiv(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "block";
    }
}

function showDivInline(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "inline";
    }
}

function showDivInlineblock(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "inline-block";
    }
}


function toggleDivButton(mid, button) {

    var ele = document.getElementById(mid);
    var btn = document.getElementById(button);
    if ( ele == null )
        return false;
    if (ele.style.display != "none")
        btn.style.backgroundColor = "#0d6efd";
    else
        btn.style.backgroundColor = "#cccccc";

    toggleDiv(mid);
    return false;
}


function toggleDiv(mid) {
    var ele = document.getElementById(mid);
    if ( ele == null )
        return false;
    if (ele.style.display != "none")
        ele.style.display = "none";
    else
        ele.style.display = "block";
    return false;
}

//  06May2022 KylaQuestion - can we delete this? It looks identical to showDiv
function toggleDivOn(mid) {
    var ele = document.getElementById(mid);
    if ( ele == null )  return false;
    ele.style.display = "block";
    return false;
}

//  06May2022 KylaQuestion - can we delete this? It looks identical to hideDiv
function toggleDivOff(mid) {
    var ele = document.getElementById(mid);
    if ( ele == null )  return false;

    ele.style.display = "none";
    return false;
}

function toggleDivInline(mid) {

    var ele = document.getElementById(mid);
    if ( ele == null )
        return false;

    if (ele.style.display != "none")
        ele.style.display = "none";
    else
        ele.style.display = "inline";

    return false;
}

function toggleDivInlineBlock(mid) {
    var ele = document.getElementById(mid);
    if ( ele == null )
        return false;

    if (ele.style.display != "none")
        ele.style.display = "none";
    else
        ele.style.display = "inline-block";

    return false;
}

function toggleDivType(mid,typex) {
    var ele = document.getElementById(mid);
    if ( ele == null )  return false;

    if ( ele.style.display != "none" )  ele.style.display = "none";
    else  ele.style.display = typex;

    return false;
}

//  06May2022 KylaQuestion - should this be "show" not "toggle"? Can we make this and the typex fnc consistent?
function toggleDivInlineState(mid, state) {
    var ele = document.getElementById(mid);
    if ( ele == null )  return false;

    ele.style.display = state;
    return false;
}

function toggleDivFade(mid, button_id) {

    var element = document.getElementById( button_id );

    var ele = document.getElementById(mid);
    if ( ele == null )
        return false;

    if (ele.style.display != "none") {
        ele.style.display = "none";
        element.style.opacity = "0.9";

    } else {
        ele.style.display = "block";
        element.style.opacity = "0.3";
    }
    return false;
}



function showTr(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "";
    }
}

function hideTR(mid) {
    var ele = document.getElementById(mid);
    if ( ele == null )  return false;

    ele.style.display = "none";

    return false;
}

function showTR(mid) {
    var ele = document.getElementById(mid);
    if ( ele == null )  return false;

    ele.style.display = "table-row";

    return false;
}

function toggleTR(mid) {

    var ele = document.getElementById(mid);
    if ( ele == null )
        return false;

    if (ele.style.display != "none")  ele.style.display = "none";
    else  ele.style.display = "table-row";

    return false;
}


function toggleObject(mid, display) {

    var ele = document.getElementById(mid);
    if ( ele == null )
        return false;

    if (ele.style.display != "none")
        ele.style.display = "none";
    else
        ele.style.display = display;

    return false;
}


function visibileDiv(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.visibility = "visible";
    }
}





function showDialog(divId) {
    $('body,html').animate({scrollTop:0}, 800);
    centerPopup(divId);
    loadPopup(divId);
    return(true);
}

function hideDialog(divId) {

    if (isModalPopup(divId)) {
        $("#modalBackgroundPopup").fadeOut("slow");
        $('#' + divId).fadeOut("slow");

        $("#modalBackgroundPopupX").fadeOut("slow");
        $('#' + divId).fadeOut("slow");

    } else {
        $("#backgroundPopup").fadeOut("slow");
        $('#' + divId).fadeOut("slow");
    }

}

function showDialogNoBlock(divId) {
    $('body,html').animate({scrollTop:0}, 800);
    centerPopup(divId);
    //  loadPopup(divId);
    return(true);
}



function showPopup(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "block";
        showDialog(divId);
    }
    return false;
}

function hidePopup(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "none";
        hideDialog(divId);
    }
    return false;
}

function showPopupNoBlock(divId) {

    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "block";
        showDialogNoBlock(divId);
    }
    return false;
}

function showPopupNoScroll(divId) {
    var ele = document.getElementById(divId);
    if (ele) {
        ele.style.display = "block";
        centerPopupNoScroll(divId);
        loadPopup(divId);
    }
    return false;
}

//centering popup
function centerPopup(divId) {

    var _isModalPopup = isModalPopup(divId);
    //request data for centering
    var isInIFrame = (window.location != window.parent.location) ? true : false;
    var div = $('#' + divId);

    var windowWidth = $(window).width();
    var parentWidth = div.parent().width();
    var parentTop = 0;
    var windowHeight = $(window).height();
    if ( windowHeight > 800 ) {
        windowHeight = 400;
    }

    var parentHeight = div.parent().height();
    var popupHeight = div.height();
    var popupWidth = div.width();

    var top = windowHeight / 2 - popupHeight / 2;
    // 09Dec - DLB - moved down by 200 for the new coreui... should still work
//    top = top - 100;
    top = top + 100;



    if ( parentTop > 0 ) {
 //       top = top - parentTop;
 //       top = parentTop;
    }


    //alert( "centerPopup: " + popupWidth);

    if ( popupWidth < 100 ) {
        popupWidth = 100;
    }


/*
    if (isInIFrame) {
        window.parent.scroll(0,0);
    }
*/
//    alert( "Top: " + top);
//    alert( "isInIFrame: " + isInIFrame);
    if (top < 0 || isInIFrame) {
        top = 100;
//        alert( "Top: " + top);
    }

    //alert( "centerPopup pw: " + parentWidth);
    var left = windowWidth / 2 - popupWidth / 2;
    //alert( "centerPopup LEft1: " + left);
    if ((_isModalPopup || true) && (parentWidth > 10)) {
        left = parentWidth / 2 - popupWidth / 2;
        //alert( "centerPopup LEft2: " + left);
    }
    left -= 20;

    // alert( "centerPopup ww: " +   windowWidth);
    // alert( "centerPopup LEft: " + left);

    // alert( "top: " + top);

    if ( (windowWidth < 525 ) ) {

        //centering
        $('#' + divId).css({
            "position":"fixed",
            "top":0,
            "left":0,
            "width":"100%",
            "height":"100%",
            "border-width":"0px",
            "border-radius": "0px",
            "-moz-border-radius": "0px",
            "-khtml-border-radius": "0px"
        });


    } else {

        //centering
        $('#' + divId).css({
//        "position":"fixed",
            "position":"absolute",
            "top":top,
            "left":left
        });

    }



    windowHeight = parentHeight;

    if (_isModalPopup) {
        $("#modalBackgroundPopup").css({
              "height":"100%"
        });

        $("#modalBackgroundPopupX").css({
            "height":"100%"
        });

    } else {
        $("#backgroundPopup").css({
            "height":"100%"
        });
    }
}


function centerPopupNoScroll(divId) {

    var test_alert_flag = false;

    var _isModalPopup = isModalPopup(divId);
    //request data for centering
    var isInIFrame = (window.location != window.parent.location) ? true : false;
    var ddiv = $('#' + divId);
    //if (ddiv == null)  alert( "ddiv is null");
    //alert("ddiv id: " + ddiv.attr('id'));
    var pdiv = ddiv.parent();
    //if (pdiv == null)  alert( "pdiv is null");
    //alert("pdiv id: " + pdiv.attr('id'));


    var parentTop = 0;
    var windowHeight = $(window).height();
    if ( windowHeight > 800 ) {
        windowHeight = 800;
    }

    var parentHeight = ddiv.parent().height();
    var popupHeight = ddiv.height();

    if ( test_alert_flag )  alert("windowHeight: " + windowHeight);
    if ( test_alert_flag )  alert("parentHeight: " + parentHeight);
    if ( test_alert_flag )  alert("popupHeight: " + popupHeight);

    // 2022/2/17 - DAVE - using parent
    var top = windowHeight / 2 - popupHeight / 2;
    if ( false && ( _isModalPopup || true )) {
        top = parentHeight / 2 - popupHeight / 2;
    }

    if ( test_alert_flag )  alert("top1: " + top);
    // 2022/2/17 - DAVE - taking this out.
    // top = top - 100;
    if ( test_alert_flag )  alert("top2: " + top);
    if ( top < 100 ) {
        top = 100;
    }

    if ( test_alert_flag )  alert("top3: " + top);

    if (top < 0 || isInIFrame) {
        top = 100;
    }
    if ( test_alert_flag )  alert("top4: " + top);


    var windowWidth = $(window).width();
    var parentWidth = ddiv.parent().width();
    var popupWidth = ddiv.width();

    if ( test_alert_flag )  alert("windowWidth: " + windowWidth);
    if ( test_alert_flag )  alert("parentWidth: " + parentWidth);
    if ( test_alert_flag )  alert("popupWidth1: " + popupWidth);


    if ( popupWidth < 100 ) {
        popupWidth = 100;
    }

    if ( test_alert_flag )  alert("popupWidth2: " + popupWidth);

    var left = windowWidth / 2 - popupWidth / 2;
    if ((_isModalPopup || true) && false)  {
        left = parentWidth / 2 - popupWidth / 2;
    }
    // left -= 20;
    if ( test_alert_flag ) alert("left: " + left);

    if ( windowWidth < 525 ) {
        $('#' + divId).css({
            "position":"fixed",
            "top":0,
            "left":0,
            "width":"100%",
            "height":"100%",
            "border-width":"0px",
            "border-radius": "0px",
            "-moz-border-radius": "0px",
            "-khtml-border-radius": "0px"
        });
    } else {

        //centering
        $('#' + divId).css({
        "position":"fixed",
//            "position":"absolute",
            "top":top,
            "left":left
        });

    }



    windowHeight = parentHeight;


    if (_isModalPopup) {
        $("#modalBackgroundPopup").css({
            "height":"100%"
        });

        $("#modalBackgroundPopupX").css({
            "height":"100%"
        });

    } else {
        $("#backgroundPopup").css({
            "height":"100%"
        });
    }
}

//centering popup
function centerPopup2(divId) {
    var _isModalPopup = isModalPopup(divId);
    //request data for centering
    var isInIFrame = (window.location != window.parent.location) ? true : false;
    var div = $('#' + divId);

    var windowWidth = $(window).width();
    var parentWidth = div.parent().width();
    var windowHeight = $(window).height();
    var parentHeight = div.parent().height();
    var popupHeight = div.height();
    var popupWidth = div.width();
    var top = windowHeight / 2 - popupHeight / 2;


    if ( popupWidth < 100 ) {
        popupWidth = 100;
    }


    if (top < 0 || isInIFrame) {
        top = 20;
    }

    var left = windowWidth / 2 - popupWidth / 2;
    if (_isModalPopup) {
        left = parentWidth / 2 - popupWidth / 2;
    }
    left -= 20;

    //centering
    $('#' + divId).css({
        "position":"absolute",
        "top":top,
        "left":left
    });


    windowHeight = parentHeight;

    if (_isModalPopup) {
        $("#modalBackgroundPopup").css({
            "height":windowHeight
        });

        $("#modalBackgroundPopupX").css({
            "height":windowHeight
        });

    } else {
        $("#backgroundPopup").css({
            "height":windowHeight
        });
    }
}






//SETTING UP OUR POPUP
//loading popup with jQuery magic!
function loadPopup(divId) {

    //loads popup only if it is disabled
    if (isModalPopup(divId)) {
        $("#modalBackgroundPopup").css({
            "opacity":"0.5"
        });
        $("#modalBackgroundPopup").fadeIn("slow");
        $('#' + divId).fadeIn("slow");

/* UU */
        $("#modalBackgroundPopupX").css({
            "opacity":"0.5"
        });
        $("#modalBackgroundPopupX").fadeIn("slow");
        $('#' + divId).fadeIn("slow");


    } else {
        $("#backgroundPopup").css({
            "opacity":"0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $('#' + divId).fadeIn("slow");
    }
}

//disabling popup with jQuery magic!
/*
function disablePopup(divId) {
    if (isModalPopup(divId)) {
        $("#modalBackgroundPopup").fadeOut("slow");
        $('#' + divId).fadeOut("slow");
    } else {
        $("#backgroundPopup").fadeOut("slow");
        $('#' + divId).fadeOut("slow");
    }
}
*/


function isModalPopup(divId) {
    var _isModalPopup = false;
    var classList = $("#" + divId).attr('class').split(/\s+/);
    for (var i = 0; i < classList.length; i++) {
        if (classList[i] === 'modal_popup_full') {
            _isModalPopup = true;
            break;
        }
    }
    return _isModalPopup;
}


function unlockRewardWidget(rewardId, userId, eventId, status, format ) {
    block_screen('18');
    //$.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 18</p></div>' });

    $("#master_function_widget").val(status);
    var form = $("#form_multipost").serialize();

    $.ajax({
        type:'post',
        url:'/rx/events_controller.php',
        data: form,

        success:function (response) {
            unblock_screen('X');
            var result = response;


            if (result.status == 'ok') {

                var o;
                var testWin =  window.opener;

                if (result.html ==  null) {
                    if (format == 'popup') {
                        document.location.reload(true);
                    } else if (format == 'now') {
                        document.location ="now.php?eventid=" + eventId;
                    } else {
                        close();
                    }
                } else {

                    $('#div_multishare_inner').html(response.html);
                }
            }
        },
        error:function (response) {
            // do nothing
            unblock_screen('X');
            alert('Error - call (919) 948-0758 ' + response);

        }
    });
}


function showMultipost(eventId) {
    $('#dialog_multishare').html('<h3 style="margin-left:10px;"><img src="/rx/images/busy.gif" /> Just a moment...</h3>');

    showPopup('dialog_multishare');

    ajax = $.ajax({
        type: 'GET',
        url: '/rx/events_controller.php',
        data: {action : 'multipost', eventid : eventId, format : 'popup' },
        success: function(response) {
            $('#dialog_multishare').html(response);
            showPopup('dialog_multishare');
        },
        error: function(response) {
            $('#dialog_multishare').html('<span style="color:red" class="smallText">There was an error processing this request (#8342213) please call (919) 948-0758.</span>');
            showPopup('dialog_multishare');
        }
    });
    return;
}

function showMultipostReward(eventId, rewardId, groupId) {
    $('#dialog_multishare').html('<h3 style="margin-left:10px;"><img src="/rx/images/busy.gif" /> Just a moment...</h3>');
    showPopup('dialog_multishare');

    ajax = $.ajax({
        type: 'GET',
        url: 'rx/events_controller.php',
        data: {action : 'multipost', eventid : eventId, rewardid : rewardId, groupid : groupId, format : 'popup' },
        success: function(response) {
            $('#dialog_multishare').html(response);
            showPopup('dialog_multishare');
        },
        error: function(response) {
            $('#dialog_multishare').html('<span style="color:red" class="smallText">There was an error processing this request (#8342214) please call (919) 948-0758.</span>');
            showPopup('dialog_multishare');
        }
    });
    return;
}

function loadHtml( divid,  url ) {

    block_screen('19');
    //$.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 19</p></div>' });

    var divNeeded = $('#' + divid);
    ajax = $.ajax({
        type: 'GET',
        url: 'master_controller.php',
        data: url,

        success: function(response) {
            $('#' + divid).html(response);
 //           hideDialog("dialog_generic");
            unblock_screen('X');
        },
        error: function(response) {
            unblock_screen('X');
            $('#dialog_generic').html('<span style="color:red" class="smallText">There was an error processing this request (#8342215) please call (919) 948-0758.</span>');
            showPopup( "dialog_generic" );
        }
    });
    return;
}

// COMPARE WITH ABOVE
function smartLoadDiv(divid, urlx) {
    var divNeeded = $('#' + divid);
    ajax = $.ajax({
        type: 'GET',
        url: 'master_controller.php',
        data: 'action=smartloaddiv&' + urlx,

        success: function(response) {
            $('#' + divid).html(response);
        },
        error: function(response) {
            $('#' + divid).html('<span style="color:red" class="smallText">There was an error processing this request (#8342216) please call (919) 948-0758.</span>');
        }
    });
    return;
}

function load_html_form( divid,  form ) {

    block_screen('20');
    //$.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 20</p></div>' });

    if ( form == '' ) {
        form = 'smart_form';
    }

    var formElement = document.getElementById(form);
    var formData = new FormData(formElement);


    $.ajax(
        {
            type:"post",
            url:"/master_controller.php",

            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,


            success:function (response) {

                $('#' + divid).html(response);
                //           hideDialog("dialog_generic");
                unblock_screen('X');
            },
            error:function (x, status, errorThrown) {
                unblock_screen('X');
                if (status == "error") {
                    $('#' + form + ' #messagefieldtop').html("ERROR - #8756502 processing your request, please call (919) 948-0758");
                    $('#' + form + ' #messagefieldbottom').html("ERROR - #8756503 processing your request, please call (919) 948-0758");
                }
            }
        }
    );
    return true;
}


function dialog_load_controller(url, controller) {

    if ( controller == '' ) {
        controller = "/rx/master_controller.php"
    }

    showPopup("dialog_generic");

    ajax = $.ajax({
        type: 'GET',
        url: controller,
        data: 'action=smart_load&' + url,
        success: function(response) {

            $('#dialog_generic').html(response);
            showPopup("dialog_generic");

        },
        error: function(response) {

            $('#dialog_generic').html('<span style="color:red" class="smallText">There was an error processing this request (#8342217) please call (919) 948-0758.</span>');
            showPopup( "dialog_generic" );
        }
    });

    return;
}


function dialog_load(url) {
    // alert("Hello World - 781213123");
    $('#dialog_generic').html('<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" />' +
        '<p style="color:#469BCF;">One Moment (Pulling up information)</p></div>');

    showPopup('dialog_generic');

    ajax = $.ajax({
        type: 'GET',
        url: '/rx/master_controller.php',
        data: 'action=smart_load&' + url,
        success: function(response) {

            $('#dialog_generic').html(response);

            showPopup('dialog_generic');
            // setBlur();
        },
        error: function(response) {
            $('#dialog_generic').html('<span style="color:red" class="smallText">There was an error processing this request (#83422175) please call (919) 948-0758.</span>');
            showPopup('dialog_generic');
        }
    });

    return;
}



function dialog_load_noblock(url) {

    $('#dialog_generic').html('<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment</p></div>');

    showPopupNoBlock("dialog_generic");

    ajax = $.ajax({
        type: 'GET',
        url: '/rx/master_controller.php',
        data: 'action=smart_load&' + url,
        success: function(response) {
            $('#dialog_generic').html(response);
            showPopupNoBlock('dialog_generic');
            // setBlur();
        },
        error: function(response) {
            $('#dialog_generic').html('<span style="color:red" class="smallText">There was an error processing this request (#8342300) please call (919) 948-0758.</span>');
            showPopup('dialog_generic');
        }
    });

    return;
}



function dialog_load_noscroll(url) {

    $('#dialog_generic').html('<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment</p></div>');

    showPopupNoScroll("dialog_generic");

    ajax = $.ajax({
        type: 'GET',
        url: '/rx/master_controller.php',
        data: 'action=smart_load&' + url,
        success: function(response) {
            $('#dialog_generic').html(response);
            showPopupNoScroll("dialog_generic");
        },
        error: function(response) {
            $('#dialog_generic').html('<span style="color:red" class="smallText">There was an error processing this request (#8342301) please call (919) 948-0758.</span>');
            showPopupNoScroll("dialog_generic");
        }
    });
    return;
}


function submitEmail3(form, gqs, controller) {

    // alert( "Hello: submitEmail3");

    block_screen('22');
    var tstr = $('#' + form).serialize();
    var tone = '';

    $.ajax(
        {
            type:'get',
            url: controller ,
            data: tstr,

            // data: 'action=smart_load&test=78we',
            success:function (response) {
                unblock_screen('X');

                var result = response;
                if ( result.status == 'ok' ) {
                    $('#signinmessage').html('');
                    $('#dynamic_body').html(result.html);
                    $('#password_d').focus();
                    return true;
                } else if ( result.status == 'reg' ) {
                    $('#signinmessage').html('');
                    var user_id = "";
                    if (result.user_id != null )
                        user_id = result.user_id;
                    dialog_load_controller( gqs + "&user_id=" + user_id , controller );
                    return true;
                }  else {
                    $('#signinmessage').html(result.msg);
                }
            },
            error:function (x, status, errorThrown) {
                unblock_screen('X');
                if (status == "error") {
                    var errorMsg = "";
                    if (errorThrown) {
                        errorMsg = errorThrown;
                    }
                    alert("The call to the server side failed. " + errorMsg);
                }
            }
        }
    );
    return true;
}


function submitEmail4(form, gqs, controller) {

    // alert( "Hello: submitEmail4");

    block_screen('221');
    var tstr = $('#' + form).serialize();
    var tone = '';
    var user_id = '';
    var emailv = '';

    $.ajax(
        {
            type:'get',
            url: controller ,
            data: tstr,

            success:function (response) {
                unblock_screen('221s');

                var result = response;
                if ( result.status == 'ok' ) {

                    if (result.user_id != null ) user_id = result.user_id;
                    if (result.emailv != null ) emailv = result.emailv;

                    dialog_load_controller( gqs + "&load=connect4pwd&user_id=" + user_id + "&connectemail=" + encodeURIComponent(emailv) , controller );

                    return true;

                } else if ( result.status == 'reg' ) {

                    $('#signinmessage').html('');

                    if (result.user_id != null ) user_id = result.user_id;
                    if (result.emailv != null ) emailv = result.emailv;
                    dialog_load_controller( gqs + "&load=connect4reg&user_id=" + user_id + "&connectemail=" + emailv, controller );
                    return true;
                }  else {
                    $('#signinmessage').html(result.msg);
                }
            },
            error: function (x, status, errorThrown) {
                unblock_screen('221e');
                if (status == "error") {
                    var errorMsg = "";
                    if (errorThrown) {
                        errorMsg = errorThrown;
                    }
                    // alert("The call to the server side failed (#3213312). [" + form + "][" + gqs +  "][" + controller + "]:" + errorMsg);
                    // alert("The call to the server side failed (#3213312). [" + tstr + "][" + gqs +  "][" + controller + "]:" + errorMsg);
                    alert("The call to the server side failed (#3213312). :" + errorMsg);
                }
            }
        }
    );
    return true;
}


function submitEmailPage(form, gqs, controller) {

    alert( "Hello: submitEmailPage");

    block_screen('721');

    var tstr = $('#' + form).serialize();
    var tone = '';

    var user_id = '';
    var emailv = '';

    $.ajax(
        {
            type:'get',
            url: controller ,
            data: tstr,

            // data: 'action=smart_load&test=78we',
            success:function (response) {
                unblock_screen('221s');

                var result = response;
                if ( result.status == 'ok' ) {
                    unblock_screen('X');
                    alert(" hello need password ");
                    // return true;
                    $('#start_email_pwd').html(result.html);
                    return true;


                    unblock_screen('X');

                    if (result.user_id != null ) user_id = result.user_id;
                    if (result.emailv != null ) emailv = result.emailv;

                    dialog_load_controller( gqs + "&load=connect4pwd&user_id=" + user_id + "&connectemail=" + encodeURIComponent(emailv) , controller );

                    return true;
                } else if ( result.status == 'reg' ) {

                    $('#signinmessage').html('');

                    if (result.user_id != null ) user_id = result.user_id;
                    if (result.emailv != null ) emailv = result.emailv;
                    dialog_load_controller( gqs + "&load=connect4reg&user_id=" + user_id + "&connectemail=" + emailv, controller );
                    return true;
                }  else {
                    $('#signinmessage').html(result.msg);
                }
            },
            error: function (x, status, errorThrown) {
                unblock_screen('221e');
                if (status == "error") {
                    var errorMsg = "";
                    if (errorThrown) {
                        errorMsg = errorThrown;
                    }
                    // alert("The call to the server side failed (#3213312). [" + form + "][" + gqs +  "][" + controller + "]:" + errorMsg);
                    // alert("The call to the server side failed (#3213312). [" + tstr + "][" + gqs +  "][" + controller + "]:" + errorMsg);
                    alert("The call to the server side failed (#3213312). :" + errorMsg);
                }
            }
        }
    );
    return true;
}







function submitEmailPassword4(form, gqs, controller) {

    block_screen('220');

    var  y = $("#" + form + " #action");
    y.val("do_signin4");


    var tstr = $('#' + form ).serialize();
    var tone = "";

    var user_id = "";
    var emailv = "";

    $.ajax(
        {
            type:"get",
            url: controller ,
            data: tstr,

            // data: 'action=smart_load&test=78we',
            success:function (response) {
                unblock_screen('220s');

                var result = response;

                if ( result.status == 'ok' ) {

                    // $('#signinmessage').html('');
                    // $('#dynamic_body').html(result.html);
                    // $('#password_d').focus();

                    window.location = result.url;

                    return true;

                } else if ( result.status == 'bademail' ) {

                    // $('#signinmessage').html('The Email: ' + emailv + ' does not have an active profile, you can create now' );

                    if (result.user_id != null ) user_id = result.user_id;
                    if (result.emailv != null ) emailv = result.emailv;
                    dialog_load_controller( gqs + "&load=connect4reg&user_id=" + user_id + "&connectemail=" + emailv + "&message=" + emailv + " does not have a profile, but you can create one", controller );
                    return true;

                } else if ( result.status == 'badpassword' ) {

                    $('#signinmessage').html('You have entered an incorrect password');

                    return true;

                }  else {

                    alert("ES: OTHER");

                    $('#signinmessage').html(result.msg);

                }
            },
            error:function (x, status, errorThrown) {
                unblock_screen('220e');
                if (status == "error") {
                    var errorMsg = "";
                    if (errorThrown) {
                        errorMsg = errorThrown;
                    }
                    alert("The call to the server side failed. " + errorMsg);
                }
            }
        }
    );
    return true;
}



/*
function submitEmail2( form, gqs  ) {
    block_screen('23');
    //$.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 23</p></div>' });
    var tstr = $('#' + form ).serialize();
    var tone = "";
    $.ajax(
        {
            type:"get",
            url:"master_controller.php" ,
            data: tstr,
            success:function (response) {
                unblock_screen('X');
                var result = response;
                if ( result.status == 'ok' ) {
                    $('#signinmessage').html('');
                    $('#dynamic_body').html(result.html);
                    return true;
                } else if ( result.status == 'reg' ) {
                    $('#signinmessage').html('');
                    var user_id = "";
                    if (result.user_id != null )
                        user_id = result.user_id;
                    dialog_load( gqs + "&user_id=" + user_id );
                    return true;
                }  else {
                    $('#signinmessage').html(result.msg);
                }
            },
            error:function (x, status, errorThrown) {
                unblock_screen('X');
                if (status == "error") {
                    var errorMsg = "";
                    if (errorThrown) {
                        errorMsg = errorThrown;
                    }
                    alert("The call to the server side failed. " + errorMsg);
                }
            }
        }
    );
    return true;
}
*/

function dialog_div( url, id ) {
    $( '#' + id ).html('<h3 style="margin-left:10px;"><img src="/rx/images/busy.gif" />It will take a moment to generate this page</h3>');

    ajax = $.ajax({
        type: 'GET',
        url: '/master_controller.php',
        data: 'action=smart_div&' + url,
        success: function(response) {
            var result = response;
            $('#' + id ).html(response);
        },
        error: function(response) {
            var result = response;
            $( '#' + id ).html('<span style="color:red" class="smallText">There was an error processing this request (#8342302) please call (919) 948-0758.</span>');

        }
    });
    return;
}




function dialog_div2( url, id ) {

    $( id ).html('<h3 style="margin-left:10px;"><img src="/rx/images/busy.gif" />It will take a moment to generate this page</h3>');

    ajax = $.ajax({
        type: 'GET',
        url: '/master_controller.php',
        data: 'action=smart_div2&' + url,
        success: function(response) {
            var result = response;
            $('#' + id).html(result.html_body);
        },
        error: function(response) {
            var result = response;
            $( '#' + id ).html('<span style="color:red" class="smallText">There was an error processing this request (#8342303) please call (919) 948-0758.</span>');

        }
    });
    return;
}




function startSlider() {
    var isAuto = false;
    if ($('.sliderImage').length > 1) {
        // Call BS Slider as normal
        isAuto = true;
    }
    $('#slider1').bxSlider({
        auto:isAuto,
        mode:'vertical',
        pager:false,
        speed:2000,
        pause:5000,
        captions:true,
        randomStart:true,
        autoHover:true,
        controls:false,
        displaySlideQty: 1,
        moveSlideQty:1
    });
}



function showEventDetailsSubscribe5( qs, eventId, subscribe, userId) {

    if (!eventId) {
        return false;
    }

    if ( subscribe == 0 ) {
        showEventDetails5(qs, eventId);

    }
    else if ( subscribe == 1 ) {
        showPopup('dialog_claim');
    }
    else if (userId > 0 )  {
        showPopup('dialog_join');
    }
    else {
        showFirstSignin();

    }
    return false;
}



function showEventDetails5(qs, eventId) {

    if (!eventId) return false;

    block_screen('24');
    $.ajax(
        {
            type: "get",
            url: "/rx/events_controller.php",
            data: qs,
            async: true,
            cache: false,
            success: function (response) {

                unblock_screen('24S');

                if (response) {
                    showDiv('activity_body');

                    $(window).scrollTop(0);

//                    document.getElementById('activity_body').scrollIntoView();

                    var innerHtml = response;

                    $('#activity_body').html(innerHtml);

                    eventDetailShown = eventId;
                }

            },
            error: function (x, status, errorThrown) {

                unblock_screen('24E');
                if (status == "error") {
                    var errorMsg = "";
                    if (errorThrown) {
                        errorMsg = errorThrown;
                    }
                    alert("The call to the server side failed. " + errorMsg);
                }
            }
        }
    );

    return false;
}



function resizeMap(eventId) {
    var outerContainer = $('#mapTableText');
    if (outerContainer.length > 0) {
        var controls = $('#mapControlsDiv');
        if (controls.length > 0) {
            var newHeight = outerContainer.outerHeight() - controls.outerHeight();
            if (newHeight < 300) {
                newHeight = 300;
            }
            var container = $('#map_canvas' + eventId);
            if (container.length > 0) {
                container.height(newHeight);
            }
        }
    }
}


function hideEventPopupX(eventId, url) {
    if (eventId === null) return;

    var foo = $( '#row_details_popup' );
    if (foo.length > 0) {
        if ( url != '' )
           window.location = url;
        else
          hidePopup('row_details_popup');
    }
    else {
        $('#row_' + eventId).show();
        $('#row_details_' + eventId).hide();
        $('#row_details_' + eventId).html('');
        eventDetailShown = null;
    }
    return false;
}




function submitCopyField(cntrl, form, tableID, rowID, field_index) {
    $("#" + form + " #action").val("copy_field");
    $("#" + form + " #field_index").val(field_index);

    var table = document.getElementById(tableID);
    var target = document.getElementById(rowID);
    var index = parseInt($("#rowcounter").val());

    var nextindex = index + 1;
    $("#rowcounter").val(nextindex);

    var rowCount = table.rows.length;
    $("#" + form + " #new_index").val(index);

    $.ajax(
        {
            type:"post",
            url:"/" + cntrl ,
            data:$('#' + form ).serialize(),

            success:function (response) {
                unblock_screen('X');
                if (response) {
                    var innerHtml = response;

                    var row = document.createElement('tr');
                    target.parentNode.insertBefore(row, target.nextSibling );

                    row.id = "tr_" + index;

                    $(row).html(innerHtml);
                    // setBlur();
                    setupTable();
                }
            },
            error:function (x, status, errorThrown) {
                unblock_screen('X');
                if (status == "error") {
                    var errorMsg = "";
                    if (errorThrown) {
                        errorMsg = errorThrown;
                    }
                    alert("The call to the server side failed. " + errorMsg);
                }
            }
        }
    );

    return true;
}


function setupTable() {

    var fixHelper2 = function (e, ui) {
        ui.children().each(function () {
            $(this).width($(this).width());
        });
        return ui;
    };

    //  IF CLASS EXISTS, THEN DO .sortable
    if ($('.storeoptiontable tbody')[0]){
        $('.storeoptiontable tbody').sortable({
            helper:fixHelper2,
            update:function (event, ui) {
                var adsOrder = $(this).sortable('toArray').toString();
            }
        });
    }
}

function submitRaceReg(cntrl, form,  target) {
    var do_reg =  $('input:radio[name=regofferq]:checked').val();
    if ( do_reg == 'on' ) {
        submitValidateFormAjaxNew5C('/rx/store_controller.php', form, target, 'form_validate_ajax', '');
    } else {
        $("#" + form + " #action").val("noreg");
        submitFormForward(form, target);
    }
    return true;
}

function submitRaceRegForce(cntrl, form,  target) {
    submitValidateFormAjaxNew5C('/rx/store_controller.php', form, target, 'form_validate_ajax', '');
    return true;
}


function updateFormStatus(cntrl, form,  target) {
    // submitValidateFormAjaxNew5C('/rx/store_controller.php', form, target, 'storeitem_set_status', '');
    // debugger;
    // return true;

    var form_id = $("#storeitem_id").val();
    var form_status = $("#storeitem_status").val();

    ajax = $.ajax({
        type: 'POST',
        url: '/rx/store_controller.php',
        data: {action : 'storeitem_set_status', storeitem_id : form_id, storeitem_status : form_status},
        success: function(response) {
            alert(response.msg);
        },
        error: function(response) {
        }
    });

}



function submitActivityReg(cntrl, form,  target) {

    var si =  $('#storeitem_id_select').val();
    if ( si != 1 ) {
        submitValidateFormAjaxNew5C(cntrl, form, target, 'form_validate_ajax', '');
    } else {
        $("#" + form + " #action").val("noreg_activity");
        submitFormForward( form, target);
    }
    return true;
}

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

function submitUrlWithValue(url, control, tag) {
    var select  = $("#" + control).val();
    submitUrl(url + '&' + tag + '=' + select);
    return;
}

function submitUrlWithValueRadio(url, control, tag) {
    var select = $('input:radio[name=' + control + ']:checked').val()
    submitUrl(url + '&' + tag + '=' + select);
    return;
}


function submitUrlWithValueCheckboxBlock(url, control, tag, blank) {

    block_screen('25');
    // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 25</p></div>' });
    var result = submitUrlWithValueCheckbox3(url, control, tag, blank);
    return($result);
}

/*
function submitUrlWithValueCheckbox( url, control, tag  ) {
    var select  = $('input:checkbox[name=' + control + ']:checked').val()
    if ( select == null ) {
        select = "off";
    }
    submitUrl( url + '&' + tag + '=' + select );
    return;
}
*/

function submitUrlWithValueCheckbox2(url, control, tag, blank_value) {
    var select  = $('input:checkbox[name=' + control + ']:checked').val()
    if ( select == null ) {
        select = "";
    }
    if ( select == "" ) {
        select = blank_value;
    }
    submitUrl( url + '&' + tag + '=' + select );
    return;
}

function submitUrlWithValueCheckbox3(url, control, tag, blank_value) {
    submitUrlWithValueCheckbox2(url, control, tag, blank_value);
    return;
}



function ajaxUrlWithValueCheckbox2( url, control, tag, blank_value  ) {
    var select  = $('input:checkbox[name=' + control + ']:checked').val()
    if ( select == null ) {
        select = "";
    }
    if ( select == "" ) {
        select = blank_value;
    }

    var url1 = url + '&' + tag + '=' + select;

    $.ajax(
        {
            type:"get",
            url:"/" +  url1 ,

            success:function (response) {
                unblock_screen('X');
            },
            error:function (x, status, errorThrown) {
                unblock_screen('X');

            }
        }
    );

    return;
}





function updateSelectFieldTeam(storeitem_id, field_name) {
    var select  = $("#team_name").val();

    var pflag = "";
    if ( $("#team_public").attr('checked') ) {
        pflag = "on";
    }

    ajax = $.ajax({
        type: 'GET',
        url: '/rx/store_controller.php',
        data: {action : 'add_field_option', storeitem_id : storeitem_id, field_name : field_name, option : select, pflag : pflag },
        success: function(response) {
            $("#" + field_name)
                .append($("<option></option>")
                .attr("value",response.value)
                .text(response.text));
            $("#" + field_name).val(response.value);
        },
        error: function(response) {
        }
    });

}

function updateSelectOptions(storeitem_id, field_name, context) {
    var select  = $("#team_name").val();
    var pflag = "";
    if ( $("#team_public").attr('checked') ) {
        pflag = "on";
    }

    ajax = $.ajax({
        type: 'GET',
        url: '/rx/store_controller.php',
        data: {action : 'add_field_option', storeitem_id:storeitem_id, field_name:field_name, option:select, pflag:pflag, context:context},
        success: function(response) {
            if ( response.status == "ok" ) {
                $("#blob_" + field_name)
                    .append($("<option></option>")
                    .attr("value",response.value)
                    .text(response.text));
                $("#blob_" + field_name).val(response.value);
                $("#blob_" + field_name + "_newflag").val(response.value);
            } else {
                $("#blob_" + field_name).val('');
                $("#blob_" + field_name + "_newflag").val('');
            }
        },
        error: function(response) {
        }
    });
}





function TAAF_updateAgeDivision(rowID, tableID, old_AgeDivision_value, old_AgeDivision_prompt) {
    let name = $('#'+rowID+'-taafathlete_FirstName').val() + " " + $('#'+rowID+'-taafathlete_LastName').val();
    let new_AgeDivision_prompt = $( '#'+rowID+'-taafathlete_AgeDivision option:selected' ).text();
    let up_age_confirm = confirm('You have selected to change '+name+'\'s age division from ' + old_AgeDivision_prompt + ' to ' + $.trim(new_AgeDivision_prompt) + '.' +
        '\r\n\r\nIf this change is correct, please confirm that you understand this athlete must compete in the new age division for all their events. ' +
        '\r\n\r\nAfter you confirm, please SUBMIT this form (bottom of the page) and log back in. Then you can enter events applicable to the new division.');

    if ( !up_age_confirm ) {
        $( '#'+rowID+'-taafathlete_AgeDivision' ).val(old_AgeDivision_value);
        return false;
    }

    //  TODO - figure out if we are using this
    $('#paypal_buy_now #blob_updateAgeDivision_confirm').val("on");

    //  TODO change eligible events
    //  TODO Add checkbox that theyve acknowledged change


    //alert("changing eligibility");
    return false;
}

function TAAF_checkEventLimit(row_name, event_name) {

    var msg = "";
    let total_limit_element = $('#' + row_name + "_total_limit");
    let track_limit_element = $('#' + row_name + "_track_limit");
    let individual_limit_element = $('#' + row_name + "_individual_limit");
    if ( total_limit_element.length ) {
        var athlete_event_checkboxes_checked = $('input:checkbox[id^="' + row_name + '-"]:checked');
        var athlete_event_checkboxes_unchecked = $('input:checkbox[id^="' + row_name + '-"]:not(:checked)');
        var athlete_track_checkboxes_checked = $('input:checkbox[id^="' + row_name + '-track-"]:checked');
        var athlete_indiv_checkboxes_checked = $('input:checkbox[id^="' + row_name + '-individual-"]:checked');
        // TODO: athlete_indiv_checkboxes_checked is only used for swimming, but for swimming it is identical to
        //  athlete_event_checkboxes_checked. We can get rid of the _indiv_ version after the 2023 Swimming year

        // TODO: A swimmer should not be allowed to be an alternate for a relay event if they are participating in that
        //  event on a different relay team. Currently, the code allows for a swimmer to be added as an alternate if
        //  they are added as an alternate BEFORE being added as a main relay team member. We should change it to where
        //  they are removed as an alternate if they are added as a main relay team member.

        var relay400_element = $('#'+row_name+"-relay400");
        var relay1600_element = $('#'+row_name+"-relay1600");

        var number_relays_selected = 0;
        if ( relay400_element.length && (relay400_element.val() ==="on") )  number_relays_selected++;
        if ( relay1600_element.length && (relay1600_element.val() ==="on") )  number_relays_selected++;

        var athlete_event_relay_checked = $('input[id^="' + row_name + '-relay"][value=on]');
        //alert("athlete_event_relay_checked " + athlete_event_relay_checked);

        var athlete_track_checkboxes_unchecked = $('input:checkbox[id^="' + row_name + '-track-"]:not(:checked)');
        var athlete_indiv_checkboxes_unchecked = $('input:checkbox[id^="' + row_name + '-individual-"]:not(:checked)');
        //if ( parseInt(total_limit_element.val()) <= athlete_event_checkboxes_checked.length ) {
        if ( parseInt(total_limit_element.val()) <= (athlete_event_checkboxes_checked.length + athlete_event_relay_checked.length) ) {
            //  THEY'VE REACHED TOTAL MAX
            if ( track_limit_element.length ) {
                //  DETERMINE BEST MESSAGE
                if ( parseInt(track_limit_element.val()) <= (athlete_track_checkboxes_checked.length + athlete_event_relay_checked.length)) {
                    if (typeof event_name !== 'undefined') {
                        msg = 'Maximum TOTAL events and RUNNING events now selected for that athlete.';
                    } else {
                        msg = 'Max events selected';
                    }
                } else {
                    if (typeof event_name !== 'undefined') {
                        msg = 'Maximum total events now selected for that athlete.';
                    } else {
                        msg = 'Max events selected';
                    }
                }
            }
            else if ( individual_limit_element.length ) {
                //  SWIMMING - DETERMINE BEST MESSAGE
                //alert("individual2");
                //  07Jul2023 KylaUpdate - we should not have been adding relays when checking individual limit
                //if ( parseInt(individual_limit_element.val()) <= (athlete_indiv_checkboxes_checked.length + athlete_event_relay_checked.length)) {
                if ( parseInt(individual_limit_element.val()) <= athlete_indiv_checkboxes_checked.length) {
                    if (typeof event_name !== 'undefined') {
                        msg = 'Maximum TOTAL events and INDIVIDUAL events now selected for that athlete.';
                    } else {
                        msg = 'Max events selected';
                    }
                } else {
                    if (typeof event_name !== 'undefined') {
                        msg = 'Maximum total events now selected for that athlete.';
                    } else {
                        msg = 'Max events selected';
                    }
                }
            }
            else {
                //  NO RUNNING LIMIT and NO SWIM INDIVIDUAL LIMIT - only one message makes sense
                if (typeof event_name !== 'undefined') {
                    msg = 'Maximum total events now selected for that athlete.';
                } else {
                    msg = 'Max events selected';
                }
            }
            //  TODO DO WE NEED TO DISABLE individual_checkboxes_unchecked?
            athlete_event_checkboxes_unchecked.css('pointer-events', 'none');
            athlete_event_checkboxes_unchecked.attr('disabled', true);
        }
        else {
            // EITHER THEY ARE GOOD (total-limit-wise) OR HAVE HIT A TRACK LIMIT OR INDIVIDUAL LIMIT
            athlete_event_checkboxes_unchecked.css('pointer-events', 'auto');
            athlete_event_checkboxes_unchecked.attr('disabled', false);
            if ( track_limit_element.length ) {
                if ( parseInt(track_limit_element.val()) <= (athlete_track_checkboxes_checked.length + athlete_event_relay_checked.length) ) {
                    if (typeof event_name !== 'undefined') {
                        if ( $('#' + row_name + '-track-' + event_name).length ) {
                            msg = 'Maximum RUNNING events now selected for that athlete.';
                        }
                        athlete_track_checkboxes_unchecked.css('pointer-events', 'none');
                        athlete_track_checkboxes_unchecked.attr('disabled', true);
                    } else {
                        msg = 'Max track events selected';
                    }
                }
            }
            else if ( individual_limit_element.length ) {
                //alert("individual 1");
                //  07Jul2023 KylaUpdate - we should not have been adding relays when checking individual limit
                //if ( parseInt(individual_limit_element.val()) <= (athlete_indiv_checkboxes_checked.length + athlete_event_relay_checked.length) ) {
                if ( parseInt(individual_limit_element.val()) <= athlete_indiv_checkboxes_checked.length ) {
                    if (typeof event_name !== 'undefined') {
                        if ( $('#' + row_name + '-individual-' + event_name).length ) {
                            msg = 'Maximum INDIVIDUAL events now selected for that athlete.';
                        }
                        athlete_indiv_checkboxes_unchecked.css('pointer-events', 'none');
                        athlete_indiv_checkboxes_unchecked.attr('disabled', true);
                    } else {
                        msg = 'Max track events selected';
                    }
                }
            }
        }
    }
    return(msg);
}


function TAAF_registerAthlete(row_name, tableID) {
    if ( row_name === "" ) {
        var rowcounter_input = $('#'+tableID+'_rowcounter');
        var rowcounter = parseInt(rowcounter_input.val());
        if ( Number.isNaN(rowcounter) )  rowcounter = 0;
        else  rowcounter = rowcounter - 1;
        row_name = tableID + "-" + rowcounter;
    }

    var athlete_registered_flag = $('#registerathlete_' + row_name + ':checked').val();
    var athlete_event_checkboxes = $('[id^="' + row_name + '-"]');

    var field_price_element = $('#'+tableID+'_price');
    var current_price = parseFloat(field_price_element.val());
    var field_registerprice_element = $('#'+tableID+'_registerprice');
    var current_registerprice = parseFloat(field_registerprice_element.val());
    var field_eventprice_element = $('#'+tableID+'_eventprice');
    var current_eventprice = parseFloat(field_eventprice_element.val());

    var row_registerprice_element = $('#'+row_name+'_registerprice');
    var row_current_registerprice = parseFloat(row_registerprice_element.val());
    var row_eventprice_element = $('#'+row_name+'_eventprice');
    var row_current_eventprice = parseFloat(row_eventprice_element.val());

    var region = $('#'+tableID+'_region').val();
    var current_form_id = $('#storeitem_id').val();

    var registration_price = parseFloat(10);
    //$taaf_11DollarAthlete_regions
    if (( region === '1' ) || ( region === '3' ) || ( region === '4' ) || ( region === '5' ) || ( region === '7' )) {
        registration_price = parseFloat(11);
    }

    //$taaf_summer_price_increase_time and $taaf_winter_price_increase_time - athlete registration price increases by $5
    var now_time_seconds = Math.round(+new Date()/1000);
    //  WINTER GAMES - Gymnastics
    //  TODO - make this generic for future gymnastics forms
    //if ( current_form_id === "56397" ) {
    if ( current_form_id === "68876" ) {
        //if ( now_time_seconds >= 1704261600 ) {  //  2024-01-03 00:00:00 CT
        if ( now_time_seconds >= 1735884000 ) {  //  2025-01-03 00:00:00 CT
            registration_price += 5.00;
        }
    //} else if ( now_time_seconds >= 1686891600 ) { //  2023-06-16 00:00:00 CT
    } else if ( now_time_seconds >= 1718514000 ) {  //  2024-06-16 00:00:00 CT
        registration_price += 5.00;
    }

    var new_price;
    var new_registerprice;
    var new_eventprice;
    var row_new_price;
    var row_new_eventprice;

    athlete_event_checkboxes.attr('disabled', !athlete_registered_flag);
    athlete_event_checkboxes.prop("checked", false);

    if ( athlete_registered_flag ) {
        athlete_event_checkboxes.css('pointer-events', 'auto');
        new_price = current_price + registration_price;
        new_registerprice = current_registerprice + registration_price;
        row_new_price = row_current_registerprice + registration_price;

        $('#taafregisterathletes_'+row_name).css("background-color", "lemonchiffon");
        $('#taafteamathletes_'+row_name).css("background-color", "lemonchiffon");
    }
    else {
        athlete_event_checkboxes.css('pointer-events', 'none');
        new_price = current_price - row_current_registerprice - row_current_eventprice;
        new_registerprice = current_registerprice - row_current_registerprice;
        new_eventprice = current_eventprice - row_current_eventprice;
        row_new_price = "0";
        row_new_eventprice = "0";

        $('#taafregisterathletes_'+row_name).css("background-color", "#FFFFFF");
        $('#taafteamathletes_'+row_name).css("background-color", "#FFFFFF");

        field_eventprice_element.val(new_eventprice);
        row_eventprice_element.val(row_new_eventprice);
    }

    field_price_element.val(new_price);
    field_registerprice_element.val(new_registerprice);
    row_registerprice_element.val(row_new_price);
    updateFormPrice('paypal_buy_now');
    return false;
}


function TAAF_importAthlete(form, tableID) {
    hideDiv('import_help_div');
    $('[id^="' + tableID + '_message"]').html('');

    var messagefieldtop = $('#'+form+' #messagefieldtop');
    messagefieldtop.html('');

    if ( !$('#'+form+' #taafimportathlete_file').val() ) {
        messagefieldtop.html('<span style="font-size:16px" >No file selected.</span>');
        return false;
    }

    block_screen('Importing Athletes');

    //  transitioning from _listform to listform_
    var listform = $('#listform_' + tableID).val();
    var listform_test = $('#' + tableID + '_listform').val();
    if ( listform !== listform_test ) {
        var test = 1;
    }

    var table = document.getElementById('table_' + tableID);
    var lastRowIndex = table.rows.length - 1;
    var target = table.rows[lastRowIndex];
    while (( target.className !== 'smart_list_x' ) && !target.id.startsWith(listform+'_'+tableID+'-') ) {
        lastRowIndex--;
        target = table.rows[lastRowIndex];
    }

    let rowcounter_element = $('#' + tableID + '_rowcounter');
    var index = parseInt(rowcounter_element.val());
    if ( Number.isNaN(index) )  index = 0;


    //$('#' + form + ' #index').val(index);

    var ff = document.getElementById(form);
    var fd = new FormData(ff);

    fd.append('region', $('#'+tableID+'_region').val());
    fd.append('index', index);

    $.ajax( {
        type:'post',
        url:'/rx/store_controller.php',
        data: fd,
        contentType: false,
        processData: false,
        success:function (response) {
            if ( response.status === 'ok' ) {

                var import_notes = "";
                var missing_keys = response.missing_keys;
                if ( missing_keys.length > 0 ) {
                    import_notes = '<div style="color:brown; padding:0 5px 0 5px">NO Athletes imported.<br>Imported file was missing the following column headers:</div>';
                    $.each( missing_keys, function( key, value ) {
                        import_notes = import_notes + '<div style="padding-left:20px" >' + value+'</div>';
                    });
                } else {
                    var new_count = 0;
                    var new_registered = 0;
                    var already_registered = 0;
                    var innerHtml = response.new_taafathlete_rows;
                    $.each( innerHtml, function( key, value ) {
                        var row = document.createElement('tr');
                        target.parentNode.insertBefore(row, target.nextSibling);

                        row.id = 'tr_' + index;
                        if (( listform !== undefined ) && ( listform !== null )) {
                            row.id = listform + '_' + tableID + '-' + index;
                        }

                        $(row).html(value);
                        setupTable();
                        TAAF_registerAthlete(tableID+"-"+index, tableID);
                        new_count++;
                        new_registered++;
                        index++;

                        lastRowIndex++;
                        target = table.rows[lastRowIndex];
                    });
                    rowcounter_element.val(index + 1);

                    var existing_rows = response.existing_taafathlete_rows;
                    $.each( existing_rows, function( key, value ) {
                        var taafathlete_row_id = $('#rowid_for_taafathleteid_'+value).val();

                        let registerathlete_element = $('#registerathlete_' + taafathlete_row_id);
                        if (( registerathlete_element.attr('type') === 'hidden' ) || registerathlete_element.prop('checked') ) {
                            already_registered++;
                        } else {
                            registerathlete_element.prop('checked', true);
                            TAAF_registerAthlete(taafathlete_row_id, tableID);
                            new_registered++;
                        }
                    });

                    rowcounter_element.val(index);

                    import_notes = '<div style="padding:0 5px 0 5px">Athletes added to list: '+new_count+'<br>New athletes to be registered: '+(new_registered)+'<br>Athletes already registered: '+already_registered+'</div>';

                    var rows_missing_data = response.rows_missing_data;
                    //if ( rows_missing_data !== 0 ) {
                        //import_notes = import_notes + '<br><div style="color:brown; padding-left:5px">Athletes NOT Imported - required data was missing: '+rows_missing_data+'</div>';
                    //}
                    if ( rows_missing_data.length > 0 ) {
                        import_notes = import_notes + '<br><div style="color:brown; padding:0 5px 0 5px">Athletes NOT Imported - missing required data: '+rows_missing_data.length+'</div>';
                        $.each( rows_missing_data, function( key, value ) {
                            import_notes = import_notes + '<div style="padding-left:20px">' + value + '</div>';
                        });
                    }
                    var rows_bad_dob = response.rows_bad_dob;
                    if ( rows_bad_dob.length > 0 ) {
                        import_notes = import_notes + '<br><div style="color:brown; padding:0 5px 0 5px" >Athletes NOT Imported - Birthday not in mm/dd/yyyy format: '+rows_bad_dob.length+'</div>';
                        $.each( rows_bad_dob, function( key, value ) {
                            import_notes = import_notes + '<div style="padding-left:20px">' + value + '</div>';
                        });
                    }
                    var rows_too_old = response.rows_too_old;
                    if ( rows_too_old.length > 0 ) {
                        import_notes = import_notes + '<br><div style="color:brown; padding:0 5px 0 5px" >Athletes NOT Imported - too old: '+rows_too_old.length+'</div>';
                        $.each( rows_too_old, function( key, value ) {
                            import_notes = import_notes + '<div style="padding-left:20px">' + value + '</div>';
                        });
                    }
                }


                $('[id^="' + tableID + '_message"]').html(import_notes);
                unblock_screen('X');
            }

            else {
                alert('TAAF_importAthlete error: ' + response);
                unblock_screen('X');
            }
        },

        error:function (x, status, errorThrown) {
            alert('fail');
            unblock_screen('X');
        }
    });

    return true;
}

function TAAF_addAthlete_get_trim_set_value(form, value_name) {
    let value_element = $('#'+form+' #'+value_name);
    let value_string_trimmed = value_element.val().trim();
    if (value_string_trimmed !== value_element.val() )  value_element.val(value_string_trimmed);
    return (value_string_trimmed);
}

function TAAF_addAthlete(form, tableID) {
    var messagefieldtop = $('#'+form+' #messagefieldtop');
    messagefieldtop.html('');

    let firstname_string_trimmed = TAAF_addAthlete_get_trim_set_value(form, 'taafathlete_FirstName');
    if ( firstname_string_trimmed === '' ) {
        messagefieldtop.html('First Name is missing');
        return false;
    }

    let lastname_string_trimmed = TAAF_addAthlete_get_trim_set_value(form, 'taafathlete_LastName');
    if ( lastname_string_trimmed === '' ) {
        messagefieldtop.html('Last Name is missing');
        return false;
    }

    if ( typeof $('input[name="taafathlete_gender"]:checked').val() === 'undefined' ) {
        messagefieldtop.html('Gender is missing');
        return false;
    }

    if (( $('#'+form+' #taafathlete_dob_month').val() === "" ) || ( $('#'+form+' #taafathlete_dob_month').val() === '00' )) {
        messagefieldtop.html('Birth Month is missing');
        return false;
    }
    if (( $('#'+form+' #taafathlete_dob_day').val() === "" ) || ( $('#'+form+' #taafathlete_dob_day').val() === '00' )) {
        messagefieldtop.html('Birth Day is missing');
        return false;
    }
    if (( $('#'+form+' #taafathlete_dob_year').val() === "" ) || ( $('#'+form+' #taafathlete_dob_year').val() === '00' )) {
        messagefieldtop.html('Birth Year is missing');
        return false;
    }

    //  NOTES: if someone is too old for T&F, do not let them be added
    if (( $('#'+form+' #sport').val() === 'track' )
        && ( parseInt($('#'+form+' #taafathlete_dob_year').val()) < (new Date().getFullYear() - 21) )) {
        messagefieldtop.html('Birth Year is too old for <br> TAAF Track & Field meets');
        return false;
    }

    TAAF_addAthlete_get_trim_set_value(form, 'taafathlete_e_contact');
    //  NOTE: Emergency contact name is not required.

    let e_phone_string_trimmed = TAAF_addAthlete_get_trim_set_value(form, 'taafathlete_e_contact_phone');
    if ( e_phone_string_trimmed === '' ) {
        messagefieldtop.html('Emergency Phone is missing');
        return false;
    }
    let e_phone_element = $('#'+form+' #taafathlete_e_contact_phone');
    let e_contact_phone_digits = e_phone_string_trimmed.replace(/\D/g,'');
    if ( e_contact_phone_digits !== e_phone_element.val() )  e_phone_element.val(e_contact_phone_digits);
    if ( !(( e_contact_phone_digits.length === 10 ) || (( e_contact_phone_digits.length === 11 ) && ( e_contact_phone_digits[0] === '1' ))) ) {
        messagefieldtop.html('Emergency Phone must be in 10-digit format');
        return false;
    }

    let email_string_trimmed = TAAF_addAthlete_get_trim_set_value(form, 'taafathlete_Email');
    if ( email_string_trimmed === '' ) {
        messagefieldtop.html('Email Address is missing');
        return false;
    }
    let email_regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if ( !email_regex.test(email_string_trimmed) ) {
        messagefieldtop.html('Email Address format invalid');
        return false;
    }

    block_screen('Adding Athlete');

    //  transitioning from _listform to listform_
    var listform = $('#listform_' + tableID).val();
    var listform_test = $('#' + tableID + '_listform').val();
    if ( listform !== listform_test ) {
        var test = 1;
    }

    var table = document.getElementById('table_' + tableID);
    var lastRowIndex = table.rows.length - 1;
    var target = table.rows[lastRowIndex];
    while (( target.className !== 'smart_list_x' ) && !target.id.startsWith(listform+'_'+tableID+'-') ) {
        lastRowIndex--;
        target = table.rows[lastRowIndex];
    }

    let rowcounter_element = $('#' + tableID + '_rowcounter');
    var index = parseInt(rowcounter_element.val());
    if ( Number.isNaN(index) )  index = 0;

    var region = $('#'+tableID+'_region').val();

    ajax = $.ajax({
        type: 'POST',
        url: '/rx/store_controller.php',
        data:$('#' + form).serialize() + '&index=' + index + '&region=' + region,
        success: function(response) {

            if ( response.status === 'ok' ) {
                $('[id^="' + tableID + '_message"]').html('');
                var existing_id = response.existing_taafathlete_id;
                var row_id = "";

                if ( existing_id === "" ) {
                    rowcounter_element.val(index + 1);
                    var innerHtml = response.taafathlete_row;
                    var row = document.createElement('tr');
                    target.parentNode.insertBefore(row, target.nextSibling);

                    row.id = 'tr_' + index;
                    if (( listform !== undefined ) && ( listform !== null )) {
                        row.id = listform + '_' + tableID + '-' + index;
                    }
                    $(row).html(innerHtml);
                    setupTable();
                    // Is this ok, having no rowid parameter?
                    TAAF_registerAthlete("", tableID);

                    $('[id^="' + tableID + '_message"]').html('Athletes added to list: 1<br> New athletes to be registered: 1<br>');

                }
                else {
                    row_id = $('#rowid_for_taafathleteid_' + existing_id).val();
                    let athlete_registered_flag = $('#registerathlete_' + row_id + ':checked').val();
                    let athlete_registered_static = $('#registerathlete_' + row_id);
                    if ( athlete_registered_flag || (( !$(athlete_registered_static).is(':visible') ) && ( athlete_registered_static.val() === "on" ))) {
                        $('[id^="' + tableID + '_message"]').html('Athletes added to list: 0 (Athlete already registered)<br> New athletes to be registered: 0 (Athlete already registered)<br>');
                    } else {
                        $("#registerathlete_" + row_id).prop("checked", true);
                        $('[id^="' + tableID + '_message"]').html('Athletes added to list: 0 (Athlete already in list)<br> New athletes to be registered: 1<br>');
                        TAAF_registerAthlete(row_id, tableID);
                    }
                }

                unblock_screen('X');
            } else {
                alert("TAAF Athlete not added. Please try again.");
                unblock_screen('X');
            }
        },
        error: function(response) {
            alert("TAAF Athlete not added due to server error. Please refresh and try again.");
            unblock_screen('X');
        }
    });
    return true;
}


function TAAF_removeAthlete(form, tableID, row_id) {
    block_screen('Removing Athlete');
    ajax = $.ajax({
        type: 'POST',
        url: '/rx/store_controller.php',
        data:$('#' + form).serialize(),
        success: function(response) {

            if ( response.status === 'ok' ) {
                //  NOTE: Hide removed athlete's row; Uncheck athlete's Register checkbox; Clear athlete's fields
                toggleTR('taafregisterathletes_' + row_id);
                toggleTR('taafteamathletes_' + row_id);
                let taaf_id_elem = $('#' + row_id + '-taafathlete_id');
                let taaf_id = taaf_id_elem.val();
                $("#registerathlete_" + row_id).prop("checked", false);
                //  NOTE: this does not clear row price, because we look for row_id "-" not "_"
                $('[id^="' + row_id + '-"]').val('');
                // NOTE: deleting the element that is used to find a row using the TAAF ID, since this was causing a bug
                // whereby previously deleted rows were being added to the price if imported more than once after being deleted
                let element_to_remove = document.getElementById('rowid_for_taafathleteid_'+taaf_id);
                $('#rowid_for_taafathleteid_'+taaf_id).remove();

                let field_price_element = $('#'+tableID+'_price');
                let field_registerprice_element = $('#'+tableID+'_registerprice');
                let field_eventprice_element = $('#'+tableID+'_eventprice');
                let row_price_element = $('#'+row_id+'_registerprice');
                let row_eventprice_element = $('#'+row_id+'_eventprice');
                let new_price = parseFloat(field_price_element.val()) - parseFloat(row_price_element.val()) - parseFloat(row_eventprice_element.val());
                let new_registerprice = parseFloat(field_registerprice_element.val()) - parseFloat(row_price_element.val());

                field_price_element.val(new_price);
                field_registerprice_element.val(new_registerprice);
                field_eventprice_element.val('0');
                row_price_element.val('0');
                row_eventprice_element.val('0');
                updateFormPrice('paypal_buy_now');
                unblock_screen('Success Removing Athlete');

            } else {
                unblock_screen('Issue Removing Athlete');
                alert("TAAF Athlete not removed. Please try again.");
            }
        },
        error: function(response) {
            unblock_screen('Error Removing Athlete');
            alert("TAAF Athlete not removed due to server error. Please refresh and try again.");
        }
    });
}


function TAAF_editAthlete(form, tableRowID) {

    var messagefieldtop = $('#'+form+' #messagefieldtop');
    messagefieldtop.html('');

    let firstname_element = $('#'+form+' #taafathlete_FirstName');
    let firstname_string_trimmed = firstname_element.val().trim();
    if (firstname_string_trimmed !== firstname_element.val() )  firstname_element.val(firstname_string_trimmed);
    if ( firstname_string_trimmed === "" ) {
        messagefieldtop.html('First Name is missing');
        return false;
    }

    let lastname_element = $('#'+form+' #taafathlete_LastName');
    let lastname_string_trimmed = lastname_element.val().trim();
    if ( lastname_string_trimmed !== lastname_element.val() )  lastname_element.val(lastname_string_trimmed);
    if ( lastname_string_trimmed === "" ) {
        messagefieldtop.html('Last Name is missing');
        return false;
    }




    if ( typeof $('input[name="taafathlete_gender"]:checked').val() === "undefined" ) {
        messagefieldtop.html('Gender is missing');
        return false;
    }
    if (( $('#'+form+' #taafathlete_dob_month').val() === "" ) || ( $('#'+form+' #taafathlete_dob_month').val() === "00" )) {
        messagefieldtop.html('Birth Month is missing');
        return false;
    }
    if (( $('#'+form+' #taafathlete_dob_day').val() === "" ) || ( $('#'+form+' #taafathlete_dob_day').val() === "00" )) {
        messagefieldtop.html('Birth Day is missing');
        return false;
    }
    if (( $('#'+form+' #taafathlete_dob_year').val() === "" ) || ( $('#'+form+' #taafathlete_dob_year').val() === "00" )) {
        messagefieldtop.html('Birth Year is missing');
        return false;
    }

    let e_contact_element = $('#'+form+' #taafathlete_e_contact');
    let e_contact_string_trimmed = e_contact_element.val().trim();
    if ( e_contact_string_trimmed !== e_contact_element.val() )  e_contact_element.val(e_contact_string_trimmed);
    //  NOTE: Emergency contact name is not required.


    //if ( $('#'+form+' #taafathlete_e_contact_phone').val() === "" ) {
        //messagefieldtop.html('Emergency Phone is missing');
        //return false;
    //}
    //let e_contact_phone_string = $('#'+form+' #taafathlete_e_contact_phone').val();
    //let e_contact_phone_digits = e_contact_phone_string.replace(/\D/g,'');
    //if ( !((e_contact_phone_digits.length === 10) || ((e_contact_phone_digits.length === 11) && (e_contact_phone_digits[0] === '1'))) ) {
        //messagefieldtop.html('Emergency Phone must be in 10-digit format');
        //return false;
    //}
    let e_phone_element = $('#'+form+' #taafathlete_e_contact_phone');
    let e_phone_string_trimmed = e_phone_element.val().trim();
    if ( e_phone_string_trimmed !== e_phone_element.val() )  e_phone_element.val(e_phone_string_trimmed);
    if ( e_phone_string_trimmed === "" ) {
        messagefieldtop.html('Emergency Phone is missing');
        return false;
    }
    let e_contact_phone_digits = e_phone_string_trimmed.replace(/\D/g,'');
    if ( e_phone_string_trimmed !== e_phone_element.val() )  e_phone_element.val(e_phone_string_trimmed);
    if ( !(( e_contact_phone_digits.length === 10 ) || (( e_contact_phone_digits.length === 11 ) && ( e_contact_phone_digits[0] === '1' ))) ) {
        messagefieldtop.html('Emergency Phone must be in 10-digit format');
        return false;
    }

    //if ( $('#'+form+' #taafathlete_Email').val() === "" ) {
        //messagefieldtop.html('Email Address is missing');
        //return false;
    //}
    //let email_regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    //if ( !email_regex.test($('#'+form+' #taafathlete_Email').val()) ) {
        //messagefieldtop.html('Email Address format invalid');
        //return false;
    //}
    let email_element = $('#'+form+' #taafathlete_Email');
    let email_string_trimmed = email_element.val().trim();
    if ( email_string_trimmed !== email_element.val() )   email_element.val(email_string_trimmed);
    if ( email_string_trimmed === '' ) {
        messagefieldtop.html('Email Address is missing');
        return false;
    }
    let email_regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if ( !email_regex.test(email_string_trimmed) ) {
        messagefieldtop.html('Email Address format invalid');
        return false;
    }

    block_screen('Editing Athlete');
    ajax = $.ajax({
        type: 'POST',
        url: '/rx/store_controller.php',
        data:$('#' + form).serialize(),
        success: function(response) {

            if ( response.status === 'ok' ) {
                if ( response.msg !== '' ) {
                    alert(response.msg);
                }

                var ta_FirstName = response.taafathlete_FirstName;
                var ta_LastName = response.taafathlete_LastName;
                var ta_dob = response.taafathlete_dob;
                var ta_gender = response.taafathlete_gender;
                var ta_Email = response.taafathlete_Email;

                if ( ta_FirstName !== '' ) $('#td_'+tableRowID+'_blob_FirstName').html(ta_FirstName);
                if ( ta_LastName !== '' )  $('#td_'+tableRowID+'_blob_LastName').html(ta_LastName);
                if ( ta_dob !== '' )  $('#td_'+tableRowID+'_blob_dob').html(ta_dob);
                if ( ta_gender !== '' )  $('#td_'+tableRowID+'_blob_gender').html(ta_gender);
                if ( ta_Email !== '' )  $('#td_'+tableRowID+'_blob_Email').html(ta_Email);

                unblock_screen('X');
            } else {
                alert("Error editing TAAF Athlete. Please try again.");
                unblock_screen('X');
            }
        },
        error: function(response) {
            alert("TAAF Athlete not edited due to server error. Please refresh and try again.");
            unblock_screen('X');
        }
    });
    return true;
}


function TAAF_updateTeamSportsList(form, tableRowID) {
    //alert(tableRowID);

    let action_element = $('#paypal_buy_now #teamslots_team');
    //alert(action_element.val());
    $('#smart_form_taafteamsports-list #td_'+tableRowID+'_blob_teamslots').html(action_element.val());
    action_element.val('updated');

    return true;
}


function TAAF_resetAgeDivision(tableRowID, default_agedivision, s_id) {

    block_screen('Resetting Age Division');
    ajax = $.ajax({
        type: 'POST',
        url: '/rx/store_controller.php',
        data:'action=taaf_reset_athlete_agedisivion&taaf_number='+tableRowID+'&default_agedivision='+default_agedivision+'&s_id='+s_id,
        success: function(response) {
            if ( response.status === 'ok' ) {
                hideTR('taafreport-ageup_'+tableRowID);
                unblock_screen('X');
            } else {
                alert("Division not edited. Please refresh and try again.");
                unblock_screen('X');
            }
        },
        error: function(response) {
            alert("TAAF Athlete not edited due to server error. Please refresh and try again.");
            unblock_screen('X');
        }
    });
    return true;
}


function TAAF_addRelay(form, tableID) {
    var messagefieldtop = $('#'+form+' #messagefieldtop_relay');
    messagefieldtop.html('');

    let track_or_swim = $('#'+form+' #track_or_swim').val();

    if ( !$("input[name='taafrelay_event']:checked").val() ) {
        messagefieldtop.html('Event is required');
        return false;
    }

    if ( track_or_swim === "track" ) {
        if ( !$("input[name='taafrelay_gender']:checked").val() ) {
            messagefieldtop.html('Gender is required');
            return false;
        }
    }

    if ( !$('#taafrelay_AgeDivision').val() ) {
        messagefieldtop.html('Age Division is required');
        return false;
    }

    if ( !$('#taafrelay_name').val() ) {
        messagefieldtop.html('Team Name/Letter (ex. A, B, 1, 2) is required');
        return false;
    }

    // First 4 relay team members
    for (const member_number of ["1", "2", "3", "4"]) {
        if ( !$('#member_' + member_number + '_select').val() ) {
            messagefieldtop.html('Member '+member_number+' is required');
            return false;
        }
    }

    block_screen('Adding Relay');

    //  transitioning from _listform to listform_
    var listform = $('#listform_' + tableID).val();
    var listform_test = $('#' + tableID + '_listform').val();
    if ( listform !== listform_test ) {
        var test = 1;
    }

    var table = document.getElementById('table_' + tableID);
    var lastRowIndex = table.rows.length - 1;
    var target = table.rows[lastRowIndex];
    while (( target.className !== 'smart_list_x' ) && !target.id.startsWith(listform+'_'+tableID+'-') ) {
        lastRowIndex--;
        target = table.rows[lastRowIndex];
    }

    let rowcounter_element = $('#' + tableID + '_rowcounter');
    var index = parseInt(rowcounter_element.val());
    if ( Number.isNaN(index) )  index = 0;
    rowcounter_element.val(index + 1);

    ajax = $.ajax({
        type: 'POST',
        url: '/rx/store_controller.php',
        data:$('#' + form).serialize() + '&index=' + index,
        success: function(response) {

            if ( response.status === 'ok' ) {
                var innerHtml = response.taafathlete_row;
                var row = document.createElement('tr');
                target.parentNode.insertBefore(row, target.nextSibling);

                row.id = 'tr_' + index;
                if (( listform !== undefined ) && ( listform !== null )) {
                    row.id = listform + '_' + tableID + '-' + index;
                }

                $(row).html(innerHtml);
                $(row).css("background-color", "lemonchiffon");
                setupTable();

                var field_price_element = $('#'+tableID+'_price');
                var current_price = parseFloat(field_price_element.val());

                var row_price_element = $('#'+tableID + '-' + index+'_price');
                var row_current_price = parseFloat(row_price_element.val());
                //  todo figure out why this didn't work
                var region = $('#'+tableID+'_region').val();
                //  NOTE Pricing for relays = 4 * event price
                var current_form_id = $('#storeitem_id').val();
                var registration_price = parseFloat(40);
                if ( track_or_swim === "track" ) {
                    //  taaf_regions_event_price
                    //  $taaf_7DollarEvent_track_regions
                    //  $taaf_8DollarEvent_track_regions
                    if ( region === '2' )  registration_price = parseFloat(28);
                    else if ( region === '3' )  registration_price = parseFloat(30);
                    else if (( region === '12' ) || ( region === '13' ))  registration_price = parseFloat(32);
                    else if (( region === '11' ))  registration_price = parseFloat(48);
                }
                else if ( track_or_swim === "swim" ) {
                    //  $taaf_3DollarEvent_swim_regions
                    //  $taaf_6DollarEvent_swim_regions
                    //  $taaf_7DollarEvent_swim_regions
                    if ( region === '17' ) registration_price = parseFloat(12);
                    else if ( region === '11' ) registration_price = parseFloat(24);
                    else if ( region === '2' )  registration_price = parseFloat(28);
                }

                var new_price;
                var row_new_price;
                new_price = current_price + registration_price;
                row_new_price = row_current_price + registration_price;

                field_price_element.val(new_price);
                row_price_element.val(row_new_price);
                updateFormPrice('paypal_buy_now');

                for (let i = 1; i <= 4; i++) {
                    let i_string = i.toString();
                    let selected_relay_member = $('#' + form +' #member_'+i_string+'_select').val();
                    if (( selected_relay_member !== '' ) && ( selected_relay_member !== null )) {
                        let selected_relay_event = $("input[name='taafrelay_event']:checked").val();
                        let member_registration_rowid = $('#rowid_for_taafathleteid_'+selected_relay_member).val();
                        $('#' + member_registration_rowid + '-' + selected_relay_event).val('on');

                    }
                }

                unblock_screen('Done');
            } else {
                alert("Error adding relay. Please try again.");
                unblock_screen('Done');
            }
        },
        error: function(response) {
            alert("Error adding relay. Please try again.");
            unblock_screen('Done');
        }
    });
    return true;
}


function TAAF_editRelay(relay_id, form, tableID) {
    //  TODO - test required fields
    block_screen('Editing Relay');

    let table_relay_id = '#'+relay_id;
    let track_or_swim = $('#'+form+' #track_or_swim').val();

    let event_element = $("input[name='taafrelay_event']:checked");
    let age_division_option_element = $('#'+form+' #taafrelay_AgeDivision option:selected');
    let member_1_element = $('#' + form+' #member_1_select option:selected');
    let member_2_element = $('#' + form+' #member_2_select option:selected');
    let member_3_element = $('#' + form+' #member_3_select option:selected');
    let member_4_element = $('#' + form+' #member_4_select option:selected');

    var event_prompt = '';
    var gender_value = '';
    var gender_prompt = '';
    if ( track_or_swim === 'track' ) {
        if ( event_element.val() === 'relay400' )  event_prompt = '4x100m';
        else if ( event_element.val() === 'relay1600' )  event_prompt = '4x400m';

        gender_value = $("input[name='taafrelay_gender']:checked").val();
        if ( gender_value === 'female' )  gender_prompt = 'F';
        else if ( gender_value === 'male' )  gender_prompt = 'M';

    } else if ( track_or_swim === 'swim' ) {
        let event_value = event_element.val();
        let event_distance = event_value.substring(5,8);
        let event_stroke = event_value.substring(8,9);

        var event_stroke_prompt = 'Free';
        if ( event_stroke === '6' )  event_stroke_prompt = 'Medley';
        event_prompt = event_distance + ' ' + event_stroke_prompt;

        gender_value = event_value.substring(9);
        if ( gender_value === 'f' ) {
            gender_value = 'female'
            gender_prompt = 'F';
        } else if ( gender_value === 'm' ) {
            gender_value = 'm';
            gender_prompt = 'M';
        } else if ( gender_value === 'x' ) {
            gender_value = 'mixed'
            gender_prompt = 'Mix';
        }
    }

    $(table_relay_id+'-taafrelay_event').val(event_element.val());
    $(table_relay_id+'-taafrelay_event_staticdisplay').val(event_prompt);
    $(table_relay_id+'-taafrelay_gender').val(gender_value);
    $(table_relay_id+'-taafrelay_gender_staticdisplay').val(gender_prompt);
    $(table_relay_id+'-taafrelay_name').val($('#'+form+' #taafrelay_name').val());

    $(table_relay_id+'-taafrelay_AgeDivision').val(age_division_option_element.val());
    $(table_relay_id+'-taafrelay_AgeDivision_staticdisplay').val(age_division_option_element.text());



    $(table_relay_id+'-taafrelay_member_1_id').val(member_1_element.val());
    $(table_relay_id+'-taafrelay_member_1').val(member_1_element.text());
    $(table_relay_id+'-taafrelay_member_2_id').val(member_2_element.val());
    $(table_relay_id+'-taafrelay_member_2').val(member_2_element.text());
    $(table_relay_id+'-taafrelay_member_3_id').val(member_3_element.val());
    $(table_relay_id+'-taafrelay_member_3').val(member_3_element.text());
    $(table_relay_id+'-taafrelay_member_4_id').val(member_4_element.val());
    $(table_relay_id+'-taafrelay_member_4').val(member_4_element.text());

    let member_5_element = $('#' + form+' #member_5_select option:selected');
    let member_6_element = $('#' + form+' #member_6_select option:selected');
    if ( member_5_element.val() === '' ) {
        $(table_relay_id+'-taafrelay_member_5_id').val('');
        $(table_relay_id+'-taafrelay_member_5').val('');
        $(table_relay_id+'-taafrelay_member_6_id').val('');
        $(table_relay_id+'-taafrelay_member_6').val('');
    } else {
        $(table_relay_id+'-taafrelay_member_5_id').val(member_5_element.val());
        $(table_relay_id+'-taafrelay_member_5').val(member_5_element.text());
        if ( member_6_element.val() === '' ) {
            $(table_relay_id+'-taafrelay_member_6_id').val('');
            $(table_relay_id+'-taafrelay_member_6').val('');
        } else {
            $(table_relay_id+'-taafrelay_member_6_id').val(member_6_element.val());
            $(table_relay_id+'-taafrelay_member_6').val(member_6_element.text());
        }
    }

    for (let i = 1; i <= 4; i++) {
        let i_string = i.toString();
        let selected_relay_member = $('#' + form +' #member_'+i_string+'_select').val();
        if (( selected_relay_member !== '' ) && ( selected_relay_member !== null )) {
            let member_registration_rowid = $('#rowid_for_taafathleteid_'+selected_relay_member).val();
            $('#' + member_registration_rowid + '-' + event_element.val()).val('on');

        }
    }


    unblock_screen('Done');

    return true;
}


function TAAF_removeRelay(row_id, tableID) {
    block_screen('Removing Relay');
    //  NOTE: Hide removed relay's row; Clear relay's fields
    // toggleTR('taafrelayteams_' + row_id);
    toggleTR('taafrelayteams-track_'+row_id);
    toggleTR('taafrelayteams-swim_'+row_id);

    for (let i = 1; i <= 4; i++) {
        let i_string = i.toString();
        var selected_relay_member = $('#' + row_id + '-taafrelay_member_'+i_string+'_id').val();
        if (( selected_relay_member !== '' ) && ( selected_relay_member !== null )) {
            let member_registration_rowid = $('#rowid_for_taafathleteid_'+selected_relay_member).val();
            let selected_relay_event = $('#' + row_id + '-taafrelay_event').val();
            $('#' + member_registration_rowid + '-' + selected_relay_event).val('');
        }
    }

    //  NOTE: this does not clear row price, because we look for row_id "-" not "_"
    $('[id^="' + row_id + '-"]').val('');

    let field_price_element = $('#'+tableID+'_price');
    let row_price_element = $('#'+row_id+'_price');
    let new_price = parseFloat(field_price_element.val()) - parseFloat(row_price_element.val());

    field_price_element.val(new_price);
    row_price_element.val('0');
    updateFormPrice('paypal_buy_now');


    unblock_screen('Relay Removed');
}





function clearSelectOptions(field_name) {
    $("#blob_" + field_name).val('');
    $("#blob_" + field_name + "_newflag").val('');
    updateAllFieldsM3();
}



function addRowToList(tableID, rowtype, isorg, context) {
    block_screen('Adding row');

    //  transitioning from _listform to listform_
    var listform = $('#listform_' + tableID).val();
    var listform_test = $('#' + tableID + '_listform').val();
    if ( listform !== listform_test ) {
        var test = 1;
    }

    var table = document.getElementById('table_' + tableID);
    var lastRowIndex = table.rows.length - 1;
    var target = table.rows[lastRowIndex];
    while (( target.className !== 'smart_list_x' ) && !target.id.startsWith(listform+'_'+tableID+'-') ) {
        lastRowIndex--;
        target = table.rows[lastRowIndex];
    }

    let rowcounter_element = $('#' + tableID + '_rowcounter');
    var index = parseInt(rowcounter_element.val());
    if ( Number.isNaN(index) )  index = 0;
    rowcounter_element.val(index + 1);



    var storeitem_id = $('#storeitem_id').val();
    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'add_row', prefix: tableID, index:index, rowtype: rowtype, isorg: isorg, context: context, s_id:storeitem_id },

        success:function (response) {
            unblock_screen('X');
            var innerHtml = response;
            var row = document.createElement('tr');
            target.parentNode.insertBefore(row, target.nextSibling);

            row.id = 'tr_' + index;
            //  SET tr id FOR NEW ROWS (ensures delete fnc works for lista)
            if (( listform !== undefined ) && ( listform !== null )) {
                row.id = listform + '_' + tableID + '-' + index;
            }

            $(row).html(innerHtml);
            setupTable();
        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}

function addRowParams() {

    $("#sizes").val("");
    var colors = $("").val();

}

function addRow(tableID, rowtype, isorg, context) {

    //block_screen('27');
    block_screen('Adding Field');

    var table = document.getElementById(tableID);
    var sizes = $("#sizes").val();
    var colors = $("#colors").val();

    var index = parseInt($("#rowcounter").val());
    nextindex = index + 1;
    $("#rowcounter").val(nextindex);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = "tr_" + index;

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'getformrow', index:index, rowtype: rowtype, isorg: isorg, sizes: sizes, colors: colors, context: context },

        success:function (response) {
            unblock_screen('X');
            if (response) {
                var innerHtml = response;
                $(row).html(innerHtml);
                setupTable();
            }
        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}


function addRowStoreitem(tableID, rowtype, isorg, context, storeitem_id) {

    block_screen('28');
    // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 28</p></div>' });

    var table = document.getElementById(tableID);
    var sizes = $("#sizes").val();
    var colors = $("#colors").val();

    var index = parseInt($("#rowcounter").val());
    nextindex = index + 1;
    $("#rowcounter").val(nextindex);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    row.id = "tr_" + index;

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'getformrow', index:index, rowtype: rowtype, isorg: isorg, sizes: sizes, colors: colors, context: context , storeitem_id: storeitem_id },

        success:function (response) {
            unblock_screen('X');
            if (response) {
                var innerHtml = response;
                $(row).html(innerHtml);
                // setBlur();
                setupTable();
            }
        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}



/*
function addOption(tableID, fieldId, optiontype) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount - 1);
    row.id = "tr_" + fieldId + "_" + (rowCount + 10);

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{ action:'getoptionrow', row_template:optiontype, index:fieldId, jndex:(rowCount + 10) },
        success:function (response) {
            if (response) {
                var innerHtml = response;
                $(row).html(innerHtml);
                // set focus
                // setBlur();
            }
        },

        error:function (x, status, errorThrown) {
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });
    return;
}
*/

function addOptionContext(tableID, fieldId, optiontype, context) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount - 1);
    row.id = "tr_" + fieldId + "_" + (rowCount + 10);

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{ action:'getoptionrow', row_template:optiontype, index:fieldId, jndex:(rowCount + 10), context: context },
        success:function (response) {
            if (response) {
                var innerHtml = response;
                $(row).html(innerHtml);
                // setBlur();
            }
        },

        error:function (x, status, errorThrown) {
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });
    return;
}


function addOption2(prefix,optiontype, context) {

    var table = document.getElementById('table_' + prefix );

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount - 1);
    var new_prefix = prefix + "_" + (rowCount + 10);
    row.id = "tr_" + new_prefix ;

    block_screen('29');
    // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 29</p></div>' });

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{ action:'getoptionrow', row_template:optiontype, prefix:new_prefix, context: context },
        success:function (response) {

            unblock_screen('X');
            if (response) {

                var innerHtml = response;
                $(row).html(innerHtml);

                // if sortable
                $(row).addClass("ui-sortable-handle");


                // set focus
                // setBlur();
            }
        },

        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });
    return;
}


function addOption2Storeitem(prefix,optiontype, context, storeitem_id) {

    var table = document.getElementById('table_' + prefix );

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount - 1);
    var new_prefix = prefix + "_" + (rowCount + 10);
    row.id = "tr_" + new_prefix ;

    block_screen('30');
    // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 30</p></div>' });

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{ action:'getoptionrow', row_template:optiontype, prefix:new_prefix, context: context, storeitem_id: storeitem_id },
        success:function (response) {

            unblock_screen('X');
            if (response) {

                var innerHtml = response;
                $(row).html(innerHtml);

                // if sortable
                $(row).addClass("ui-sortable-handle");


                // set focus
                // setBlur();
            }
        },

        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });
    return;
}

function deleteRowId(id) {
    //alert( "deleteRowId:" + id );
    var el = document.getElementById(id);
    el.parentNode.removeChild(el);
}


function updateSelectField(control, object, name, id) {

    var select  = $("#" + control).val();
    $("#td_" + control).css('background', '#ff0000');

    $.ajax({
        type:'post',
        url:'rx/master_controller.php',
        data:{action:'toggle3',  object: object, id:id , name: name , value: select},

        success:function (response) {
            var result = response;
            $("#td_" + control).css('background', '#ffffff');
        },
        error:function (x, status, errorThrown) {
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}

//  THIS ONE TAKES A VALUE....
function updateSelectField2(value, object, name, id) {

    $.ajax({
        type:'post',
        url:'rx/master_controller.php',
        data:{action:'toggle3',  object: object, id:id , name: name , value: value},

        success:function (response) {
            var result = response;
        },
        
        error:function (x, status, errorThrown) {
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}


function toggleInputNew(ii, object, form_name, field, control, context) {
    block_screen('71');

    var input_value = $("#" + control).val();

    $.ajax({
        type:'post',
        url:'rx/master_controller.php',
        data:{action:'toggle_input_new', id:ii, object:object, form_name:form_name, field_name:field, value:input_value, context:context},

        success:function (response) {
            unblock_screen('71s');

            var result = response;
            if ( result.status == 'ok' ) {
                $('#messagefieldtop').html(result.msg);
            }
        },
        error:function (x, status, errorThrown) {
            unblock_screen('71e');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}

function toggleControl(ii, form_name, field, select, context) {

    block_screen('71');

    $.ajax({
        type:'post',
        url:'rx/master_controller.php',
        data:{action:'toggle_control', id:ii, form_name: form_name, field_name:field, value:select, context:context},

        success:function (response) {
            unblock_screen('71s');
            var result = response;
            if ( result.status == 'ok' ) {
                if ( result.value_prompt.length > 0 )  $('#control_' + ii +'_' + field).html(result.value_prompt);
                if ( result.value_color.length > 0 )  $('#control_'+ii + '_' + field).css('background-color', result.value_color);
                if ( result.value_font_color.length > 0 )  $('#control_' + ii +'_' + field).css('color', result.value_font_color);
            }
        },
        error:function (x, status, errorThrown) {
            unblock_screen('71e');

            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}



function VSR_updateSeedApproval(row_id, updated_field, context, report) {
    block_screen('Updating Corral');

    var seed_approval = $('#seed_' + row_id).val();
    var corral = $('#corral_' + row_id).val();
    var approval = '';
    var email_sent = '';
    if ( report === 'smart_list' ) {
        var row_ii = $('#' + row_id+'_ii').val();
        corral = $('#' + row_id+'-' +row_ii + '-blob_Whatsyourestima_4').val();
        var approved = $('#' + row_id+'-' +row_ii + '-blob_YC_ReviewedByTim').is(':checked');
        if ( updated_field === 'corral' ) {
            approval = 'on';
        } else if ( updated_field === 'approval' ) {
            if ( approved )  approval = 'on';
        } else if ( updated_field === 'email' ) {
            var emailed = $('#' + row_id+'-' +row_ii + '-blob_YC_MoveEmailSent').is(':checked');
            if ( emailed )  email_sent = 'on';
        }
    }

    $.ajax({
        type:'post',
        //  16Oct2024 KylaUpdate - added slash before rx
        //url:'/rx/master_controller.php',
        url:'/rx/master_controller.php',
        data:{action:'vsr_update_seed_approval', row_id:row_id, context:context, updated_field:updated_field, seed_approval:seed_approval, corral:corral, yellow_approval:approval, yellow_email:email_sent},

        success:function (response) {
            unblock_screen('Done Updating Corral');

            if ( report === 'smart_list' ) {
                var row_ii = $('#' + row_id+'_ii').val();
                if ( $('#td_' + row_id+'-'+row_ii + '_blob_YC_ReviewedByTim').length && ( updated_field === "corral" )) {
                    //$('#td_' + row_id+'-'+row_ii + '_blob_YC_ReviewedByTim').html('yes');
                    $('#' + row_id + '-' + row_ii + '-blob_YC_ReviewedByTim').prop('checked', true);
                }
            }
            var result = response;
            if ( result.status == 'ok' ) {}
        },
        error:function (x, status, errorThrown) {
            unblock_screen('Error Updating Corral');

            if ( status == "error" ) {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}


function updateDoComplete(ii, select, form, field, context) {

    block_screen('31');

    hideDiv('checkit_' + ii);
    hideDiv('undocheck_' + ii);

    $.ajax({

        type:'post',
        url:'rx/master_controller.php',
        data:{action:'toggle6',  form: form,  id:ii , name: field,  value: select, context : context},

        success:function (response) {

            unblock_screen('X');
            var result = response;
            if ( result.status == 'ok' ) {

                $('#messagefieldtop').html('');
                if ( select  == "on" ) {
                    showDivInline('undocheck_' + ii);
                    // CLEAR..

                } else {
                    showDivInline('checkit_' + ii);
                    $("#" + bibid).val("");
                }

                //  TEST THIS
                if ( select == "deleted" )
                    window.location.reload();

            }  else {
                $('#messagefieldtop').html(result.message);
                if ( select  == "on" ) {

                    showDivInline('checkit_' + ii);
                    $('#checkit_' + ii + '_button').css('background-color', '#cc2222');

                } else {

                    showDivInline('undocheck_' + ii);
                    $('#undocheck_' + ii + '_button').css('background-color', '#cc2222');
                }
            }
        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}

function updateDoCheckIn(ii, select, bibid, model, context) {

    // alert("hello 5656 BS1");
    // return;


    block_screen('32');

    // alert("hello 5656 BS2");


    var bibval = $("#" + bibid).val();

    hideDiv('checkit_' + ii);
    hideDiv('undocheck_' + ii);
    hideDiv('day_checkit_' + ii);


    $.ajax({

        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'update_purchase_checkin',  purchase_id:ii , status: select, bibval: bibval, model: model, context : context},

        success:function (response) {
            var result = response;

            // alert("hello 5656 CS");

            if ( result.status == 'ok' ) {
                $('#messagefieldtop').html('');

                if ( select  == "on" ) {
                    showDivInline('undocheck_' + ii);

                } else  if ( select  == "pre" ) {
                    showDivInline('day_checkit_' + ii);

                } else  if ( select  == "day" ) {
                    showDivInline('undocheck_' + ii);

                } else {
                    showDivInline('checkit_' + ii);
                }

                if ( result.redirect == "on" ) {
                    window.location.reload();
                    return;
                }

                unblock_screen('X');

                //  TEST THIS
                if ( select == "deleted" )
                    window.location.reload();

            }  else {
                unblock_screen('X');

                $('#messagefieldtop').html(result.message);
                if ( select  == "on" ) {
                    showDivInline('checkit_' + ii);
                    $('#checkit_' + ii + '_button').css('background-color', '#cc2222');

                } else if ( select  == "pre" ) {
                    showDivInline('checkit_' + ii);
                    $('#checkit_' + ii + '_button').css('background-color', '#ff3700');

                } else {
                    showDivInline('undocheck_' + ii);
                    $('#undocheck_' + ii + '_button').css('background-color', '#cc2222');
                }
            }
        },
        error:function (x, status, errorThrown) {

            // alert("hello 5656 CE");
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    // alert("hello 5656 BE");
    return;
}


function updateDoCheckInGrowRuck(ii, select, bibid, model, context) {

    block_screen('32');

    var bibval = $("#" + bibid).val();

    hideDiv('checkit_' + ii);
    hideDiv('complete_checkit_' + ii);
    hideDiv('complete_done_' + ii);
    hideDiv('medout_checkit_' + ii);
    hideDiv('medout_done_' + ii);
    hideDiv('volout_checkit_' + ii);
    hideDiv('volout_done_' + ii);
    hideDiv('undocheck_' + ii);

    $.ajax({

        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'update_purchase_checkin',  purchase_id:ii , status: select, bibval: bibval, model: model, context : context},

        success:function (response) {
            var result = response;

            if ( result.status == 'ok' ) {

                // alert("hello 1:" + select );

                $('#messagefieldtop').html('');

                if ( select  == "on" ) {
                    showDivInline('undocheck_' + ii);

                } else  if ( select  == "checkedin" ) {
                    showDivInline('complete_checkit_' + ii);
                    showDivInline('medout_checkit_' + ii);
                    showDivInline('volout_checkit_' + ii);
                    showDivInline('undocheck_' + ii);

                } else  if ( select  == "complete" ) {
                    showDivInline('complete_done_' + ii);
                    showDivInline('undocheck_' + ii);

                } else  if ( select  == "medout" ) {
                    showDivInline('medout_done_' + ii);
                    showDivInline('undocheck_' + ii);

                } else  if ( select  == "volout" ) {
                    showDivInline('volout_done_' + ii);
                    showDivInline('undocheck_' + ii);

                } else {
                    showDivInline('checkit_' + ii);
                }

                if ( result.redirect == "on" ) {
                    window.location.reload();
                    return;
                }

                unblock_screen('X');

                //  TEST THIS
                if ( select == "deleted" )
                    window.location.reload();

            }  else {
                unblock_screen('X');

                $('#messagefieldtop').html(result.message);
                if ( select  == "on" ) {
                    showDivInline('checkit_' + ii);
                    $('#checkit_' + ii + '_button').css('background-color', '#cc2222');

                } else if ( select  == "pre" ) {
                    showDivInline('checkit_' + ii);
                    $('#checkit_' + ii + '_button').css('background-color', '#ff3700');

                } else {
                    showDivInline('undocheck_' + ii);
                    $('#undocheck_' + ii + '_button').css('background-color', '#cc2222');
                }
            }
        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}



function updateDoCheckInLeave(ii, select, bibid, model, context) {

    block_screen('33');

    var bibval = $("#" + bibid).val();
    if ( bibval == null ) {
        model = "old";
    }

    hideDiv('checkit_' + ii);
    hideDiv('undocheck_' + ii);

    $.ajax({

        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'update_purchase_checkin',  purchase_id:ii , status: select, bibval: bibval, model: model, context: context },

        success:function (response) {

            unblock_screen('X');
            var result = response;
            // window.location = '<?php print gurl2("filter-purchase_id=&docheckin="); ?>'
            window.location.reload();


        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}

function updateDoVolCheckIn(ii , option_name, select, context) {

    block_screen('34');
    // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 34</p></div>' });

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'update_volunteer_checkin',  purchase_id:ii , option_name: option_name, status: select, context: context},

        success:function (response) {

            unblock_screen('X');
            var result = response;

            if ( result.status == 'ok' ) {

                //  TEST THIS
                if ( select == "deleted" ) {
                    window.location.reload();
                }

            } else {
                window.location.href = "dumpmsg.php?msg=" + result.msg;

                if ( result.message != null ) {
                    $('#messagefieldtop').html(result.message);
                    $('#messagefieldbottom').html(result.message);
                } else if ( result.msg != null ) {
                    $('#messagefieldtop').html(result.msg);
                    $('#messagefieldbottom').html(result.msg);
                } else  {
                    $('#messagefieldtop').html("ERROR - #8756502  processing your request, please call (919) 948-0758");
                    $('#messagefieldbottom').html("ERROR - #8756 processing your request, please call (919) 948-0758");
                }
            }
        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}




function updateActForm(formtype, user_id, event_id, template_id, context) {

    var select  = $("#storeitem_id_select").val();

    if ( select == 1 ) {
        hideDiv('regnewform');
        showDiv('reghelp');
        return;
    } else {
        hideDiv('reghelp');
        showDiv('regnewform');
    }

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{ action:'get_storeitem', formtype: formtype, userid: user_id, eventid: event_id, templateid: template_id, storeitem_id:select, context: context, source:'postworkout' },

        success:function (response) {

            var result = response;

            if ( result.status == 'ok' ) {
                var innerHtml = result.body;
                $('#regnewform').html(innerHtml);
                showDiv('regnewform');

            }  else {
                $('#messagefieldtop').html(result.message);
                $('#messagefieldbottom').html(result.message);
            }

        },
        error:function (x, status, errorThrown) {
            if ( status == 'error' ) {
                var errorMsg = '';
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });

    return;
}

function updateCategory(form)
{
    block_screen('35');
    // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 35</p></div>' });

    var select = $("#" + form + " #storeitem_couponstoreitem").val();

    $.ajax({
        type:'post',
        url:'/rx/store_controller.php',
        data:{action:'update_category', storeitem_id:select },
        success:function (response) {
            unblock_screen('X');
            var innerHtml = response.body;
            $('#' + form + ' #td_couponcategory').html(innerHtml);
        },
        error:function (x, status, errorThrown) {
            unblock_screen('X');
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });
    return true;
}

function updateAddressFieldDetailsForm(id) {

    var test = $("#"+id).length;
    if ( test == 0 )  return;
    var select = $("#" + id).val();

    return;
    //  20Feb2024 TODO - we need to fix this so this div is toggled on/off instead of just being shown/hidden upon load
    //  TODO - currently this fnc returns and does nothing

    //alert("hello:" + select );

    //  05Jan2022 KylaThoughts - better way since no duplicate selectors?
    //var country_element = $("#" + id);
    //if ( !country_element.length )  return;
    //var select = country_element.val();

    if (( select == "US" ) || ( select == "" )) {
        //$('#Zipcode').html('Zip Code');
        showDiv('DivState');
        $('#State').html('State');

        // $('#blob_state').find('option').remove()
        // var $options = $('#blob_state_usa_options > option').clone();
        // $('#blob_state').append($options);

    } else if ( select == "CA" ) {
        showDiv('blob_state_tr');
        $('#row_blob_zipcode').html('Postal Code');

        $('#row_blob_state').html('Province');
        $('#blob_state').find('option').remove()
        var $options = $('#blob_state_canada_options > option').clone();
        $('#blob_state').append($options);

    } else {
        hideDiv('blob_state_tr');
        $('#row_blob_zipcode').html('Postal Code');
    }
}

function updateAddressField2(id) {

    var test = $("#"+id).length;
    if ( test == 0 )  return;
    var select = $("#" + id).val();

    // alert("hello:" + select );

    //  05Jan2022 KylaThoughts - better way since no duplicate selectors?
    //var country_element = $("#" + id);
    //if ( !country_element.length )  return;
    //var select = country_element.val();

    if (( select == "US" ) || ( select == "" )) {
        $('#row_blob_zipcode').html('Zip Code');
        showDiv('blob_state_tr');
        $('#row_blob_state').html('State');

        $('#blob_state').find('option').remove()
        var $options = $('#blob_state_usa_options > option').clone();
        $('#blob_state').append($options);

    } else if ( select == "CA" ) {
        showDiv('blob_state_tr');
        $('#row_blob_zipcode').html('Postal Code');

        $('#row_blob_state').html('Province');
        $('#blob_state').find('option').remove()
        var $options = $('#blob_state_canada_options > option').clone();
        $('#blob_state').append($options);

    } else {
        hideDiv('blob_state_tr');
        $('#row_blob_zipcode').html('Postal Code');
    }
}

function updateAddressFields(base_id) {

    var country_field = $('#' + base_id + '_country');

    if ( country_field.length == 0 ) {
        return;
    }

    var selected_country = country_field.val();

    if ( selected_country == "US" ) {
        showDiv(base_id + '_state_tr');

        //  CHANGE TEXT FOR STATE FIELD (and add required * if applicable)
        if ( $('#row_' + base_id + '_state').html().indexOf("*</span>") >= 0 ) {
            $('#row_' + base_id + '_state').html('State <span class="field_required">*</span>');
        } else {
            $('#row_' + base_id + '_state').html('State');
        }

        var $options = $('#' + base_id + '_state_usa_options > option').clone();
        //$('#' + base_id + '_state').find('option').remove()
        //$('#' + base_id + '_state').append($options);
        $('#' + base_id + '_state').empty().append($options);


        //  CHANGE TEXT FOR ZIP CODE FIELD (and add required * if applicable)
        if ( $('#row_' + base_id + '_zipcode').html().indexOf("*</span>") >= 0 ) {
            $('#row_' + base_id + '_zipcode').html('Zip Code <span class="field_required">*</span>');
        } else {
            $('#row_' + base_id + '_zipcode').html('Zip Code');
        }

    } else if ( selected_country == 'CA' ) {
        showDiv(base_id + '_state_tr');

        //  CHANGE TEXT FOR STATE FIELD (and add required * if applicable)
        if ( $('#row_' + base_id + '_state').html().indexOf("*</span>") >= 0 ) {
            $('#row_' + base_id + '_state').html('Province <span class="field_required">*</span>');
        } else {
            $('#row_' + base_id + '_state').html('Province');
        }

        var $options = $('#' + base_id +'_state_canada_options > option').clone();
        //$('#' + base_id + '_state').find('option').remove()
        //$('#' + base_id + '_state').append($options);
        $('#' + base_id + '_state').empty().append($options);

        //  CHANGE TEXT FOR ZIP CODE FIELD (and add required * if applicable)
        if ( $('#row_' + base_id + '_zipcode').html().indexOf("*</span>") >= 0 ) {
            $('#row_' + base_id + '_zipcode').html('Postal Code <span class="field_required">*</span>');
        } else {
            $('#row_' + base_id + '_zipcode').html('Postal Code');
        }

    } else {
        hideDiv(base_id + '_state_tr');
        //  CHANGE TEXT FOR ZIP CODE FIELD (and add required * if applicable)
        if ( $('#row_' + base_id + '_zipcode').html().indexOf("*</span>") >= 0 ) {
            $('#row_' + base_id + '_zipcode').html('Postal Code <span class="field_required">*</span>');
        } else {
            $('#row_' + base_id + '_zipcode').html('Postal Code');
        }
    }

    return;
}


function submitTab5(url, format, qs, eventId) {
    if (format == "dialog") {
        showEventDetails5(qs, eventId );
    } else if ( format == "wpf" ) {
        submitUrlParent( url );
    } else {
        submitUrl( url );
    }
    return false;
}


function getAge(birthDate) {
    var now = new Date();

    // days since the birthdate
    var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
    var age = 0;
    // iterate the years
    for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
        var daysInYear = isLeap(y) ? 366 : 365;
        if (days >= daysInYear){
            days -= daysInYear;
            age++;
            // increment the age only if there are available enough days for the year.
        }
    }
    return age;
}


/*
function getAgeWhen(birthDate, when) {
    var now = new Date();
    if ( when != null ) {
        var parts = when.split('-');
        var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
        now = Date(mydate);
    }
    // days since the birthdate
    var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
    var age = 0;
    // iterate the years
    for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
        var daysInYear = isLeap(y) ? 366 : 365;
        if (days >= daysInYear){
            days -= daysInYear;
            age++;
            // increment the age only if there are available enough days for the year.
        }
    }
    return age;
}
*/


function isLeap(year) {
    return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}


//  23Feb2024 KylaUpdate - removed unused fnc
/*
function showProductCodes(field_name)
{
    var val = $('#field_pcode_'+ field_name).prop('checked')
    if ( val  ) {
        $("input[name^='pcode_field_"+ field_name + "_productoption_']").show();
    } else {
        $("input[name^='pcode_field_"+ field_name + "_productoption_']").hide();
    }
}
*/



function updateRegStatus() {

    var status = $("#formedit #storeitem_status option:selected").val();

    if ( status == 'notusing') {
        showDiv('reglayout_notusing');
        hideDiv('reglayout_active');
        hideDiv('regform_active');
        hideDiv('regform_coming');
        hideDiv('regform_soldout');
        hideDiv('regform_closed');
    } else {
        showDiv('reglayout_active');
        hideDiv('reglayout_notusing');
        showDiv('regform_active');
        showDiv('regform_coming');
        showDiv('regform_soldout');
        showDiv('regform_closed');
    }

}

/*
function updateRegStatus1() {

    var status = $("#formedit #storeitem_status option:selected").val();

    hideDiv('regform_active');
    hideDiv('regform_coming');
    hideDiv('regform_soldout');
    hideDiv('regform_closed');

    if ( status == 'coming') {
        showDiv('regform_coming');
    }
    else if ( status == 'sold') {
        showDiv('regform_soldout');
    } else if ( status == 'inactive') {
        showDiv('regform_closed');
    } else if ( status == 'notusing') {
    } else if ( status == '') {
    } else {
        showDiv('regform_active');
    }

}
*/

function updateRegStatus2(id) {

    var status = $("#form_use").is(':checked');

    if ( !status ) {
        showDiv('reglayout_notusing');
        hideDiv('reglayout_active');

        // set status to not using...
        updateSelectField2( "notusing","storeitem" , "storeitem_status",    id );
        $("#storeitem_status").val("notusing");

    } else {
        showDiv('reglayout_active');
        hideDiv('reglayout_notusing');
        $("#storeitem_status").val("active");
    }

}

function handle_team_radio(id) {
    var control = '' + id +'_teamcat_team';
    var status = $('input:radio[name=' + control + ']:checked').val();

    var control_category = '' + id +'_teamcat';
    var status_category = $('input:radio[name=' + control_category + ']:checked').val();


    //  maxmem is being phased out
    if ( status != "teamind" ) {
        hideDiv('maxmem_' + id);
    } else {
        showDivInline('maxmem_' + id);
    }

    //  HIDE AND SHOW maxmemcap
    if ( status != "team" ) {
        hideDiv('maxmemcap_' + id);
    } else {
        showDiv('maxmemcap_' + id);
    }

    //  HIDE AND SHOW teammanager_settings
    if ( status != "teammanager" ) {
        hideDiv('teammanager_settings_' + id);
    } else {
        showDiv('teammanager_settings_' + id);
    }

    if (( status == "teammanager" ) || ( status_category == "teamdivider" )) {
        $("#"+ id + "_notrealreg").prop("checked", true);
        $("#"+ id + "_notrealreg").attr("disabled", true);

    } else if (( status == "team" ) || ( status == "teamind" ) || ( status == "teampaid" ) || ( status == "teamind_paying" )) {
        $("#"+ id + "_notrealreg").prop("checked", false);
        $("#"+ id + "_notrealreg").attr("disabled", true);

    } else if (( status_category == "" ) || ( status == "teampart" )) {
        $("#"+ id + "_notrealreg").prop("checked", false);
        $("#"+ id + "_notrealreg").removeAttr("disabled");
    }
}


function handle_category_radio(id) {
    var control_teamcategory = id + '_teamcat_team';
    var status_teamcategory = $('input:radio[name=' + control_teamcategory + ']:checked').val();

    var control_category = id + '_teamcat';
    var status_category = $('input:radio[name=' + control_category + ']:checked').val();

    if ( status_category == '' ) {
        hideDiv('team_options_' + id);
        hideDiv(id + '_collapse');
        showDiv(id + '_category_prices');
        showDiv(id + '_category_restrictions');
        showDiv(id + '_hide_pricing_div');

        $('#' + id + '_category_label').text('Individual').css('background-color', 'pink');
        //$('#' + id + '_category_label').css('background-color', 'pink');
        $('#' + id + '_notrealreg').prop('checked', false).removeAttr('disabled');
        //$('#' + id + '_notrealreg');

    } else if ( status_category == 'teamdivider' ) {
        hideDiv('team_options_' + id);
        showDiv(id + '_collapse');
        hideDiv(id + '_category_prices');
        hideDiv(id + '_category_restrictions');
        hideDiv(id + '_hide_pricing_div');

        $('#' + id + '_category_label').text('Divider').css('background-color', 'gainsboro');
        //$('#' + id + '_category_label');
        $('#' + id + '_notrealreg').prop('checked', true).attr('disabled', true);
        //$('#' + id + '_notrealreg');

    } else {
        showDiv('team_options_' + id);
        hideDiv(id + '_collapse');
        showDiv(id + '_category_prices');
        showDiv(id + '_category_restrictions');
        showDiv(id + '_hide_pricing_div');

        $('#' + id + '_notrealreg').attr('disabled', true);

        if (( status_teamcategory == 'teammanager' ) || ( status_teamcategory == 'teampart' )) {
            $('#' + id + '_notrealreg').prop('checked', true);
            if ( status_teamcategory == 'teampart' ) {
                $('#' + id + '_category_label').text('Team Affiliate').css('background-color', 'palegreen');
            } else {
                //$('#' + id + '_category_label').text('Paying Team Member').css('background-color', 'palegreen');
            }

        } else if (( status_teamcategory == 'teamind' ) || ( status_teamcategory == 'teampaid' ) || ( status_teamcategory == 'teamind_paying' )) {
            $('#' + id + '_notrealreg').prop('checked', false);
            if ( status_teamcategory == 'teamind' ) {
                $('#' + id + '_category_label').text('Pre-paid Team Member').css('background-color', 'palegreen');
            } else if ( status_teamcategory == 'teampaid' ) {
                $('#' + id + '_category_label').text('Paying Team Member').css('background-color', 'palegreen');
            } else if ( status_teamcategory == 'teamind_paying' ) {
                $('#' + id + '_category_label').text('Team Member (Paying or Pre-paid)').css('background-color', 'palegreen');
            }
        } else if ( status_teamcategory == 'team' ) {
            $('#' + id + '_notrealreg').prop('checked', false).removeAttr('disabled');
            $('#' + id + '_category_label').text('Team Captain').css('background-color', 'paleturquoise');
        }
    }

    //  HIDE AND SHOW maxmemcap
    if ( status_teamcategory != 'team' ) {
        hideDiv('maxmemcap_' + id);
    } else {
        showDiv('maxmemcap_' + id);
    }

    //  HIDE AND SHOW teammanager_settings
    if ( status_teamcategory != 'teammanager' ) {
        hideDiv('teammanager_settings_' + id);
    } else {
        showDiv('teammanager_settings_' + id);
    }
}



function claim_promote(url, share) {
    if ( share != '' ) {
        submitUrlTarget(share);
    }
    dialog_load_noscroll(url);
}



function functionPopUp(thix, message)
{
    staticPopup = true;
    var pos = $(thix).offset();
    var width = $(thix).width();
    var height = $(thix).height();
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    var reposition = {
        left: (pos.left + width) + 'px',
        top: (pos.top + height) + 'px'
    };

    // If the same popup is already shown, then don't requery
    if (currentPosition.left == reposition.left) {
        if (currentPosition.top == reposition.top) {
            return;
        }
    }

    container.css({
        left: reposition.left,
        top: reposition.top
    });

    currentPosition = reposition;

    $('#personPopupContent').html('<img src="/rx/images/ajax-loader.gif" alt="loading" />');

    var lstNames = '<table width="300" >';
    lstNames += '<tr><td align=right><a id="closepopup" class="rolloverOption" style="font-weight:normal;" href="#" >X</a></td></tr>';
    lstNames += '<tr><td>' + message + '</td></tr>';
    lstNames += '</table>';

    var origLeft = container.css('left');
    container.css('left', 0 + 'px');
    $('#personPopupContent').html('<span>' + lstNames + '</span>');
    var availableWidth = $(window).width() - pos.left;
    var availableHeight = $(window).height() - pos.top;
    if (availableWidth < container.width()) {
        var shiftLeft = pos.left - container.width();
        reposition.left = shiftLeft;
        container.css('left', shiftLeft + 'px');
    } else {
        container.css('left', origLeft);
    }
    if (availableHeight < container.height()) {
        var shiftUp = pos.top - (container.height() / 2) - 5;
        if (shiftUp < 0) {
            shiftUp = 20;
        }
        reposition.top = shiftUp;
        container.css('top', shiftUp + 'px');
    }

    currentPosition = reposition;
    container.css('display', 'block');
    return false;
}

//  THESE FUNCTIONS MIGHT BE DUPLICATES...  RESEARCH TOGGLE4 and TOGGLE 5

function updateCheckboxField( control, object , name,  id, key, context ) {

    var select = $('input:checkbox[name=' + control + ']:checked').val()

    $("#td_" + control).css('background', '#ff0000');

    $.ajax({
        type:'post',
        url:'rx/master_controller.php',
        data:{action:'toggle4_value',  object: object, id:id , name: name , value: select, key: key, context : context},

        success:function (response) {
            var result = response;
            $("#td_" + control).css('background', '#ffffff');
        },
        error:function (x, status, errorThrown) {
            if (status == "error") {
                var errorMsg = "";
                if (errorThrown) {
                    errorMsg = errorThrown;
                }
                alert("The call to the server side failed. " + errorMsg);
            }
        }
    });
    return;
}

function strncmp(a, b, length) {
    if ( a == null ) {
        return(false)
    }
    if ( b == null ) {
        return(false)
    }

    a = a.substring(0, length);
    b = b.substring(0, length);

    return a == b;
}

function convert_state_full( state ) {
    state = state.toLowerCase();
    if ( state == "--" ) {
        return( "-- select state --" );
    }
    if ( state == "al" ) {
        return( "Alabama" );
    }
    if ( state == "ak" ) {
        return( "Alaska" );
    }
    if ( state == "az" ) {
        return( "Arizona" );
    }
    if ( state == "ar" ) {
        return( "Arkansas" );
    }
    if ( state == "ca" ) {
        return( "California" );
    }
    if ( state == "co" ) {
        return( "Colorado" );
    }
    if ( state == "ct" ) {
        return( "Connecticut" );
    }
    if ( state == "de" ) {
        return( "Delaware" );
    }
    if ( state == "dc" ) {
        return( "District of Col." );
    }
    if ( state == "fl" ) {
        return( "Florida" );
    }
    if ( state == "ga" ) {
        return( "Georgia" );
    }
    if ( state == "hi" ) {
        return( "Hawaii" );
    }
    if ( state == "id" ) {
        return( "Idaho" );
    }
    if ( state == "il" ) {
        return( "Illinois" );
    }
    if ( state == "in" ) {
        return( "Indiana" );
    }
    if ( state == "ia" ) {
        return( "Iowa" );
    }
    if ( state == "ks" ) {
        return( "Kansas" );
    }
    if ( state == "ky" ) {
        return( "Kentucky" );
    }
    if ( state == "la" ) {
        return( "Louisiana" );
    }
    if ( state == "me" ) {
        return( "Maine" );
    }
    if ( state == "md" ) {
        return( "Maryland" );
    }
    if ( state == "ma" ) {
        return( "Massachusetts" );
    }
    if ( state == "mi" ) {
        return( "Michigan" );
    }
    if ( state == "mn" ) {
        return( "Minnesota" );
    }
    if ( state == "ms" ) {
        return( "Mississippi" );
    }
    if ( state == "mo" ) {
        return( "Missouri" );
    }
    if ( state == "mt" ) {
        return( "Montana" );
    }
    if ( state == "ne" ) {
        return( "Nebraska" );
    }
    if ( state == "nv" ) {
        return( "Nevada" );
    }
    if ( state == "nh" ) {
        return( "New Hampshire" );
    }
    if ( state == "nj" ) {
        return( "New Jersey" );
    }
    if ( state == "nc" ) {
        return( "North Carolina" );
    }
    if ( state == "nm" ) {
        return( "New Mexico" );
    }
    if ( state == "ny" ) {
        return( "New York" );
    }
    if ( state == "nd" ) {
        return( "North Dakota" );
    }
    if ( state == "oh" ) {
        return( "Ohio" );
    }
    if ( state == "ok" ) {
        return( "Oklahoma" );
    }
    if ( state == "or" ) {
        return( "Oregon" );
    }
    if ( state == "pa" ) {
        return( "Pennsylvania" );
    }
    if ( state == "ri" ) {
        return( "Rhode Island" );
    }
    if ( state == "sc" ) {
        return( "South Carolina" );
    }
    if ( state == "sd" ) {
        return( "South Dakota" );
    }
    if ( state == "tn" ) {
        return( "Tennessee" );
    }
    if ( state == "tx" ) {
        return( "Texas" );
    }
    if ( state == "ut" ) {
        return( "Utah" );
    }
    if ( state == "vt" ) {
        return( "Vermont" );
    }
    if ( state == "va" ) {
        return( "Virginia" );
    }
    if ( state == "wa" ) {
        return( "Washington" );
    }
    if ( state == "wv" ) {
        return( "West Virginia" );
    }
    if ( state == "wi" ) {
        return( "Wisconsin" );
    }
    if ( state == "wy" ) {
        return( "Wyoming" );
    }

    return("XX");
}





function dynamicLink(eventId, templateId, status, nowFlag, section, groupid, context, group_name ) {



    switch (section) {
        case "upcoming" :
        case "confirm" :
        case "message" :
            var table = $("#update_" + eventId + "_" + section );
            break;
        case "multi" :
        case "multibanner" :
            var table = $("#multicell_" + eventId );
            break;

        case "nowevent" :
            break;
        case 'list' :
        default :
            var table = $("#row_" + eventId );
            break;
    }

    if ( table != null) {
        table.animate({ opacity:"0.2" }, 500);
    }
    else {
        block_screen('36');
        // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment 36</p></div>' });

    }

    $.ajax({
        type:'post',
        url:'rx/events_controller.php',
        data:{action:status, eventid:eventId, templateid:templateId, format:nowFlag, groupid:groupid, context: context, section: section, group_name: group_name },
        success:function (response) {

            if ( table != null) {
                table.animate({opacity:"1"}, "slow");
            }
            else {
                unblock_screen('X');
            }

            switch ( section ) {
                case 'popup':
                    var innerHtml = response;
                    var foo = $('#row_details_' + eventId);
                    var foo2 = $('#row_details_popup');

                    if (foo2.length > 0) {
                        $('#row_details_popup').html(innerHtml);
                        $('#row_details_popup').show();
                    }  else if (foo.length > 0) {
                        $('#row_details_' + eventId).html(innerHtml);
                        $('#row_' + eventId).hide();
                        $('#row_details_' + eventId).show();
                        eventDetailShown = eventId;
                    }

                    initializeViewCanvasByEventId(eventId);
                    resizeMap(eventId);

                    if (typeof startSlider == 'function') {
                        startSlider();
                    }
                    break;

                case 'list':
                case 'offer':
                    var innerHtml = response;
                    var foo = $('#row_' + eventId);
                    foo.html(innerHtml);
                    break;

                case 'multi' :
                case 'multibanner' :
                    var innerHtml = response;
                    var foo = $('#multicell_' + eventId);
                    foo.html(innerHtml);
                    break;

                case 'upcoming':
                case 'confirm':
                    var innerHtml = response;
                    var foo = $('#row_' + eventId + "_" + section);
                    foo.html(innerHtml);
                    break;

                case 'message':
                    window.location.reload();
                    break;

                case 'nowevent':
                    window.location = "now.php?eventid=" + eventId ;
                    break;
            }
        },
        error:function (response) {
            // do nothing
            alert('Error linking activity');
            table.animate({opacity:"1"}, "fast");
        }
    });
}


function set_bankaccnt_id( bid ) {
    $("#bankaccnt_id").val(bid);
}

function runScript(e) {
    if (e.keyCode == 13) {
        return false;
    }
}



function updateAge(field) {
    var age;

    let VSR_REG_FORM = "57224";

    var year = $('#' + field + '_year').val();
    if ( !(year > 0) ) {
        $('#' + field + '_age').html("");
        return;
    }
    var month =   $('#' + field + '_month').val();
    if ( !(month > 0) ) {
        $('#' + field + '_age').html("");
        return;
    }
    var day = $('#' + field + '_day').val();
    if ( !(day > 0) ) {
        $('#' + field + '_age').html("");
        return;
    }
    dateObj = new Date(year, month-1, day); // months 0-based!
    age = getAge(dateObj);
    if (( age < 6 ) && ( $('#storeitem_id').val() !== VSR_REG_FORM)) {
        $('#' + field + '_age').html("AGE NOW: " + age + " <span style='color:red'>Are you really younger than 6?</span>");
    }  else {
        $('#' + field + '_age').html("AGE NOW: " + age);
    }
}



function toggle_donation_handling() {
    //  09Aug2022 KylaUpdate - added code to exit if the togglehandling element is not found on form
    var toggle_donation_handling_exists = $('#togglehandling').length;
    if ( !toggle_donation_handling_exists ) {
        handling_unbundle_donation_flag = false;
        return;
    }

    var is_checked = $('#togglehandling').prop('checked');
    if ( is_checked ) {
        // alert( "handling check");
        handling_unbundle_donation_flag = true;
    } else {
        // alert( "handling UNcheck");
        handling_unbundle_donation_flag = false;
    }
    //alert(handling_unbundle_donation_flag);
    //  27Jul2022 KylaUpdate - moved this call outside this function
    //updateFormPrice('paypal_buy_now');
}


function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return  num=="-" ? acc : num + (i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}


function voljob_unlock(id, code)
{
    var ucode = $('#' + id + '_passcode').val();
    if ( code != ucode ) {
        alert('Error: incorrect passcode to unlock the job ['+ ucode +']');
    } else {
        alert('Job unlocked');
        $('#' +  id + '_lockicon_div').hide();
        $('#' +  id + '_passcode_div').hide();
        //$('#' +  id + '_voljob_value_div').show();
        showDivInline(id + '_voljob_value_div');
    }
}


//  This function is broken and probably not used.
function showDialogSigninZ(url, user_id) {
    if ( user_id > 0) {
        submitUrl(url);
    } else {
        dialog_load('<?php print gqs("load=connect&mustsignin=on") ?>');
    }
}



function resetCheckbox(checkbox_prefix, real_checkbox) {
    var is_checked = $('#' + real_checkbox).prop('checked');
    $('input:checkbox[id^=' + checkbox_prefix + ']').each(function() { this.checked = false; });
    if ( is_checked ) {
        $("#" +  real_checkbox ).prop('checked', true);
    }
    return(true);
}


function set_all_checkbox(checkbox_prefix, state) {
    if ( state ) {
        $('input:checkbox[id^=' + checkbox_prefix + ']').each(function() { this.checked = true; });
    } else {
        $('input:checkbox[id^=' + checkbox_prefix + ']').each(function() { this.checked = false; });
    }
    return(true);
}


function setHiddenSurvey(id) {
   // Clear all hidden
}

var  global_uiblock_cnt = 0;

function block_screen(id) {
    //alert("START BLOCK: " + id + " : " + global_uiblock_cnt);
    if (global_uiblock_cnt == 0) $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment (' + id + ')</p></div>' });
    // $.blockUI({ baseZ:500000, message:'<div style="margin-top:15px;"><img src="/rx/images/racereach-loader.gif" /> <p style="color:#469BCF;">One Moment ' + id + '</p></div>' });
    global_uiblock_cnt++;
    return true;
}

function unblock_screen(id) {
    //alert("START UNBLOCK: " + id + " : " + global_uiblock_cnt);
    global_uiblock_cnt--;
    //  04Oct2021 KylaQuestion - should we check if global_uiblock_cnt <= 0?
    //  This would prevent errors where the global_uiblock_cnt was not incremented during the block (i.e. block_screen wasn't called)
    if (global_uiblock_cnt == 0)    $.unblockUI();
    //$.unblockUI();
    return true;
}


//  CLEAR VALUE IF FIELD WITH THAT Id CAN BE FOUND
function clearFieldX(id)
{
    if ( $('#' + id).length ) {
        $('#' + id).val('');
    }
}



function AJAX_file_import(form1, form2, file_field_name = 'file_import_field') {


    var messagefieldtop = $('#'+form1+' #messagefieldtop');
    messagefieldtop.html('');

    if ( !$('#'+form1+' #'+file_field_name).val() ) {
        messagefieldtop.html('<span style="font-size:16px" >No file selected.</span>');
        return false;
    }

    block_screen('Importing');

    // var table = document.getElementById('table_' + form2);
    //
    // if (table.length > 0) {
    //     var lastRowIndex = table.rows.length - 1;
    //     var target = table.rows[lastRowIndex];
    //     var rowcounter_input = $('#' + form2 + '_rowcounter');
    //     var index = parseInt(rowcounter_input.val());
    //     if ( Number.isNaN(index) ) {
    //         index = 0;
    //     }
    // }

    // var region = $('#'+form2+'_region').val();
    // fd.append('region', region);

    var ff = document.getElementById(form1);
    var fd = new FormData(ff);

    $.ajax( {
        type:'post',
        url:'/rx/store_controller.php',
        data: fd,
        contentType: false,
        processData: false,
        success:function (response) {
            if ( response.status === 'ok' ) {

                var import_notes = "";
                var missing_keys = response.missing_keys;
                if ( missing_keys.length > 0 ) {
                    import_notes = '<div style="color:brown; padding:0 5px 0 5px">NO Tracking Info imported.<br>Imported file was missing the following column headers:</div>';
                    $.each( missing_keys, function( key, value ) {
                        import_notes = import_notes + '<div style="padding-left:20px" >' + value+'</div>';
                    });
                } else {
                    var new_count = response.count;


                    import_notes = '<div style="padding:0 5px 0 5px">Records with imported Tracking Info: '+new_count+'</div>';
/*
                    var rows_missing_data = response.rows_missing_data;
                    if ( rows_missing_data.length > 0 ) {
                        import_notes = import_notes + '<br><div style="color:brown; padding:0 5px 0 5px">Athletes NOT Imported - missing required data: '+rows_missing_data.length+'</div>';
                        $.each( rows_missing_data, function( key, value ) {
                            import_notes = import_notes + '<div style="padding-left:20px">' + value + '</div>';
                        });
                    }
                    */

                }


                //$('[id^="' + form2 + '_message"]').html(import_notes);
                hideDiv(file_field_name+'_div');
                location.reload();
                unblock_screen('X');
                return true;
            }

            else {
                alert('AJAX_file_import error: ' + response);
                unblock_screen('X');
                return false;
            }
        },

        error:function (x, status, errorThrown) {
            alert('fail');
            unblock_screen('X');
            return false;
        }
    });

    return true;
}
