(function (utmBuilder, $, undefined) {

    document.getElementById("utm-form").addEventListener("change", generateUrl);
    let outObj = {}

    function urlFromObject(baseUrl, obj) {
        let url = baseUrl + "?"
        let first = true;
        for (let key in obj) {
            if (first) {
                url += `${key}=${obj[key]}`
                first = false;
                continue
            }
            url += `&${key}=${obj[key]}`
        }
        return url
    }
    let url = document.getElementById("url");
    let camp_id = document.getElementById("camp-id");
    let source = document.getElementById("camp-source");
    let medium = document.getElementById("camp-medium");
    let name = document.getElementById("camp-name");
    let errorElement = document.getElementById("error-msg")
    function generateUrl(e) {
        function is_url(str) {
            regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
            if (regexp.test(str)) {
                return true;
            }
            else {
                return false;
            }
        }
        if (url.value === "" || url.value === undefined) {
            errorElement.innerText = "Please fill the mendatory fields"
            document.getElementById("g-url-form").style.visibility = "hidden";
        }
        else if (is_url(url.value) == false) {
            errorElement.innerText = "The website URL provided is not a valid URL."
            document.getElementById("g-url-form").style.visibility = "hidden";
        }
        else if (camp_id.value.length != "24" && camp_id.value.length != 0 ) {
            errorElement.innerText = "Campaign ID wrong."
            document.getElementById("g-url-form").style.visibility = "hidden";
        }
        else if (camp_id.value == "") {
            errorElement.innerText = "Please fill the mendatory fields"
            document.getElementById("g-url-form").style.visibility = "hidden";
        }
        else if (source.value === "" || source.value === undefined || source.value.trim().length <= 0) {
            errorElement.innerText = "Please fill the mendatory fields"
            document.getElementById("g-url-form").style.visibility = "hidden";
        }
        else if (medium.value === "" || medium.value === undefined || medium.value.trim().length <= 0) {
            errorElement.innerText = "Please fill the mendatory fields"
            document.getElementById("g-url-form").style.visibility = "hidden";
        }
        else if (name.value === "" || name.value === undefined || name.value.trim().length <= 0) {
            errorElement.innerText = "Please fill the mendatory fields"
            document.getElementById("g-url-form").style.visibility = "hidden";
        }
        else {
            document.getElementById("g-url-form").style.visibility = "visible";
            errorElement.innerText = ""
        }
        let form = document.getElementById("utm-form");
        let formData = new FormData(form);
        const skipKeys = ['utm_url']

        for (let [key, value] of formData) {
            if (skipKeys.includes(key)) {
                continue
            }
            if (value === '') {
                continue
            }
            outObj[key] = value
        }
        let baseUrl = document.getElementById('url').value;
        let generatedUrl = document.getElementById('g-url');
        generatedUrl.value = urlFromObject(baseUrl, outObj)
    }

    // shortened url

    $('#short-url').click(function () {
        let url = document.getElementById("g-url").value;
        let campId = document.getElementById("camp-id").value;
        $.ajax({
            type: "GET",
            url: semusiCommon.API_PARTS.metrices.r + '/postShortUrl',
            data: {
                api_key: semusiCommon.getActiveUser.api_key,
                app_id: semusiCommon.ACTIVE_APP_ID,
                campId: campId,
                args: JSON.stringify({
                    url: url
                }),
                uniqueNumber : semusiCommon.randomNumber()
            },
            headers: {
                'csrf-token': appiceCookies.getCookie('_csrf')
            },
            // dataType: "json",
            success: function (data) {
                if (data[0]) {
                    $('#s-url').val(data[0]);
                } else {
                    errorElement.innerText = "Please check your campaign ID"
                }
            }
        })


    })


}(window.utmBuilder = window.utmBuilder || {}, jQuery));