jQuery(document).ready(function(){
    getTrackingCodes();
})
function updateChangedStatus(changed) {
    if (changed) {
        jQuery('.wpms-unsaved-changes').show();
    } else {
        jQuery('.wpms-unsaved-changes').hide();
        jQuery('.wpms-saved-changes').show();
        setTimeout(function () {
            jQuery('.wpms-saved-changes').fadeOut(2000);
        }, 2000);
    }
}
function requireTrackingIdTitle(propertyType) {
    if (propertyType !== 'undefined') {
        if (propertyType === 'analytics4') {
            jQuery('.wpms-tracking-id > label').text(wpms_localize.tracking_text.ga4);
            jQuery('.wpms-tracking-id').show();
            jQuery('.wpms-code-placement, .wpms-head-code-input, .wpms-body-code-input').hide();
        } else if(propertyType === 'tagmanager') {
            jQuery('.wpms-tracking-id > label').text(wpms_localize.tracking_text.tagmanager);
            jQuery('.wpms-tracking-id').show();
            jQuery('.wpms-code-placement, .wpms-head-code-input, .wpms-body-code-input').hide();
            // jQuery('.wpms-head-code-input').hide();
        } else if(propertyType === 'analytics4_custom') {
            jQuery('.wpms-tracking-id').hide();
            jQuery('#wpms-body-code').prop('checked', false);
            jQuery('#wpms-body-code, label[for="wpms-body-code"]').hide();
            jQuery('.wpms-code-placement').show();
            showOrHideCustomCodeGoogleAnalytics();
        } else if(propertyType === 'analytics4_custom' || propertyType === 'tagmanager_custom' || propertyType === 'other_custom') {
            jQuery('.wpms-tracking-id').hide();
            jQuery('#wpms-body-code, label[for="wpms-body-code"]').show();
            jQuery('.wpms-code-placement').show();
            showOrHideCustomCodeGoogleAnalytics();
        }
    }
}
function addOrUpdateTracking() {
    const validated = validateWpmsForm();
    if (!validated) {
        return false;
    }
    let trackingRecordId = parseInt(jQuery('.wpms-tracking-form .wpms_tracking_id').val());
    const trackingType = jQuery('.wpms-tracking-form #wpms_gg_service_tracking_type').val();
    const trackingTypeLabel = jQuery('.wpms-tracking-form #wpms_gg_service_tracking_type option[value="'+trackingType+'"]').text();
    let trackingIdentifier = '';
    let headCode = '';
    let bodyCode = '';
    let codeInHead = false;
    let codeInBody = false;
    switch (trackingType) {
        case 'analytics4':
        case 'tagmanager':
            trackingIdentifier = jQuery('.wpms-tracking-form .wpmsga_code_tracking').val();
            break;
        case 'analytics4_custom':
            if (jQuery('.wpms-tracking-form #wpms-head-code').prop('checked')) {
                headCode = jQuery('.wpms-gg-tagmanager-header-code').val();
                codeInHead = true;
            }
            break;
        case 'tagmanager_custom':
        case 'other_custom':
            if (jQuery('.wpms-tracking-form #wpms-head-code').prop('checked')) {
                headCode = jQuery('.wpms-gg-tagmanager-header-code').val();
                codeInHead = true;
            }
            if (jQuery('.wpms-tracking-form #wpms-body-code').prop('checked')) {
                bodyCode = jQuery('.wpms-gg-tagmanager-body-code').val();
                codeInBody = true;
            }
            break;
        default:
            return false;
            break;
    }
    if (trackingRecordId < 0) {
        latestRecordId = 1;
        if (jQuery('.wpms-trackings-list .wpms-tracking-record').length > 0) {
            latestRecordId = parseInt(jQuery('.wpms-trackings-list .wpms-tracking-record:last-child').data('tracking-record-id')) + 1;
        }
        let newTracking = `<div data-tracking-record-id=${latestRecordId} class="wpms-tracking-record wpms-tracking-list-row">
                <span>#${latestRecordId}</span>
                <span class="wpms-tracking-type" data-tracking-type="${trackingType}">${trackingTypeLabel}</span>
                <span class="wpms-tracking-identifier" data-tracking-identifier="${trackingIdentifier ? htmlEscape(trackingIdentifier) : ''}">${trackingIdentifier ? trackingIdentifier : '<span class="material-icons wpms-icons md-24">disabled_by_default</span>'}</span>
                <span class="wpms-insert-head-code" data-is-checked="${codeInHead}" data-insert-head-code="${codeInHead ? htmlEscape(headCode) : ''}">${codeInHead ? '<span class="material-icons wpms-icons md-24">select_check_box</span>' : '<span class="material-icons wpms-icons md-24">disabled_by_default</span>'}</span>
                <span class="wpms-insert-body-code" data-is-checked="${codeInBody}" data-insert-body-code="${codeInBody ? htmlEscape(bodyCode) : ''}">${codeInBody ?  '<span class="material-icons wpms-icons md-24">select_check_box</span>' : '<span class="material-icons wpms-icons md-24">disabled_by_default</span>'}</span>
                <span class="wpms-action">
                    <span onclick="editTrackingRecord(this)" class="material-icons wpms-icons wpms-action-btn wpms-info">edit</span> 
                    <span onclick="removeTrackingRecord(this)" class="material-icons wpms-icons wpms-action-btn wpms-danger">delete</span>
                </span>
            </div>`;
        jQuery('.wpms-trackings-list').append(newTracking);
    } else if (trackingRecordId > 0) {
        const rowElement = jQuery('.wpms-trackings-list .wpms-tracking-record[data-tracking-record-id="'+trackingRecordId+'"]');
        rowElement.find('.wpms-tracking-type').data('tracking-type', trackingType).text(trackingTypeLabel);
        rowElement.find('.wpms-tracking-identifier').data('tracking-identifier', '').html('<span class="material-icons wpms-icons md-24">disabled_by_default</span>');
        if (trackingIdentifier && ['analytics4', 'tagmanager'].includes(trackingType)) {
            rowElement.find('.wpms-tracking-identifier').data('tracking-identifier', htmlEscape(trackingIdentifier));
            rowElement.find('.wpms-tracking-identifier').text(htmlEscape(trackingIdentifier));
        }
        rowElement.find('.wpms-insert-head-code').data('is-checked', codeInHead).data('insert-head-code',false).html('<span class="material-icons wpms-icons md-24">disabled_by_default</span>');
        if (codeInHead && ['analytics4_custom', 'tagmanager_custom', 'other_custom'].includes(trackingType)) {
            rowElement.find('.wpms-insert-head-code').data('is-checked', codeInHead).data('insert-head-code', htmlEscape(headCode)).html('<span class="material-icons wpms-icons md-24">select_check_box</span>');
        }
        rowElement.find('.wpms-insert-body-code').data('is-checked', codeInBody).data('insert-body-code',false).html('<span class="material-icons wpms-icons md-24">disabled_by_default</span>');
        if (codeInBody && ['tagmanager_custom', 'other_custom'].includes(trackingType)) {
            rowElement.find('.wpms-insert-body-code').data('is-checked', codeInBody).data('insert-body-code', htmlEscape(bodyCode)).html('<span class="material-icons wpms-icons md-24">select_check_box</span>');
        }
    }
    clearTrackingForm();
    updateChangedStatus(true);
}
function editTrackingRecord(e) {
    const clickedRow = jQuery(e).closest('.wpms-tracking-record');
    const trackingRecordId = parseInt(clickedRow.data('tracking-record-id'));
    const trackingType = clickedRow.find('.wpms-tracking-type').data('tracking-type');
    const trackingIdentifier = clickedRow.find('.wpms-tracking-identifier').data('tracking-identifier');
    const hasHeadCode = clickedRow.find('.wpms-insert-head-code').data('is-checked');
    const headCode = clickedRow.find('.wpms-insert-head-code').data('insert-head-code');
    const hasBodyCode = clickedRow.find('.wpms-insert-body-code').data('is-checked');
    const bodyCode = clickedRow.find('.wpms-insert-body-code').data('insert-body-code');
    // Update form
    jQuery('.wpms-tracking-form .wpms_tracking_id').val(trackingRecordId);
    jQuery('.wpms-tracking-form #wpms_gg_service_tracking_type').val(trackingType);
    jQuery('.wpms-tracking-form #wpms_gg_service_tracking_type option[value="'+trackingType+'"]').trigger('click');
    jQuery('.wpms-tracking-form .wpmsga_code_tracking').val(htmlUnescape(trackingIdentifier));
    jQuery('.wpms-tracking-form .wpms-gg-tagmanager-header-code').val(htmlUnescape(headCode));
    jQuery('.wpms-tracking-form .wpms-gg-tagmanager-body-code').val(htmlUnescape(bodyCode));
    jQuery('.wpms-tracking-form #wpms-head-code').prop('checked', hasHeadCode);
    jQuery('.wpms-tracking-form #wpms-body-code').prop('checked', hasBodyCode);
    showOrHideCustomCodeGoogleAnalytics();
}
function removeTrackingRecord(e) {
    let clickedRow = jQuery(e).closest('.wpms-tracking-record');
    if (parseInt(jQuery('.wpms-tracking-form .wpms_tracking_id').val()) === parseInt(clickedRow.data('tracking-record-id'))) {
        clearTrackingForm();
    }
    clickedRow.remove();
    updateChangedStatus(true);
}
function saveTrackingCodes() {
    let trackingList = [];
    jQuery('.wpms-trackings-list .wpms-tracking-record').each(function(){
        let rowElement = jQuery(this);
        let trackingRow = {
            'tracking_record_id' : parseInt(rowElement.data('tracking-record-id')),
            'tracking_type' : rowElement.find('.wpms-tracking-type').data('tracking-type'),
            'tracking_identifier' : rowElement.find('.wpms-tracking-identifier').data('tracking-identifier'),
            'tracking_insert_in_head' : rowElement.find('.wpms-insert-head-code').data('is-checked'),
            'tracking_head_code' : htmlEscape(rowElement.find('.wpms-insert-head-code').data('insert-head-code')),
            'tracking_insert_in_body' : rowElement.find('.wpms-insert-body-code').data('is-checked'),
            'tracking_body_code' : htmlEscape(rowElement.find('.wpms-insert-body-code').data('insert-body-code')),
        }
        trackingList.push(trackingRow);
    })
    jQuery.ajax({
        url: wpms_localize.ajax_url,
        type: 'post',
        data: {
            'action': 'wpms',
            'task': 'wpmsSaveTrackings',
            'wpms_nonce': wpms_localize.wpms_nonce,
            'wpms_tracking_list': trackingList
        },
        dataType: 'json',
        beforeSend: function () {
            jQuery('.wpms-tracking-loader').show();
            jQuery('.ju-button.orange-button.wpms_save_tracking_list').prop('disabled', true);
            jQuery('.ju-button.orange-button.wpms_add_trackings').prop('disabled', true);
        },
        success: function (response) {
            reloadTrackingList(response);
            updateChangedStatus(false);
            jQuery('.wpms-tracking-loader').hide();
            jQuery('.ju-button.orange-button.wpms_save_tracking_list').prop('disabled', false);
            jQuery('.ju-button.orange-button.wpms_add_trackings').prop('disabled', false);
        }
    });
}
function getTrackingCodes() {
    jQuery.ajax({
        url: wpms_localize.ajax_url,
        type: 'post',
        data: {
            'action': 'wpms',
            'task': 'wpmsGetTrackings',
            'wpms_nonce': wpms_localize.wpms_nonce,
        },
        dataType: 'json',
        beforeSend: function () {
            jQuery('.wpms-tracking-loader').show();
            jQuery('.ju-button.orange-button.wpms_save_tracking_list').prop('disabled', true);
            jQuery('.ju-button.orange-button.wpms_add_trackings').prop('disabled', true);
        },
        success: function (response) {
            reloadTrackingList(response);
            jQuery('.wpms-tracking-loader').hide();
            jQuery('.ju-button.orange-button.wpms_save_tracking_list').prop('disabled', false);
            jQuery('.ju-button.orange-button.wpms_add_trackings').prop('disabled', false);
        }
    });
}
function showOrHideCustomCodeGoogleAnalytics() {
    if(jQuery('#wpms-head-code').prop('checked')){
        jQuery('.wpms-head-code-input').show();
    } else {
        jQuery('.wpms-head-code-input').hide();
    }
    if(jQuery('#wpms-body-code').prop('checked')){
        jQuery('.wpms-body-code-input').show();
    } else {
        jQuery('.wpms-body-code-input').hide();
    }
}
function clearTrackingForm() {
    jQuery('#wpms-head-code').prop('checked', false);
    jQuery('#wpms-body-code').prop('checked', false);
    jQuery('.wpms-head-code-input').val('').hide();
    jQuery('.wpms-body-code-input').val('').hide();
    jQuery('.wpms-code-placement').hide();
    jQuery('.wpms-tracking-form .wpms_tracking_id').val(-1);
    jQuery('.wpms-tracking-form #wpms_gg_service_tracking_type').val('analytics4');
    jQuery('.wpms-tracking-form #wpms_gg_service_tracking_type option[value="analytics4"]').click();
    jQuery('.wpms-tracking-form .wpmsga_code_tracking').val('');
}
function htmlEscape(str) {
    if (!str) {
        return '';
    }
    return str
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');
}
function htmlUnescape(str){
    if (!str) {
        return '';
    }
    return str
        .replace(/&quot;/g, '"')
        .replace(/&#39;/g, "'")
        .replace(/&lt;/g, '<')
        .replace(/&gt;/g, '>')
        .replace(/&amp;/g, '&');
}
function reloadTrackingList(data) {
    const parentElement = jQuery('.wpms-trackings-list');
    parentElement.empty();
    data.forEach(function(row){
        const trackingTypeLabel = jQuery('.wpms-tracking-form #wpms_gg_service_tracking_type option[value="'+row.tracking_type+'"]').text();
        parentElement.append(`<div data-tracking-record-id=${row.tracking_record_id} class="wpms-tracking-record wpms-tracking-list-row">
                <span>#${row.tracking_record_id}</span>
                <span class="wpms-tracking-type" data-tracking-type="${row.tracking_type}">${trackingTypeLabel}</span>
                <span class="wpms-tracking-identifier" data-tracking-identifier="${row.tracking_identifier ? htmlEscape(row.tracking_identifier) : ''}">${row.tracking_identifier ? row.tracking_identifier : '<span class="material-icons wpms-icons md-24">disabled_by_default</span>'}</span>
                <span class="wpms-insert-head-code" data-is-checked="${row.tracking_insert_in_head}" data-insert-head-code="${row.tracking_insert_in_head ? row.tracking_head_code : ''}">${row.tracking_insert_in_head ? '<span class="material-icons wpms-icons md-24">select_check_box</span>' : '<span class="material-icons wpms-icons md-24">disabled_by_default</span>'}</span>
                <span class="wpms-insert-body-code" data-is-checked="${row.tracking_insert_in_body}" data-insert-body-code="${row.tracking_insert_in_body ? row.tracking_body_code : ''}">${row.tracking_insert_in_body ?  '<span class="material-icons wpms-icons md-24">select_check_box</span>' : '<span class="material-icons wpms-icons md-24">disabled_by_default</span>'}</span>
                <span class="wpms-action">
                    <span onclick="editTrackingRecord(this)" class="material-icons wpms-icons wpms-action-btn wpms-info">edit</span> 
                    <span onclick="removeTrackingRecord(this)" class="material-icons wpms-icons wpms-action-btn wpms-danger">delete</span>
                </span>
            </div>`);
    })
}
function validateWpmsForm() {
    if (jQuery('.wpms-tracking-form #wpms_gg_service_tracking_id').filter(':visible').length && !jQuery('.wpms-tracking-form #wpms_gg_service_tracking_id').val()) {
        alert(wpms_localize.tracking_text.err_no_track_id);
        return false;
    }
    if (jQuery('.wpms-tracking-form #wpms-head-code').filter(':visible').length && jQuery('.wpms-tracking-form #wpms-head-code').is(':checked') && !jQuery('.wpms-tracking-form .wpms-gg-tagmanager-header-code').val()) {
        alert(wpms_localize.tracking_text.err_no_head_code);
        return false;
    }
    if (jQuery('.wpms-tracking-form #wpms-body-code').filter(':visible').length && jQuery('.wpms-tracking-form #wpms-body-code').is(':checked') && !jQuery('.wpms-tracking-form .wpms-gg-tagmanager-body-code').val()) {
        alert(wpms_localize.tracking_text.err_no_body_code);
        return false;
    }
    return true;
}