// This is the generic method to request an AJAX XML document
// The parameters are described as follows:
//
// p_ajaxIdentifier: The name of the AJAX module to call (see AjaxAction class for details)
// p_useNestedLocale: "nested" if we should use the nested locale, "site" otherwise
// p_parameters: A map of parameters to be tacked on to the URL
// p_callbackFunctionName: The name of the callback function (as a string)
function issueAjaxRequest(p_ajaxIdentifier, p_locale, p_parameters, p_callbackFunctionName)
{
    return issueGenericAjaxRequest(p_ajaxIdentifier, p_locale, p_parameters, p_callbackFunctionName, true)
}
// Same as issueAjaxxRequest but added support for synchronous calls
function issueGenericAjaxRequest(p_ajaxIdentifier, p_locale, p_parameters, p_callbackFunctionName, p_asynch)
{
    // Construct the URL
    var url = window.location.href;
    url = url.substring(0, url.lastIndexOf("/"));
    url = url + "/ajax.do";

    // Add the locale
    url += "?locale=" + p_locale;

    // Add the ajax handler name
    url += "&ajaxHandlerName=" + encodeURIComponent(p_ajaxIdentifier);

    // Add the parameters to the url
    for(parameterName in p_parameters)
    {
        url += "&" + encodeURIComponent(parameterName) + "=" + encodeURIComponent(p_parameters[parameterName]);
    }

    var req = false;
    if(window.XMLHttpRequest)
    {
        // Non-IE browsers
        req = new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    {
        // IE
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if(req)
    {
        req.onreadystatechange = function()
        {
            if(req.readyState == 4)
            {
                eval(p_callbackFunctionName + '(req);');
            }
        }

        req.open("GET", url, p_asynch);
        req.setRequestHeader("Keep-Alive", "10");
        req.send(null);
    }
    return req;
}


////////////////////////////////////////////////////////////////////////////////
// AJAX Sublist filtering
////////////////////////////////////////////////////////////////////////////////

// This is the function called onchange() by the parent control in the sublistfilter relationship
function sublistFilterFieldDef(parentFieldFormElement, parentFieldDefName,
                               localeString, repeaterSectionName, repeaterIndex)
{
    // Get the selected value from the field def
    var selectedParentIndex = parentFieldFormElement.selectedIndex;
    var selectedParentValue = parentFieldFormElement.options[selectedParentIndex].value;
    return sublistFilterFieldDefByParentValue(selectedParentValue, parentFieldDefName, localeString, repeaterSectionName, repeaterIndex)
}

function sublistFilterFieldDefByParentValue(selectedParentValue, parentFieldDefName,
    localeString, repeaterSectionName, repeaterIndex)
{
    var params = new Array();
    params["fielddef"] = parentFieldDefName;
    params["value"] = selectedParentValue;
    params["repeaterSectionName"] = repeaterSectionName;
    params["repeaterIndex"] = repeaterIndex;

    issueAjaxRequest("sublistfilter", localeString, params, "sublistFilterCallback");
    return true;
}

// This function is called upon a successful XML response from the server.
// It sets the option values for the child control(s).
function sublistFilterCallback(p_request)
{
    // Complete
    if (p_request.status == 200)
    {
        try
        {
            // OK response
            var response  = p_request.responseXML.documentElement;

            // Check for the repeater information
            var repeaterNameElement = response.getElementsByTagName("repeaterSectionName")[0];
            var repeaterIndexElement = response.getElementsByTagName("repeaterIndex")[0];

            var controlPrefix = "com.peopleclick.cp.formdata.";
            if(undefined != repeaterNameElement)
            {
                controlPrefix = controlPrefix + "repeater." + repeaterNameElement.firstChild.data + "." + repeaterIndexElement.firstChild.data + ".";
            }

            // Need to loop through the child controls and populate their option lists.
            var childElementNodes = response.getElementsByTagName("childcontrol");
            for(var i = 0; i < childElementNodes.length; i++)
            {
                // Get the current element
                var currentChildNode = childElementNodes[i];

                // Get the name of the child element. We use this
                // to find the appropriate control
                var currentChildFieldDefName = currentChildNode.getAttribute("name");
                var childControl = document.getElementById(controlPrefix + currentChildFieldDefName);

                // Clear out the options and put in the new ones
                childControl.options.length = 0;
                var optionList = currentChildNode.getElementsByTagName("option");

                // if there are no options, blank out the child control.

                for(var j = 0; j < optionList.length; j++)
                {
                    // Each option node should have 2 children - one for key, one for value.
                    var key = optionList[j].getElementsByTagName("key")[0].firstChild.data;
                    var value = optionList[j].getElementsByTagName("value")[0].firstChild.data;

                    childControl.options[j] = new Option();
                    childControl.options[j].value = key;
                    childControl.options[j].text = value;
                }
            }
        }
        catch(e)
        {
            ;
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// AJAX FIELD VALIDATION
////////////////////////////////////////////////////////////////////////////////

// This function is called onBlur() from textboxes for real-time validation.
function validateFieldDef(fieldDefName, valueFieldArray, delimiter,
    localeString, repeaterSectionName, repeaterIndex)
{
    // Create the value string
    var valueString = "";
    for(var i = 0; i < valueFieldArray.length; i++)
    {
        var formElement = document.getElementById(valueFieldArray[i]);
        if(!(null == formElement))
        {
            valueString += formElement.value;
        }

        if(i < valueFieldArray.length - 1)
        {
            valueString += delimiter;
        }
    }

    // Check for empty phones.  Strip out the "|" character, and if
    // the resulting string is empty, send that instead.
    var regex = /\|/g;
    if(valueString.replace(regex, "").length == 0)
    {
        valueString = valueString.replace(regex, "")
    }

    var params = new Array();
    params["fielddef"] = fieldDefName;
    params["value"] = valueString;
    params["repeaterSectionName"] = repeaterSectionName;
    params["repeaterIndex"] = repeaterIndex;

    issueAjaxRequest("validation", localeString, params, "clientSideValidationCallback");
    return true;
}

// This function performs much the same as validateFieldDef, except it
// gets the validation information passed in.
function validateQuestionnaire(questionCounter, isRequired, maxLength, maxValue, minValue, guiDataType, proposedValue)
{
    // Create the param array to pass to the server
    var params = new Array();
    params["questionCounter"] = questionCounter;
    params["isRequired"] = isRequired;
    params["maxLength"] = maxLength;
    params["maxValue"] = maxValue;
    params["minValue"] = minValue;
    params["guiDataType"] = guiDataType;
    params["proposedValue"] = proposedValue;

    issueAjaxRequest("questionnaireValidation", "nested", params, "clientSideValidationCallback");
    return true;
}

// Callback function for client side validation
function clientSideValidationCallback(p_request)
{
    // Complete
    if (p_request.status == 200)
    {
        try
        {
            // OK response
            var response  = p_request.responseXML.documentElement;
            var fieldName = response.getElementsByTagName("fielddef")[0].firstChild.data;

            var repeaterNameElement = response.getElementsByTagName("repeaterSectionName")[0];
            var repeaterIndexElement = response.getElementsByTagName("repeaterIndex")[0];

            var repeaterPrefix = "";
            if(undefined != repeaterNameElement)
            {
                repeaterPrefix = "repeater." + repeaterNameElement.firstChild.data + "." + repeaterIndexElement.firstChild.data + ".";
            }

            var messageTextElement = response.getElementsByTagName("message")[0].firstChild;
            var errorSpan = document.getElementById(repeaterPrefix + "dynamicError" + fieldName)

            if(undefined != messageTextElement)
            {
                message = messageTextElement.data;
                errorSpan.innerHTML = message;
            }
            else
            {
                if (undefined != errorSpan)
                {
                    var innerHTML2 = errorSpan.innerHTML;
                    if (undefined != innerHTML2 && innerHTML2 != "")
                    {
                        errorSpan.innerHTML = "";
                    }
                }
            }
        }
        catch(e)
        {
            ;
        }
    }
}
