﻿/************

Functions to handle the AJAX calls (and callbacks) for the dynamic forms module

More info here: http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
and here: http://dotnetslackers.com/columns/ajax/ASPNETAjaxWebService.aspx

************/

// this should let us use "$" in the code, but it's not working
//jQuery.noConflict();
// either way, this file HAS to use "jQuery" throughout instead of "$" to work in Chrome, and I don't know why.

// to enable console messages (in Chrome JavaScript console or Firebug)
var DEBUG = false;

if (DEBUG)
{
    // so our JS debugging doesn't break the code in IE/Chrome
    if (!window.console) console = {};
    console.log = console.log || function(){};
    console.warn = console.warn || function(){};
    console.error = console.error || function(){};
    console.info = console.info || function(){};
}

function resetDynamicForm(frmID)
{
    // clear all form fields
    var frmFields = jQuery("[id^=" + frmID + "]");
    jQuery.each(frmFields, function() {
        switch(this.type) {
	            case 'password':
	            case 'text':
	            case 'textarea':
	            case 'select-multiple':
	                jQuery(this).val('');
	                break;                
	            case 'select-one':
	                this.selectedIndex = -1;
                    break;
	            case 'checkbox':
	            case 'radio':
	                this.checked = false;
	                break;
	        }
    });
}

function SubmitCustomForm(frmName, frmID, txtError, practiceEmail,referringUrl, contextID)
{
    //alert(practiceEmail);
    // set up strings    
    //alert(referringUrl);
    
    if (txtError == "")
        txtError = "Sorry, there was an error submitting your form.  Please try again later.";

    
    
    // validate any required fields    
    var isFormValid = true;    
    // get all form field objects whose ID starts with the name of this form    
    var frmFields = jQuery("[id^=" + frmID + "]");
    jQuery.each(frmFields, function() {
        // in some browsers you get back "true" and in others you get bac true (no quotes)
        if (jQuery(this).attr("required") == "true" || jQuery(this).attr("required") == true)
        {
            if ( (this.type == "checkbox" && !(this.checked)) || (jQuery(this).val() == "") || (jQuery(this).val() == null) )
            {
				
                if(jQuery(this).attr('orgMsg')!==""){
					jQuery(this).next('div').text(jQuery(this).attr('orgMsg'));
				}
				jQuery(this).next().show();
                // highlight row
                jQuery(this).parent().addClass('mck_formErrorDetected');
                isFormValid = false;
            }                        
            else
            {
                // hide any validation msgs we previously showed for fields that are no long invalid
                if (jQuery(this).next().is('.sitecore_module_form_error'))
                {
                    jQuery(this).next().hide();
                    // un-highlight row
                    jQuery(this).parent().removeClass('mck_formErrorDetected');
                }
            }           
        }       
       
        //alert(jQuery(this).val());
        if (this.type == "text" && this.id.indexOf("_emailaddress_") >= 0 && jQuery(this).val() == "")
        {
        		
                var originalMsg = jQuery(this).next('div').text();
				jQuery(this).attr('orgMsg',originalMsg);
				jQuery(this).next('div').text("Required");
                // highlight row
                jQuery(this).parent().addClass('mck_formErrorDetected');
                isFormValid = false;
        }       
       
        if (this.type == "text" && this.id.indexOf("_emailaddress_") >= 0 && jQuery(this).val() != "")
        {
			
            // validate email address
            // using RegEx copied from ExtranetEmailRegistration.ascx
            var regex=/^([a-zA-Z0-9_\-\.])+@(([0-2]?[0-5]?[0-5]\.[0-2]?[0-5]?[0-5]\.[0-2]?[0-5]?[0-5]\.[0-2]?[0-5]?[0-5])|((([a-zA-Z0-9\-])+\.)+([a-zA-Z\-])+))$/;
            if (!regex.test(jQuery(this).val()))
            {
				if(jQuery(this).attr('orgMsg')!==''){
					jQuery(this).next('div').text(jQuery(this).attr('orgMsg'));
					jQuery(this).next().show();
                	// highlight row
                	jQuery(this).parent().addClass('mck_formErrorDetected');
                	isFormValid = false;
				}
				else{
					jQuery(this).next().show();
                	// highlight row
                	jQuery(this).parent().addClass('mck_formErrorDetected');
                	isFormValid = false;
				}
                
            }
            else
            {
                // put back anything we previously turned red that is no long invalid
                if (jQuery(this).next().is('.sitecore_module_form_error'))
                {
                    jQuery(this).next().hide();
                    // un-highlight row
                    jQuery(this).parent().removeClass('mck_formErrorDetected');
                }
            }  
        } 
        if (this.type == "text" && this.id.indexOf("_emailaddress_") >= 0 && jQuery(this).val() == "" && (jQuery(this).attr("required") != "true" && jQuery(this).attr("required") != true))
        {
            // hide err msg for non-required blank email address fields
            if (jQuery(this).next().is('.sitecore_module_form_error'))
            {
                jQuery(this).next().hide();
                // un-highlight row
                jQuery(this).parent().removeClass('mck_formErrorDetected');
            }
        }          
    });
    
    if (isFormValid)
    {        
		
        // hide generic err msg box
        var res = document.getElementById(frmID + "_validation_error");
        res.style.display = "none"; 
        
        // build a JSON-formatted string to submit to the web service (couldn't get jQuery's JSON helper to properly format the string)
        var undefinedfieldname = "";
        var strFormData = "{\"formfields\": [";        
        jQuery.each(frmFields, function() { 
            if (this.tagName != "DIV")
            {
                // resolving a bug where after checking, submitting, and then unchecking a checkbox & submitting again, the box value still comes through    
                if (this.type == "checkbox" && this.checked != true)
                {
                }           
                else
                {                                
                    //set name
                    if(this.type == undefined)
                    {                     
                        undefinedfieldname = escape(jQuery(this).attr("customname"));                        
                    }
                    
                    if(this.type == "radio" && this.checked)
                    {                        
                        strFormData += "{";        
                        strFormData += "\"name\": \"" + undefinedfieldname + "\",";                        
                    }
                    else
                    {
                       if(this.type != "radio" && this.type != undefined)                       
                       {                           
                            strFormData += "{";         
                            strFormData += "\"name\": \"" + escape(jQuery(this).attr("customname")) + "\",";
                       }
                    }
                    
                    
                    //set Value                    
                    if (this.type == "textarea" && jQuery(this).val().length > 2000)
                    {
						
                        strFormData += "\"value\": \"" + escape(jQuery(this).val().substring(0,2000)) + "\",";
                    }
                    else if ( (this.type == "radio") || (jQuery(this).val() == "") || (jQuery(this).val() == null) )
                    {                       
                        if(this.checked)
                        {
                         strFormData += "\"value\": \"" + escape(jQuery(this).val()) + "\",";                         
                        }
                    }                    
                    else
                    {                      
						if(this.type=="textarea" || this.type =="text"){
						
							var searchFor = jQuery(this).val();
							var originalErrorMsg = jQuery(this).next('div').text();
							var compareTo= new RegExp;
							compareTo=/['|^|*|<|>|=|#|%|{|}|\[|\]|\:|(|)|$\/]/g; // regex special chars
							
							var findSpec = searchFor.match(compareTo);
							if(findSpec != null ){
								jQuery(this).attr('orgMsg',originalErrorMsg);
								jQuery(this).next('div').text('This field contains disallowed characters');
								jQuery(this).next('div').show();
								jQuery(this).parent().addClass("mck_formErrorDetected");
								
								return false;
							}else{
								
								strFormData += "\"value\": \"" + escape(jQuery(this).val()) + "\",";
							}
						}
						
                        
                    }
                    
                    
                    
                    
                    // set type
                    if(this.type == "radio" && this.checked)
                    {
                        strFormData += "\"type\": \"" + this.type + "\"";
                        strFormData += "},";                                    
                    }
                    else
                    {
                       if(this.type != "radio" && this.type != undefined)  
                       {
                            strFormData += "\"type\": \"" + this.type + "\"";
                            strFormData += "},";                                    
                       }
                    }                  
                    
                }
            }
        }); 
        
        // remove last comma
        strFormData = strFormData.slice(0, -1);
        strFormData += ",{\"name\": \"UrlReferral%3A\",\"value\": \""+ referringUrl +"\",\"type\": \"textarea\"}";
        strFormData += "] }";
        //alert(strFormData);   
        //document.write         (strFormData)        ;
        if (DEBUG)
        {
            console.log("Sending this string to web service: " + strFormData);
        }
              
        var userContext = new Array();
        userContext["frmID"] = frmID;
        userContext["txtError"] = txtError;
                       
        // call the web service via JS
        // params: Web service params, success callback JS function, error callback JS function, custom parameter
        // our custom parameter is an array of the form ID (so the callbacks know which div to manipulate) and
        // and the generic error message (from SC) to display if a server-side exception occurs.
        
        // TESTING - uncomment line below to throw an error in the web service
        //frmID = "badtest"; 
        if(typeof s !=='undefined') 
        {
            if(s.pageName != "")       
            {
                s.pageName = s.pageName + " - thank you";
                s.t();
            }
        }
        
        McKinsey.Web.services.forms.formapi.SubmitForm(strFormData, frmID, practiceEmail, contextID, onSubmitComplete, onError, userContext); 
		//jQuery(".contenttext").hide();   
    }    
    else
    {       
        // form not valid, show generic err msg box
        var res = document.getElementById(frmID + "_validation_error");
        res.style.display = "inline"; 
        // jump to top of page
        window.location.hash="anchor_form_" + frmID;
    }
}

// userContext is an array containing the form ID and the error header text
function onSubmitComplete(result, userContext, methodName)
{
    if (DEBUG)
    {
        console.log("Form submitted, result was: " + result);
    }
    
    // jQuery can't find our div for some reason
    //var res = jQuery("div#" + userContext);
    var res = document.getElementById(userContext["frmID"]);
    res.innerHTML = result;
}

function onError(exception, userContext, methodName)
{
    var text = userContext["txtError"];
    var res = document.getElementById(userContext["frmID"] + "_error");
    res.innerHTML = "<span class='sitecore_module_form_error' style='font-weight:bold;'>" + text + "</span>";
    res.style.display = "inline";
    
    if (DEBUG)
    {
        // we should log this somewhere...but how?
        console.error("Error: " + exception.get_message() + "\n" + exception.get_stackTrace());        
    }
}

