/*
    Contact form including Captcha, using Ajax for validation.
	Part of the SummerSound integrated visual and audio captcha package.
	File contents copyright 2009 by David Summer.
*/
   
    /* check Captcha answer with the server */
    function checkCaptchaAnswer()
    {  
        url = "dsAudioCaptchaSubmit.php";
        params = "userAnswer=" + captchaInput.value;
        var ret = makeServerCall(url, params);
        return (ret == 1) ? true : false;
    }

   /*
        Send the email message via Ajax.
   */
   function sendEmail(theForm)
   {
        url = "dsmailCaptcha.php";
        params = "";
        // get the form elemnets for the POST
        for(i=0; i<theForm.elements.length; i++)
        {
            if(theForm.elements[i].type == "text" || theForm.elements[i].type == "textarea" || theForm.elements[i].type == "button")
            {
                params += theForm.elements[i].name + "=" + theForm.elements[i].value + "&";
            }
        }
        var ret = makeServerCall(url, params);
        // if successful, show success message
        if(ret == 1)
        {
            var emailSucessColor = '#285a2a';
            var messageElement = document.getElementById('contactMessageToUser');
            messageElement.style.color = emailSucessColor;
            messageElement.style.fontWeight = 'bold';
            messageElement.innerHTML = theForm.elements['yourNameInput'].value + ',<br/>Thank you.<br/>Your email has been sent.<br/>We will contact you soon.';    
            // change the background color so the message is noticed
            // messageElement.style.backgroundColor = '#b3e2f4';
            
            // clear the input fields
            for(i=0; i<theForm.elements.length; i++)
            {
                if(theForm.elements[i].type == "text" || theForm.elements[i].type == "textarea" || theForm.elements[i].type == "button")
                {
                    theForm.elements[i].value = '';
                }
            }
        }
        
        // in any case reset the Captcha and clear the input
        var captchaImage = document.getElementById('captchaImage');
        captchaImage.src = "dsCaptchaImage.php?b=" + Math.random();
        var captchaInput = document.getElementById('captchaInput');
        captchaInput.value = "";    
   }

   /*
        Perform form validation.
   */
   function validateForm()
   { 
        // remove the mp3 player from the page
        dsSoundComplete();
   
        var ret = true;
        var errorColor = '#b74326';
        var correctColor = '#000000';
        
        // Name, email and comments are required fields
        var nameInput = document.getElementById('yourNameInput');
        var emailInput = document.getElementById('emailAddressInput');
        var commentsInput = document.getElementById('commentsInput');
        var inputField = new Array(nameInput, emailInput, commentsInput);
        
        var name = document.getElementById('yourName');
        var email = document.getElementById('emailAddress');
        var comments = document.getElementById('comments');
        var textField = new Array(name, email, comments);
        
        for(var i = 0; i < inputField.length; i++)
        {
            if (inputField[i].value==null||inputField[i].value=="")
            {
                textField[i].style.color = errorColor;
                if(ret == true)
                    inputField[i].focus();
                ret = false;
            }
            else
            {
                 textField[i].style.color = correctColor;
            }
        }
        
        // check for well formed email
        var apos = emailInput.value.indexOf("@");
        var dotpos = emailInput.value.lastIndexOf(".");
        if (apos < 1 || dotpos-apos < 2) 
        {
            email.style.color = errorColor;
            if(ret == true)
                emailInput.focus();
            ret = false;
        }
        
        // check phone
        var phoneInput = document.getElementById('phoneInput');
        var phone = document.getElementById('phone');
        if(phoneInput.value.length > 0 && phoneInput.value.length < 7)
        {
            phone.style.color = errorColor;
            if(ret == true)
                phoneInput.focus();
            ret = false;
        }
        else
        {
             phone.style.color = correctColor;
        }
        
        // check Captcha via Ajax
        captchaInput = document.getElementById('captchaInput');
        var captcha = document.getElementById('captcha');
        var correctCaptcha = checkCaptchaAnswer();
        
        if(!correctCaptcha)
        {        
            captchaImage = document.getElementById('captchaImage');
            captchaImage.src = "dsCaptchaImage.php?b=" + Math.random();
            captcha.style.color = errorColor;
            captchaInput.value = "";
            if(ret == true)
                captchaInput.focus();
            ret = false;
        }
        else
        {
             captcha.style.color = correctColor;
        }
           
        return ret;
   }
   
   /*
        Callback the mp3 player uses when the sound is done playing.
        Remove the mp3 player from the page.
   */
   function dsSoundComplete()
   {
        var playerElement = document.getElementById('flashPlayerWraper');
        playerElement.innerHTML = "<div id='flascontent2' style='display:none;'>test</div>";
   } 
   
   /*
        Dynamically load the mp3 player
   */
   function loadPlayer()
   {         
        var curID = 'flashPlayerWraper';
        var playerElement = document.getElementById(curID);

        playerElement.innerHTML = "<div id='flascontent2' style='display:none;'>test</div>";

        var flashvars =
        {
            file:   "dsPlaySound.php",
            as:     '1'
        };

        var params =
        {
            swliveconnect:      'true',
            allowScriptAccess:  'sameDomain'
        };

        var attributes =
        {
            name:   'captchaPlayer',
            id:     'captchaPlayer'
        };

        var versionStr = "9.0";
        var hasMinPlayerVersion = swfobject.hasFlashPlayerVersion(versionStr);

        if (hasMinPlayerVersion == false) 
        {
            playerElement = document.getElementById(curID);
            playerElement.innerHTML = '<div id="flashcontent2"><a href="http://get.adobe.com/flashplayer/" target="_new">Get Flash player</a> to use the audio Captcha</div>';
        }
        else
        {
            swfobject.embedSWF('captchaplayer.swf', 'flascontent2', '0', '0', '9', false, flashvars, params, attributes);	
        }                      
    }

    /* 
        Helper, make a call to the server 
    */
    function makeServerCall(url, params)
    {
        var xmlhttp;
    
        if (window.XMLHttpRequest)
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        // 3rd param to false makes sync
        xmlhttp.open("POST",url,false);
        //Send the proper header information along with the request
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");
        // send the request to the server 
        xmlhttp.send(params);
        var ret = xmlhttp.responseText;
        return ret;
   }