﻿/*  File attached an anonymous listener to CM forms to add CMAnalytics
    Requires: files be located at lifemath, no subdomain
    Requires: JQuery    
    
    Event button will have div name "submitButtom"                      */
    $(document).ready(CMA_init); // Wait until page complete (JQ change)

    function CMA_init() {
        // Truncate domain if at cancermath redirect
        //if(document.domain == 'cancer.lifemath.net') {document.domain = 'lifemath.net';}
        if($('#submitButton') && (document.domain=='lifemath.net' || document.domain=='cancer.lifemath.net') ) {
            $('#submitButton').click(CMA_log);  // Bind to page submit function (JQ change)
        }
        //        document.domain = 'lifemath.net'; // Reroute SOP
    }

    function CMA_log()
    {
        var form = document.forms[0];   // Get all values in form
        if(!form) { return; }           // Quit on no form presence
        
        // Gather all array elements
        var el = form.elements;
        var eln = ''; // Names
        var elv = ''; // Values   
        // Gather two arrays, one of values, the other of names
        for(var n = 0, len=el.length; n<len; n++)
        {
            eln += el[n].name + ( (n+1==len) ? '' : '\n' ); // Name
            // Special case for boolean types
            if(el[n].type=='checkbox' || el[n].type=='radio') {
                 elv += el[n].checked +( (n+1==len) ? '' : '\n' );
            }
            else {
                // Use a null place holder for empty text entry
                if( (el[n].type=='' || el[n].type=='text') && el[n].value=='' ) {
                    elv += '0' +( (n+1==len) ? '' : '\n' );
                }
                else {
                    elv += el[n].value +( (n+1==len) ? '' : '\n' );
                }
            }
        }
           
        // Prepare XMLHttpRequest object
        var url = (document.domain=='lifemath.net') ? 'http://lifemath.net/cancer/CMA/CMA_log.php?':'http://cancer.lifemath.net/CMA/CMA_log.php';        

        // Send (JQ change)
        $.post(url, { names: eln, values: elv });   
    }

    
