<div id="viewleadContainer">
</div>

<div class="pagination">
    <button id="prevBtnLogsLeadDetailsPage" class="btn btn-primary"
        onclick="LoadDataPageFunc.Logs.changePage(-1)">Next</button>
    <span id="pageInfo"></span>
    <button id="nextBtnLogsLeadDetailsPage" class="btn btn-primary"
        onclick="LoadDataPageFunc.Logs.changePage(1)">Previous</button>
</div>
<script>  $$ = {};
    $$.UI = {};
    $$.UI.Table = {};
    $$.UI.Table.CreateTable = function (id, theadinnerhtml, bodyinnerhtml) { return CreateTable(id, theadinnerhtml, bodyinnerhtml); };
    $$.UI.Table.GenerateTheadFromArraySimple = function (array) { return GenerateTheadFromArraySimple(array); };
    $$.UI.Table.GenerateTableRowFromArraySimple = function (array) { return GenerateTableRowFromArraySimple(array); };
    $$.UI.ResetBrowserAndCache = function () { return ResetBrowserAndCache(); };
    $$.UI.formatCurrency = function (number, withdecimal = true) { return formatCurrency(number, withdecimal); };
    $$.UI.getDateInGMT8 = function () { return getDateInGMT8(); };
    $$.UI.RunFunctiononMutation = function (targetidToMonitor, callbackfunction) { return RunFunctiononMutation(targetidToMonitor, callbackfunction); };
    $$.UI.Element = {};
    $$.UI.Element.appendtobody = function (string) { return appendtobody(string); };
    $$.UI.Element.Exists = function (ElementIDtext) { ElementExists(ElementIDtext); };
    $$.UI.Element.RemovebyID = function (idstring) { return removeelementbyID(idstring); };
    $$.UI.Element.DeleteById = function (id) { return DeleteElementById(id); }
    $$.UI.Element.getHTML = function (idetext) { return getElementhtml(idtext); };
    $$.UI.Element.setHTML = function (idetext, html) { return setElementhtml(idtext, html); };
    $$.UI.Element.getValue = function (idetext) { return getElementvalue(idtext); };
    $$.UI.Element.setValue = function (idetext,) { return setElementvalue(idtext, value); };
    $$.UI.Validate = {};
    $$.UI.Validate.isValidEmail = function (email) { return isValidEmail(email); };
    $$.UI.Validate.hasValidMobileFormat = function (usernumber) { return hasValidMobileFormat(usernumber); };
    $$.UI.Modal = {};
    $$.UI.Modal.Create = function (modalid, modaltitle, modalbody, modalfooter, modalfooterclose = true, topclosebutton = true, modalbodyclass = 'modal-body', modalheaderclass = 'modal-header') { return createmodal(modalid, modaltitle, modalbody, modalfooter, modalfooterclose, topclosebutton, modalbodyclass, modalheaderclass); };
    $$.UI.Modal.Show = function (idtxt) { return modalshow(idtxt); };
    $$.UI.Modal.Hide = function (idtxt) { return modalhide(); };
    $$.UI.Modal.CreateAndShow = function (modalid, modaltitle, modalbody, modalfooter = '', modalfooterclose = true, topclosebutton = true, modalbodyclass = 'modal-body', modalheaderclass = 'modal-header') { return CreateAndShowModal(modalid, modaltitle, modalbody, modalfooter, modalfooterclose, topclosebutton, modalbodyclass, modalheaderclass); };
    $$.UI.Modal.ModalQuickDismiss = function (modaltitle, modalbody, modalid = '', modaltohide = '', functiontodo = '', conditiontrue = true) { return ModalQuickDismiss(modaltitle, modalbody, modalid, modaltohide, functiontodo, conditiontrue) };
    $$.UI.Modal.ModalContinueCancel = function (modalid, modaltitle, modalbody, continuebuttononclick, cancelbuttontext = 'Cancel', continuebuttontext = 'Continue', continuebuttoncss = 'btn btn-danger', cancelbuttoncss = 'btn btn-warning') { return ModalContinueCancel(modalid, modaltitle, modalbody, continuebuttononclick, cancelbuttontext, continuebuttontext, continuebuttoncss, cancelbuttoncss); };
    $$.UI.Modal.hide = function (modalid) { return hidemodal(modalid); };
    $$.UI.Modal.show = function (modalid) { return showmodal(modalid); };
    $$.UI.col = function (content = '', additionalclass = '') { return col(content, additionalclass); };
    $$.UI.row = function (content = '', additionalclass = '', hidden = false, style = '') { return row(content, additionalclass, hidden, style); };
    $$.UI.dualcolrow = function (colcontent1, colcontent2, rowclass = '', hidden = false, style = '') { return dualcolrow(colcontent1, colcontent2, rowclass, hidden, style); };
    $$.UI.Button = {};
    $$.UI.Button.Default = function (content, value = '', onclick = '', idtext = '', setclass = '', addtionaldata = '') { return button(content, value, onclick, idtext, setclass, addtionaldata); };
    $$.UI.Button.Warning = function (content, value = '', onclick = '', block = '', idtext = '', addclass = '', addtionaldata = '') { return buttonwarning(content, value, onclick, block, idtext, addclass, addtionaldata); };
    $$.UI.Button.Danger = function (content, value = '', onclick = '', block = '', idtext = '', addclass = '', addtionaldata = '') { return buttondanger(content, value, onclick, block, idtext, addclass, addtionaldata); };
    $$.UI.Button.Primary = function (content, value = '', onclick = '', block = '', idtext = '', addclass = '', addtionaldata = '') { return buttonprimary(content, value, onclick, block, idtext, addclass, addtionaldata); };
    $$.UI.Button.HomeMenuButtons = function (buttonicon, buttonText, buttonGo, buttonVariabletoPass = '', iconwidth = '', iconheight = '', buttonstyle = '', buttononclick = '', divclass = '', divid = '', buttonid = '', textclass = '') { return HomeMenuButtons(buttonicon, buttonText, buttonGo, buttonVariabletoPass, iconwidth, iconheight, buttonstyle, buttononclick, divclass, divid, buttonid, textclass); };
    $$.UI.Input = {};
    $$.UI.Input.textInput = function (idtext = '', setclass = '', required = '', placeholder = '', value = '') { return textinput(idtext, setclass, required, placeholder, value); };
    $$.UI.Input.textFormControl = function (idtext = '', addclass = '', required = '', placeholder = '', value = '') { return textformcontrol(idtext, addclass, required, placeholder, value); };
    $$.UI.Card = {};
    $$.UI.Card.Create = function (cardtitle = '', cardid = '', cardtools = '', cardbodyid = '', cardbodytext = '', cardbodyclassadd = '', maincardstyle = '', titlecardhide = false) { return createCard(cardtitle, cardid, cardtools, cardbodyid, cardbodytext, cardbodyclassadd, maincardstyle, titlecardhide); };
    $$.UI.Card.Simple = function (title = '', text = '', id = '') { return CreateCardSimple(title, text, id); };
    $$.UIalt = {};
    $$.UIalt.hrefonclickButtonGO = function (pagename, pagedatastring = '') { return hrefonclickButtonGO(pagename, pagedatastring); };
    $$.UIalt.generateHTMLfromarray = function (prepend, append, array, func) { return generateHTMLfromarray(prepend, append, array, func); };
    $$.UIalt.imgiconuserdefault = function (imgsrc, imgwidth = '', imgheight = '', id = '') { return imgiconuserdefault(imgsrc, imgwidth, imgheight, id); };
    $$.UIalt.UICardStats = {};
    $$.UIalt.UICardStats.UICardStatsDetails = function (Title = '', number = 0, Unit = '', leftORright = 'left', numberid = '') { return UICardStatsDetails(Title, number, Unit, leftORright, numberid); };
    $$.UIalt.UICardStats.UIStatsDetailsArray = function (statsarray) { return UIStatsDetailsArray(statsarray); };
    $$.UIalt.BalanceCard = {};
    $$.UIalt.BalanceCard.UIBalance_WrapperfromArray = function (statsarray) { return UIBalance_WrapperfromArray(statsarray); };
    $$.UIalt.BalanceCard.UIBalance_Wrapper_WalletFooter_Item = function (maintitle = '', onclickstring = '', imgsrc = '', href = '', subtitleline1 = '', subtitleline2 = '', subtitleline3 = '', subtitleline4 = '', imgwidth = '', imgheight = '') { return UIBalance_Wrapper_WalletFooter_Item(maintitle, onclickstring, imgsrc, href, subtitleline1, subtitleline2, subtitleline3, subtitleline4, imgwidth, imgheight); };
    $$.UIalt.BalanceCard.UIBalance_Wrapper_WalletFooter_Item_ButtonGO = function (maintitle, pagename, pagestring = '', iconclass = '', subtitleline1 = '', subtitleline2 = '', subtitleline3 = '', subtitleline4 = '') { return UIBalance_Wrapper_WalletFooter_Item_ButtonGO(maintitle, pagename, pagestring, iconclass, subtitleline1, subtitleline2, subtitleline3, subtitleline4); };
    $$.UIalt.BalanceCard.UIBalance_Wrapper_WalletFooter_ARRAY = function (balancewrapper_item_array) { return UIBalance_Wrapper_WalletFooter_ARRAY(balancewrapper_item_array); };
    $$.UIalt.BalanceCard.UIcreateBalanceBoxfromArray = function (statsarray, balancewrapper_item_array, style = 'border: solid 3px #000d88;') { return UIcreateBalanceBoxfromArray(statsarray, balancewrapper_item_array, style); };
    $$.UIalt.Services = {};
    $$.UIalt.Services.Button = function (imgiconsrc, title = '', onclick = '', href = '', bgcolor8 = false) { return UIServices_Button(imgiconsrc, title, onclick, href, bgcolor8); };
    $$.UIalt.Services.Button_GOTOPAGE = function (imgiconsrc, title, pagename, pagedatastring = '') { return UIServices_Button_GOTOPAGE(imgiconsrc, title, pagename, pagedatastring); };
    $$.UIalt.Services.FullDIV_GOTOPAGE_Array = function (title, viewallhref = '', viewallonclick = '', viewalltext = '', services_button_array) { return UIServices_FullDIV_GOTOPAGE_Array(title, viewallhref, viewallonclick, viewalltext, services_button_array); };
    $$.UIalt.Services.FullDIV_ONCLICK_Array = function (title, viewallhref = '', viewallonclick = '', viewalltext = '', services_button_array) { return UIServices_FullDIV_ONCLICK_Array(title, viewallhref, viewallonclick, viewalltext, services_button_array); };
    $$.UIalt.Sidetext = {};
    $$.UIalt.Sidetext.UISideText_DualColumnButton = function (text, pagename, pagedatastring = '', imgsrc = '', imgwidth = '', imgheight = '') { return UISideText_DualColumnButton(text, pagename, pagedatastring, imgsrc, imgwidth, imgheight); };
    $$.UIalt.Sidetext.UISideText_DualColumnButton_Array = function (sidetext_button_dualcolumn_array) { return UISideText_DualColumnButton_Array(sidetext_button_dualcolumn_array); };
    $$.UIalt.UICardSimple = function (title, text = '', id = '') { return UICardSimple(title, text, id); };
    $$.UIalt.RecentSearchBar = {};
    $$.UIalt.RecentSearchBar.SearchBar = function (searchplaceholdertext, classtosearch, id, imgsrclefticon = '', imgsrcrighticon = '', imgwidth = '', imgheight = '') { return UIRecentSearchBar(searchplaceholdertext, classtosearch, id, imgsrclefticon, imgsrcrighticon, imgwidth, imgheight); };
    $$.UIalt.RecentSearchBar.Searchable_Button_GO = function (title, subtitle, rightsidetext, classforsearch, pagename, pagedatastring = '', imgsrc, imgwidth = '', imgheight = '') { return UIRecentSearchable_Button_GO(title, subtitle, rightsidetext, classforsearch, pagename, pagedatastring, imgsrc, imgwidth, imgheight); };
    $$.UIalt.RecentSearchBar.Searchable_Button_GO_ARRAY = function (title, recentssearchablebuttonarray, viewallpagetarget, viewallpagedata = '', viewalltext = '') { return UIRecentSearchable_Button_GO_ARRAY(title, recentssearchablebuttonarray, viewallpagetarget, viewallpagedata, viewalltext); };
    $$.UIalt.UIListArrowButton_GO = function (title, subtitle, pagename, pagedatastring = '', imgsrc, imgwidth = '', imgheight = '') { return UIListArrowButton_GO(title, subtitle, pagename, pagedatastring, imgsrc, imgwidth, imgheight); };
    $$.UIalt.RecentSearchBar.SearchBox_with_BUTTONS_FULL = function (title, recentssearchablebuttonarray, UIListArrowButtonGOARRAY = '', viewallpagetarget, viewallpagedata = '', viewalltext = '', classtosearch = '', searchid = '', searchplaceholdertext = '', searchlefticon = '', searchrighticon = '', imgwidth = '', imgheight = '') { return UISearchBox_with_BUTTONS_FULL(title, recentssearchablebuttonarray, UIListArrowButtonGOARRAY, viewallpagetarget, viewallpagedata, viewalltext, classtosearch, searchid, searchplaceholdertext, searchlefticon, searchrighticon, imgwidth, imgheight); };
    $$.UIalt.Input = {};
    $$.UIalt.Input.InputGroupCore = function (innerhtml = '', label = '', inputgroupid = '') { return UIinputgroupcore(innerhtml, label, inputgroupid); };
    $$.UIalt.Input.InputGroup = function (placeholder, type, id, label = '', classinput = '', spanclass = '', imginsteadofspan = '', required = false, textvalue = '') { return UIInputGroup(placeholder, type, id, label, classinput, spanclass, imginsteadofspan, required, textvalue); };
    $$.UIalt.Input.InputGroupSelect = function (id = '', label = '', optionsarray = '', spanclass = '', imginsteadofspan = '', selectedvalue = '') { return UIInputGroupSelect(id, label, optionsarray, spanclass, imginsteadofspan, selectedvalue); };
    $$.UIalt.Input.InputGroupDatePicker = function () { return UIInputGroupDatePicker(); };
    $$.UIalt.Input.ArraytoOptionforSelect = function (array, selectedvalue = '') { return UIArraytoOptionforSelect(array, selectedvalue); };
    $$.UIalt.Input.ReplaceCurrentOptionsSelect = function (selectid, optionsarray, selectedvalue = '') { return UIReplaceCurrentOptionsSelect(selectid, optionsarray, selectedvalue); };
    $$.UIalt.Input.InputGroupButton = function (buttontext, buttonclass = '', buttonid = '', onclick = '', buttonstyle = '') { return UIInputGroupButton(buttontext, buttonclass, buttonid, onclick, buttonstyle); };
    $$.UIalt.UISetDarkMode = function () { return UISetDarkMode(); };
    $$.UIalt.UIUpdateBodyHTML = function (html = '') { return UIUpdateBodyHTML(html); };
    $$.UIalt.changeTopbarTitle = function (title) { return changeTopbarTitle(title); };
    $$.StatusIntToString = function (Status) { return InttoStrDetailsFuncs.Status(Status); };
</script>
<script>
    LoadDataPageFunc = {};
    LoadDataPageFunc.PageTitle = 'Lead Details';

    LoadDataPageFunc.ids = {};
    LoadDataPageFunc.ids.ViewLeadContainer = "viewleadContainer";
    LoadDataPageFunc.ids.ViewDetailsLogsContainer = 'ViewDetailsLogsContainer';
    LoadDataPageFunc.ids.ViewLeadCard = 'ViewLeadCard';
    LoadDataPageFunc.ids.ViewLeadDetailsCardBody = 'ViewLeadDetailsCardBody';
    LoadDataPageFunc.ids.PreviousLogsPage = 'prevBtnLogsLeadDetailsPage';
    LoadDataPageFunc.ids.NextLogsPage = 'nextBtnLogsLeadDetailsPage';
    LoadDataPageFunc.ids.ChangeStatus_Select = 'ViewLeadDetails_ChangeStatus_Select';

    LoadDataPageFunc.onclicks = {};
    LoadDataPageFunc.onclicks.EditDetailsModalOnclick = 'LoadDataPageFunc.EditDetails.EditDetailsModal();';


    LoadDataPageFunc.Logs = {};
    LoadDataPageFunc.Logs.Pagination = {};


    LoadDataPageFunc.Logs.Pagination.cardsPerPage = 5;
    LoadDataPageFunc.Logs.Pagination.currentPage = 1;

    LoadDataPageFunc.Logs.LogRowCard = function (Date = '', content = '') {
        content = replaceLineBreaks(content);
        return (UICardSimple('', formatDateTimetoReadable(Date) + '<br><br><h4>' + content + '</h4>'));
    };

    LoadDataPageFunc.Logs.Pagination.PageArray = function () {
        return divideArrayIntoSets(LoadDataPageFunc.Logs.LogsCardRowHTMLArray, LoadDataPageFunc.Logs.Pagination.cardsPerPage);
    };

    LoadDataPageFunc.Logs.Pagination.Firstpage = 1;
    LoadDataPageFunc.Logs.Pagination.Lastpage = function () {
        return LoadDataPageFunc.Logs.Pagination.PageArray().length;
    };

    LoadDataPageFunc.Logs.LogsCardRowHTMLArray = [];


    LoadDataPageFunc.Logs.Pagination.FirstPageFound = function () {
        $('#' + LoadDataPageFunc.ids.NextLogsPage).prop('disabled', false);
        $('#' + LoadDataPageFunc.ids.PreviousLogsPage).prop('disabled', true);
    };
    LoadDataPageFunc.Logs.Pagination.LastPageFound = function () {
        $('#' + LoadDataPageFunc.ids.NextLogsPage).prop('disabled', true);
        $('#' + LoadDataPageFunc.ids.PreviousLogsPage).prop('disabled', false);
    };

    LoadDataPageFunc.Logs.Pagination.MiddlePageFound = function () {
        $('#' + LoadDataPageFunc.ids.NextLogsPage).prop('disabled', false);
        $('#' + LoadDataPageFunc.ids.PreviousLogsPage).prop('disabled', false);
    };

    LoadDataPageFunc.Logs.Pagination.OnlyOnePageFound = function () {
        $('#' + LoadDataPageFunc.ids.NextLogsPage).prop('disabled', true);
        $('#' + LoadDataPageFunc.ids.PreviousLogsPage).prop('disabled', true);
    };

    LoadDataPageFunc.Logs.LogRowHtmlPage = function (page = 1) {
        if (page) { LoadDataPageFunc.Logs.Pagination.currentPage = page; }

        let arrayset = LoadDataPageFunc.Logs.Pagination.PageArray();
        let newpageindex = LoadDataPageFunc.Logs.Pagination.currentPage - 1;


        if (!isIndexAccessibleArray(arrayset, newpageindex)) {
            return false;
        }
        LoadDataPageFunc.Logs.Pagination.DetectAndTogglePageButton(page);

        let targetarr = arrayset[newpageindex];
        const htmlstr = targetarr.join('<br>');

        $('#' + LoadDataPageFunc.ids.ViewDetailsLogsContainer).html(htmlstr);
    };

    LoadDataPageFunc.Logs.Pagination.DetectAndTogglePageButton = function (newpage) {
        if (newpage <= LoadDataPageFunc.Logs.Pagination.Firstpage) { LoadDataPageFunc.Logs.Pagination.FirstPageFound(); }
        else if (newpage >= LoadDataPageFunc.Logs.Pagination.LastPageFound()) {
            LoadDataPageFunc.Logs.Pagination.FirstPageFound();
        } else if (LoadDataPageFunc.Logs.Pagination.Lastpage() == 1) {
            LoadDataPageFunc.Logs.Pagination.OnlyOnePageFound();
        } else if (newpage > LoadDataPageFunc.Logs.Pagination.Firstpage && newpage < LoadDataPageFunc.Logs.Pagination.Lastpage()) {
            LoadDataPageFunc.Logs.Pagination.MiddlePageFound();
        }

        if (LoadDataPageFunc.Logs.Pagination.Lastpage() === 1) {
            LoadDataPageFunc.Logs.Pagination.OnlyOnePageFound();
        }
    };

    LoadDataPageFunc.Logs.changePage = function (forwardORBackward) {
        if (!forwardORBackward) { return false; }

        let newpage = LoadDataPageFunc.Logs.Pagination.currentPage;
        if (forwardORBackward === -1) { newpage = newpage - 1; }
        else if (forwardORBackward === 1) { newpage = newpage + 1; }
        if (newpage < LoadDataPageFunc.Logs.Pagination.Firstpage || newpage > LoadDataPageFunc.Logs.Pagination.Lastpage()) {
            newpage = LoadDataPageFunc.Logs.Pagination.currentPage;
            return false;
        }

        LoadDataPageFunc.Logs.Pagination.DetectAndTogglePageButton(newpage);
        LoadDataPageFunc.Logs.Pagination.currentPage = newpage;

        // Load the new page
        LoadDataPageFunc.Logs.LogRowHtmlPage(newpage);
    };


    LoadDataPageFunc.Logs.LogFullCard = function (obj) {
        if (!obj.logs) { return ''; }
        LoadDataPageFunc.LogsCardRowHTMLArray = [];
        let newlogfullarr = [];
        if (obj.logs && Array.isArray(obj.logs)) {
            newlogfullarr.push('<br><br><div id="' + LoadDataPageFunc.ids.ViewDetailsLogsContainer + '">');
            let logrow = '';

            const reversedLogs = [...obj.logs].reverse();

            for (let log of reversedLogs) {
                logrow = LoadDataPageFunc.Logs.LogRowCard(log[0], log[1]);
                LoadDataPageFunc.Logs.LogsCardRowHTMLArray.push(logrow);
                //    newlogfullarr.push(logrow);
            }
        }
        newlogfullarr.push('</div>');

        return newlogfullarr.join('');

    };

    LoadDataPageFunc.RefetchDataAndReload = function (istrue = true) {
        if (!istrue) { return false; }
        Preloaders.ViewLeadDetailsData(currenttarget, false,
            function () {
                ReloadPage();
            }
        );
    };

    LoadDataPageFunc.LeadDetailsCardControls = function () {
        let buttonLImaker = function (text, onclick, icon) {
            return `<li><a href="javascript:void(0);" onclick="${onclick}"><div class="icon-box "><img src="/assets/${icon}"></div>${text}</a></li>`;
        };
        let htmlarr = [`<div class="mt-5"><div class="tf-container">`];
        htmlarr.push('<ul class="box-service mt-3">');
        htmlarr.push(buttonLImaker('Change Status', 'LoadDataPageFunc.ChangeStatus.NewStatusModal();', 'changestatus.png'));
        htmlarr.push(buttonLImaker('Add Logs', 'LoadDataPageFunc.Logs.AddLogsModal();', 'logs.png'));
        htmlarr.push(buttonLImaker('Edit Details', LoadDataPageFunc.onclicks.EditDetailsModalOnclick, 'edit.png'));
        htmlarr.push(buttonLImaker('View Property Details', `ButtonGo('ViewPropertyDetails','${LoadDataPageFunc.Details.target_property}')`, 'house.png'));
        htmlarr.push(buttonLImaker('Declare As Sold', `LoadDataPageFunc.SetAsSold.ModalConfirm()`, 'sold.png'));
        htmlarr.push('</ul</div></div>');
        return htmlarr.join('');
    };

    LoadDataPageFunc.Logs.SubmitNewLog = function () {
        let ShowEmptyTextModal = function () { ModalQuickDismiss('No Input', 'Please input text as log.') };
        let ShowUnabletoAddLog = function () { ModalQuickDismiss('Error', 'Unable to Add Log.') };
        let ShowSuccess = function () { ModalQuickDismiss('Success', 'New Log Added.') };
        let ShowError = function (errorstring) { ModalQuickDismiss('Error', 'Error Occured. <br><br>' + errorstring) };
        let newlogtext = $('#newlogtextarea').val();
        if (!newlogtext) {
            ShowEmptyTextModal();
            return false;
        }
        request
            .url('/ViewLeadPage/controls/logs/add')
            .type('POST')
            .fromVarCache(false)
            .data({ target: currenttarget, newlog: newlogtext })
            .success((response) => {
                if (response === true) {
                    LoadDataPageFunc.RefetchDataAndReload(istrue = true);
                    ShowSuccess();


                    modalhide('ViewDetailsNewLogModal');

                    return true;
                } else {
                    ShowUnabletoAddLog();
                    return false;
                }
            })
            .error((err) => {
                ShowError(err);
                return false;
            })
            .caching(false)
            .go();


    };


    LoadDataPageFunc.Logs.AddLogsModal = function () {
        let modalbody = `<label for="newlogtextarea">Log:</label>
                        <textarea id="newlogtextarea" rows="10" cols="50" placeholder="Enter the log here..."></textarea>`;
        CreateAndShowModal('ViewDetailsNewLogModal', 'New Log', modalbody, buttonprimary('Add New Log', value = '', onclick = 'LoadDataPageFunc.Logs.SubmitNewLog();', block = '', idtext = 'ViewLeadDetailsAddLogButton'));
    };

    LoadDataPageFunc.Details = {};
    LoadDataPageFunc.Details.Status = '';

    LoadDataPageFunc.LeadDetailsCard = function (obj) {
        if (!obj) { return false; }

        let rowcoldetail = [];

        const LeadName = obj.fullname || false;
        const DateCreated = formatDateTimetoReadable(obj.created) || false;
        const DateModified = formatDateTimetoReadable(obj.modified) || false;
        let Status = obj.status;
        const Referrer = obj.referral || false;
        const TargetProperty = obj.property_name || false;
        const TargetViewingDate = formatDateTimetoReadable(obj.target_viewing_date) || false;
        const Mobile = obj.mobile || false;
        const Landline = obj.landline || false;
        const Email = obj.email || false;

        LoadDataPageFunc.Details.Status = Status;


        Status = InttoStrDetailsFuncs.Status(Status);

        const AddDualColifValue = function (varstr, label) {
            if (varstr !== false && varstr !== null) {
                rowcoldetail.push(dualcolrow(label, varstr));
            }
        };

        AddDualColifValue(DateModified, 'Last Activity');
        AddDualColifValue(Status, 'Status');
        AddDualColifValue(Referrer, 'Referrer');
        AddDualColifValue(`<a href="javascript:void(0);" onclick="ButtonGo('ViewPropertyDetails','${obj.target_property}')">` + TargetProperty + '</a>', 'Target Property');
        AddDualColifValue(TargetViewingDate, 'Target Viewing Date');
        AddDualColifValue(Mobile, 'Mobile');
        AddDualColifValue(Landline, 'Landline');
        AddDualColifValue(Email, 'Email');
        rowcoldetail.push('<br><br>');

        rowcoldetail.push(LoadDataPageFunc.LeadDetailsCardControls());
        rowcoldetail.push(LoadDataPageFunc.Logs.LogFullCard(obj));

        const finalRowColDetail = rowcoldetail.join('');

        let ViewLeadCardDetails = createCard(LeadName, LoadDataPageFunc.ids.ViewLeadCard, DateCreated, LoadDataPageFunc.ids.ViewLeadDetailsCardBody, cardbody = finalRowColDetail);
        return ViewLeadCardDetails;
    };



    LoadDataPageFunc.ChangeStatus = {};
    LoadDataPageFunc.ids.ChangeStatusModal = 'ViewDetails_ChangeStatusModal';


    LoadDataPageFunc.ChangeStatus.NewStatusModal = function () {
        const StatusSelect = $$.UIalt.Input.InputGroupSelect(LoadDataPageFunc.ids.ChangeStatus_Select, '', [
            [-2, $$.StatusIntToString(-2)],
            [-1, $$.StatusIntToString(-1)],
            [0, $$.StatusIntToString(0)],
            [1, $$.StatusIntToString(1)],
            [2, $$.StatusIntToString(2)],
            [3, $$.StatusIntToString(3)],
            [4, $$.StatusIntToString(4)],
            [5, $$.StatusIntToString(5)]], '', '', LoadDataPageFunc.Details.Status);


        const htmltext = 'Update the Status of the Lead';
        let modalbody = StatusSelect + htmltext;
        CreateAndShowModal(LoadDataPageFunc.ids.ChangeStatusModal, 'Update Status', modalbody, buttonprimary('Update', value = '', onclick = 'LoadDataPageFunc.ChangeStatus.Submit();', block = '', idtext = ''));


    };


    LoadDataPageFunc.ChangeStatus.Submit = function () {
        const sel = $('#' + LoadDataPageFunc.ids.ChangeStatus_Select).val();
        const selectedstatus = (sel !== null) ? sel : null;

        if (selectedstatus === null) { $$.UI.Modal.ModalQuickDismiss('', 'Select a Status'); return false; }
        if (selectedstatus == LoadDataPageFunc.Details.Status) { $$.UI.Modal.ModalQuickDismiss('', 'Nothing to Change!'); return false; }


        let request = new RequestData(false);
        request
            .url('/ViewLead/Details/ChangeStatus')
            .type('POST')
            .fromVarCache(false)
            .data({ target: currenttarget, newstatus: selectedstatus })
            .success((response) => {
                // console.log(response);
                if (response === true) {
                    LoadDataPageFunc.RefetchDataAndReload(true);
                    $$.UI.Modal.ModalQuickDismiss('', 'Success!');
                    hidemodal(LoadDataPageFunc.ids.ChangeStatusModal);
                    return true;
                }

            })
            .error((err) => {
                ModalQuickDismiss('Error', 'Unable To Change Status<br><br>' + err);
            })
            .go();

    };



    LoadDataPageFunc.ids.EditDetailsModal = 'ViewLeads_EditDetailsModal';
    LoadDataPageFunc.EditDetails = {};
    LoadDataPageFunc.ids.EditDetails_Fullname = 'ViewLeads-EditDetailsFullname';
    LoadDataPageFunc.ids.EditDetails_Mobile = 'ViewLeads-EditDetailsmobile';
    LoadDataPageFunc.ids.EditDetails_Landline = 'ViewLeads-EditDetailslandline';
    LoadDataPageFunc.ids.EditDetails_Email = 'ViewLeads-EditDetailsemail';
    LoadDataPageFunc.ids.EditDetails_ViewingDate = 'ViewLeads-EditDetailspreferreddate';
    LoadDataPageFunc.ids.EditDetails_Property = 'ViewLeads-EditDetailsPreferredSite';

    LoadDataPageFunc.EditDetails.EditDetailsModal = function () {

        $('#' + LoadDataPageFunc.ids.EditDetailsModal).remove();

        Preloaders.PreferredSitesOption(fromVarCache = false, successfunc = false);
        const SubmitOnclick = '';
        const targetdiv = 'modal-body-' + LoadDataPageFunc.ids.EditDetailsModal;
        let FormHTML = ReusableUIElements.NewLeadsGenerateUI(targetdiv, idprefix = 'ViewLeads-EditDetails', replace = false, LoadDataPageFunc.Details.fullname, LoadDataPageFunc.Details.mobile, LoadDataPageFunc.Details.landline, LoadDataPageFunc.Details.email, LoadDataPageFunc.Details.target_viewing_date, LoadDataPageFunc.Details.target_property, false, true);
        const footer = buttonprimary('Update', '', onclick = 'LoadDataPageFunc.EditDetails.Submit();');
        const modalhtml = $$.UI.Modal.Create(LoadDataPageFunc.ids.EditDetailsModal, 'Update Details', FormHTML, footer);

        $$.UI.Element.appendtobody(modalhtml);

        Preloaders.PreferredSitesOption(fromVarCache = true, function (response) {
            UIReplaceCurrentOptionsSelect(idprefix + 'PreferredSite', response);
            $(idprefix + 'PreferredSite').val(LoadDataPageFunc.Details.target_property);
            $$.UI.Modal.Show(LoadDataPageFunc.ids.EditDetailsModal);
        });
    };



    LoadDataPageFunc.EditDetails.GetChanges = function () {
        let objectdata = {};
        objectdata.target = currenttarget;
        const new_fullname = $('#' + LoadDataPageFunc.ids.EditDetails_Fullname).val();
        const new_mobile = $('#' + LoadDataPageFunc.ids.EditDetails_Mobile).val();
        const new_landline = $('#' + LoadDataPageFunc.ids.EditDetails_Landline).val();
        const new_email = $('#' + LoadDataPageFunc.ids.EditDetails_Email).val();
        const new_viewingdate = $('#' + LoadDataPageFunc.ids.EditDetails_ViewingDate).val();
        const new_property = $('#' + LoadDataPageFunc.ids.EditDetails_Property).val();
        let changes = 0;

        if (LoadDataPageFunc.Details.fullname !== new_fullname) { objectdata.fullname = new_fullname; changes++; }
        if (LoadDataPageFunc.Details.mobile !== new_mobile) { objectdata.mobile = new_mobile; changes++; }
        if (LoadDataPageFunc.Details.landline !== new_landline) { objectdata.landline = new_landline; changes++; }
        if (LoadDataPageFunc.Details.email !== new_email) { objectdata.email = new_email; changes++; }
        if (LoadDataPageFunc.Details.target_viewing_date !== new_viewingdate) { objectdata.target_viewing_date = new_viewingdate; changes++; }
        if (LoadDataPageFunc.Details.target_property !== new_property) { objectdata.target_property = new_property; changes++; }
        if (!changes) { return false; }

        return objectdata;
    };


    LoadDataPageFunc.EditDetails.Submit = function () {

        let ChangesObject = LoadDataPageFunc.EditDetails.GetChanges();
        if (!ChangesObject) { $$.UI.Modal.ModalQuickDismiss('No Changes', 'No Changes to Update!'); return false; }
        if (ChangesObject.fullname === '' || ChangesObject.fullname === false || ChangesObject.mobile === '' || ChangesObject.mobile === false || ChangesObject.email === false || ChangesObject.email === '') { $$.UI.Modal.ModalQuickDismiss('Incomplete Details', 'The Following Details are REQUIRED!<br><br>Fullname<br>Mobile<br>Email'); return false; }

        if (ChangesObject.mobile && !hasValidMobileFormat(ChangesObject.mobile)) { toastr.error('Incorrect Mobile Format. Must Be 11 Digits!'); }
        if (ChangesObject.email && !isValidEmail(ChangesObject.email)) { toastr.error('Incorrect Email  Format'); }


        let SendUpdatedDetails = new RequestData(false);
        request
            .url('/ViewLead/Details/Edit/Submit')
            .type('POST')
            .fromVarCache(false)
            .data(ChangesObject)
            .success((response) => {
                if (!response) { return false; }
                const error = response.error || false;
                if (response !== true) {
                    if (error) { $$.UI.Modal.ModalQuickDismiss('Error', error); }
                    return false;
                } else if (response === true) {
                    LoadDataPageFunc.RefetchDataAndReload();
                    hidemodal(LoadDataPageFunc.ids.EditDetailsModal);
                    $$.UI.Modal.ModalQuickDismiss('Success', 'Details Updated');
                }
            })
            .error((err) => {
                ModalQuickDismiss('Error', 'Unable to Load<br>' + errordesc);
            })
            .go();


    };

    LoadDataPageFunc.SetAsSold = {};
    LoadDataPageFunc.ids.FinalRemarks = 'FinalRemarksAsSold';
    LoadDataPageFunc.ids.SetAsSoldModal = 'SetAsSoldModal';

    LoadDataPageFunc.SetAsSold.ModalConfirm = function () {
if (LoadDataPageFunc.Details.status===5){ModalQuickDismiss('', 'Already Sold!'); return;}
        let modalbody = 'Remarks<br><br><textarea id="'+LoadDataPageFunc.ids.FinalRemarks+'"></textarea>';
        CreateAndShowModal(LoadDataPageFunc.ids.SetAsSoldModal, 'Set as Sold', modalbody, buttonprimary('Sold', value = '', onclick = ' LoadDataPageFunc.SetAsSold.Submit();', block = '', idtext = ''));
    };

    LoadDataPageFunc.SetAsSold.Submit = function () {

        const FinalRemarks = $('#' + LoadDataPageFunc.ids.FinalRemarks).val();


        const SetAsSoldDetails = {
            'Final_Remarks': FinalRemarks,
            target: currenttarget
        };

        let SendData = new RequestData(false);

        SendData
            .url('/ViewLead/Details/Edit/SetAsSold')
            .type('POST')
            .fromVarCache(false)
            .data(SetAsSoldDetails)
            .success((response) => {
                const error = response.error || false;
                if (response !== true) {
                    if (error) { $$.UI.Modal.ModalQuickDismiss('Error', error); }
                    return false;
                } else if (response === true) {
                    LoadDataPageFunc.RefetchDataAndReload();
                    hidemodal(LoadDataPageFunc.ids.SetAsSoldModal);
                    $$.UI.Modal.ModalQuickDismiss('Success', 'Leads Set as Complete and Sold');
                }
            })
            .error((err) => {
                ModalQuickDismiss('Error', 'Unable to Load<br>' + errordesc);
            })
            .go();


    };





    LoadDataPageFunc.main = function () {
        let request = new RequestData(true);
        request
            .url('/ViewLead/Details/data')
            .type('POST')
            .fromVarCache(true)
            .data({ target: currenttarget })
            .success((response) => {

                if (response.success ===false){
                    ModalQuickDismiss('Error', 'Unable to Load<br>' + response.message);
                    return false;
                }

                LoadDataPageFunc.ViewLeadCurrentDetails = response.Details;
                LoadDataPageFunc.Details = response.Details;
                if (currentPage !== 'ViewLeadDetails') { return false; }
                $('#' + LoadDataPageFunc.ids.ViewLeadContainer).html(LoadDataPageFunc.LeadDetailsCard(response.Details));
                LoadDataPageFunc.Logs.LogRowHtmlPage();
            })
            .error((err) => {
                ModalQuickDismiss('Error', 'Unable to Load<br>' + errordesc);
            })
            .go();






        //  let mainhtmlviewlead = ViewLeadCardDetails;
        //  $('#viewleadContainer').html(mainhtmlviewlead);




        changeTopbarTitle(LoadDataPageFunc.PageTitle);
    };




    $(document).ready(function () {
        LoadDataPageFunc.main();

    });



</script>