



(function() {
    var postUrl = 'https://business.burlington-chamber.com/communication',
        ajaxUrl = 'https://business.burlington-chamber.com/communication/WidgetConfirmation',
        widgetId = 'mn-widget-' + (+new Date),
		prefix = 'mn-widget-comm',
        domain = 'business.burlington-chamber.com',
        xhr = createXHR(),
        supportsAjax = !!xhr && window.JSON,
        supportsCrossDomain = false, // supportsAjax && 'withCredentials' in xhr,
        widget,
        form,
        msg,
        html;

    html = '<div id="' + widgetId + '" class="mn-widget ' + prefix + '"><div class="mn-widget-head">Subscriptions/Groups</div><div class="mn-widget-content"><div id="' + widgetId + '-msg" class="mn-widget-msg mn-widget-msgempty"></div><form id="' + widgetId + '-form" action="' + postUrl + '" method="post" class="mn-form">';
    html += '<input name="RequireCompany" type="hidden" value="False" />';

    html += '<div class="mn-form-pretext">Please select the items that interest you. You will receive periodic communications from us regarding your selections.</div>';
    html += '<div class="mn-form-reqnote" title="Asterisk denotes a required field"><span class="mn-form-req">*</span> Required field</div>';

    // Render all form elements.
    html += '<div class="mn-comm-contact mn-comm-section">';
    html += '<div class="mn-form-row mn-comm-name"><label><span class="mn-form-name">Name: <span class="mn-form-req" title="Required field">*</span></span> <span class="mn-form-field"><input id="' + widgetId + '-name" name="Name" type="text" class="mn-form-text" size="50" maxlength="100" value="" /></span></label></div>';
    html += '<div class="mn-form-row mn-comm-company"><label><span class="mn-form-name">Company: </span> <span class="mn-form-field"><input id="' + widgetId + '-company" name="Company" type="text" class="mn-form-text" size="50" maxlength="75" value="" /></span></label></div>';
    html += '<div class="mn-form-row mn-comm-email"><label><span class="mn-form-name">Email: <span class="mn-form-req" title="Required field">*</span></span> <span class="mn-form-field"><input id="' + widgetId + '-email" name="EMail" type="text" class="mn-form-text" size="50" maxlength="80" value="" /></span></label></div>';
    html += '<div class="mn-form-row mn-comm-phone"><label><span class="mn-form-name">Phone: </span> <span class="mn-form-field"><input id="' + widgetId + '-phone" name="Phone" type="text" class="mn-form-text" size="20" maxlength="30" value="" /></span></label></div>';
    html += '</div>';

    // Render group elements.
    var groupTypes = {"Points of Interests":[{"GroupId":65,"Name":"Advocacy \u0026 Local Legislature"},{"GroupId":72,"Name":"Monthly Newsletter"},{"GroupId":64,"Name":"Professional Development \u0026 Business Education"},{"GroupId":63,"Name":"Relationship Building/Networking"},{"GroupId":69,"Name":"Tourism \u0026 Community Events"}]},
        selectedGroups = [];

    function generateGroups(groups) {
        var result = '';
        for(var i = 0; i < groups.length; i++) {
            var group = groups[i];
            result += '<label><span class="mn-form-field"><input type="checkbox" class="mn-form-check" name="selectedGroups" value="' + group.GroupId + '"' + (selectedGroups.indexOf(group.GroupId)>=0 ? ' checked="checked"' : '') + '/></span><span class="mn-form-name">' + group.Name + '</span></label>';
        }
        return result;
    };

    html += '<div class="mn-comm-groups mn-comm-section">'
    for(var name in groupTypes) {
        var groups = groupTypes[name];
        if (groups.length) {
            html += '<div class="mn-form-row">' + (name ? '<div class="mn-form-name">' + name + '</div>' : '') + '<div class="mn-form-combo mn-form-checkcombo">' + generateGroups(groups) + '</div></div>';
        }
    }
    html += '</div>';

    html += '<script src="https://www.google.com/recaptcha/api.js"></script>';
    html += '<div id="mn-com-captcha" class="mn-com-section"><div class="mn-section-content"><div id="mn-postcomment-answer" class="mn-form-row"><div class="g-recaptcha" data-sitekey="6LcpNUMUAAAAAB5iVpO_rzGG2TK_vFp7V6SCw_4s" data-callback="onReCaptchaSuccess"></div></div></div></div>';

    html += '<div class="mn-actions"><ul><li class="mn-action-submit"><input type="submit" class="mn-button" value="Submit" /></li></ul></div></form></div></div>';
    
    // only add the script if it is being loaded at load time
    if (document.readyState == "loading") {        
        document.write(html);

        widget = document.getElementById(widgetId);
        form = document.getElementById(widgetId + '-form');
        msg = document.getElementById(widgetId + '-msg');

        if (form.addEventListener)
            form.addEventListener('submit', onSubmit, false);
        else if (form.attachEvent)
            form.attachEvent('onsubmit', onSubmit);
    }

    function preventDefault(e) {
        if (e = e || window.event)
            e.preventDefault && e.preventDefault() || (e.returnValue = false);
    };

    function stopPropagation(e) {
        if (e = e || window.event)
            e.stopPropagation && e.stopPropagation() || (e.cancelBubble = true);
    };

    function createXHR() {
        if (window.XMLHttpRequest)
            try { return new XMLHttpRequest(); } catch (e) { }

        if (window.ActiveXObject) {
            try { return new ActiveXObject("MSXML2.XMLHTTP"); } catch (e) { }
            try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { }
        }
    };

    function serialize(form) {
        var elements = form.elements,
            rselectTextarea = /^(?:select|textarea)/i,
            rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
            values = [],
            i;

        for(i = 0; i < elements.length; i++)
        {
            var element = elements[i];

            if (element.name && !element.disabled && (element.checked || rselectTextarea.test(element.nodeName) || rinput.test(element.type)))
            {
                if (element.nodeType === 1 && element.multiple) // multiple select
                {
                    for(var j = 0; j < element.options.length; j++)
                    {
                        if (element.options[j].selected)
                            values.push(encodeURIComponent(element.name) + '=' + encodeURIComponent(element.options[j].value));
                    }
                }
                else
                {
                    values.push(encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value));
                }
            }
        }

        return values.join('&');
    };

    function validate()
    {
        var invalid = [],
            element;

        element = document.getElementById(widgetId + '-name');
        if (!element || !element.value)
            invalid.push('Name');


        element = document.getElementById(widgetId + '-email');
        if (!element || !element.value)
            invalid.push('Email');

        if (invalid.length) {
            alert('The following fields are required:\n\n' + invalid.join(', ') + '.\n');
            return false;
        }

        return true;
    };

    function setMessage(type, message)
    {
        resetMessage();
        msg.className = 'mn-widget-msg mn-widget-msg' + type;
        msg.innerHTML = message;
    }

    function success(data)
    {
        if (data.Success)
        {
            setMessage('success', 'Thank you! A confirmation email has been sent. Please check your email and click the link in the email to confirm your subscriptions.');
            form.style.display = 'none';
        }
        else
        {
            error(data.ErrorMsg);
        }
    };

    function error(errorMsg)
    {
        var styledError = '<span style="color:red">' + errorMsg + '</span>'
        setMessage('error', styledError);
    };

    function resetMessage()
    {
        msg.className = 'mn-widget-msg mn-widget-msgempty';
        while (msg.hasChildNodes())
            msg.removeChild(msg.lastChild);
    };

    function parseJSON(data) {
		if (typeof data !== 'string' || !data)
			return null;

		// Attempt to parse using the native JSON parser first
		if (window.JSON && window.JSON.parse)
			return window.JSON.parse(data);

		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if (/^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
			.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
			.replace(/(?:^|:|,)(?:\s*\[)+/g, '')))
        {
			return (new Function('return ' + data))();
		}
		
        throw new Error('Invalid JSON: ' + data);
	};

    function onSubmit(e) {
        resetMessage();
        preventDefault(e);
        stopPropagation(e);

        if (!validate())
            return;

        data = serialize(form);

        setMessage('sending', 'Please wait while we process your request.');

        var url = ajaxUrl + '?' + data,
            isJsonp = !supportsAjax || (domain != window.location.host && !supportsCrossDomain);

        if (isJsonp) {
            var jsonpFuncName = 'MNI_Comm_jpc' + (+new Date);

            url += '&jsonpcallback=' + jsonpFuncName;
            url += '&X-Requested-With=XMLHttpRequest';

            window[jsonpFuncName] = function (data) {
                success(data);
                delete window[jsonpFuncName];
            };

            var firstScript = document.getElementsByTagName('script')[0],
                script = document.createElement('script');
            script.async = true;
            script.onload = script.onreadystatechange = scriptOnLoad;
            script.src = url;
            firstScript.parentNode.insertBefore(script, firstScript);
        }
        else {
            var xhr = createXHR();
            xhr.open('POST', url, true);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*');
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            xhr.onreadystatechange = function () {
                if (this.readyState == 4)
                {
                    if (this.status == 200)
                        success(parseJSON(this.responseText));
                    else
                        error();
                }
            };
            xhr.send(data);
        }
    };

    function scriptOnLoad() {
        if (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') {
            this.onload = this.onreadystatechange = null;
            this.parentNode.removeChild(this);
        }
    };
})();
