/* Prevent execution of ajaxForm if included more than once */
if(typeof window.af == "undefined") {

var ajaxForm = {
    STATUS_DONE : "done",
    STATUS_PAGE_ERROR : "pageError",
    STATUS_REDIRECTED : "redirected",
    ERR_PREFIX: "err_",
    FIELD_PREFIX: "field_",
    ERR_ICON: "err_icon_",

    initStatusPlace : function () {
        try{
            $('#pageStatusPlace #fieldList').empty();
            $('#pageStatusPlace').hide();
        } catch (e) {
            // Ignore it if status element not present on the page.
        }
    },

  /**
   * Get parameter value by specified name.
   *
   * @param formName - web form name
   * @param docXML - xml descriptor
   */
    getParameter : function (docXML, name) {
        var res = "";

        try {
            var doc = "";

            doc = docXML.getElementsByTagName("formDescriptor")[0];

            var fieldList = doc.getElementsByTagName("field");

            for (var i = 0; i < fieldList.length; i++) {
                var field = fieldList[i];
                var fieldName = field.getAttribute("name");

                if (fieldName == name) {
                    res = this.getValue(field, "value");

                    break;
                }
            }
        } catch (e) {
           // alert("ajaxForm.getParam() exception  : " + e);
        }

        return res;
   },

    /**
     * Populate form properies from xml descriptor.
     *
     * @param formName - web form name
     * @param docXML - xml descriptor
     */
    updateFormView : function (docXML, formName) {
        var form = (formName == undefined) ? null : formName;

        try {
            var doc = "";

            doc = docXML.getElementsByTagName("formDescriptor")[0];

            // handle redirect.
            var redirectUrl =  this.getValue(doc, "redirectUrl");

            if (redirectUrl != "") {
                window.location.href = redirectUrl;

                return this.STATUS_REDIRECTED;
            }

            this.initStatusPlace();

            var pageStatus = doc.getElementsByTagName("status")[0].firstChild.nodeValue;

            if (pageStatus == 'false') {
                var msg = doc.getElementsByTagName("message")[0];

                if (msg != null) {
                    $('#pageStatusPlace').show();
                    $('#pageStatusMsg').text(doc.getElementsByTagName("message")[0].firstChild.nodeValue);
                }
            }

            var fieldList = doc.getElementsByTagName("field");

            var lastFieldName = "";

            // Scan form fields.
            for (var i = 0; i < fieldList.length; i++) {
                var field = fieldList[i];
                var fieldName = field.getAttribute("name");
                var fieldType = field.getAttribute("type");
                var fieldStatus = field.getElementsByTagName("status")[0].firstChild.nodeValue;

                var errorEl = document.getElementById(this.ERR_PREFIX + fieldName);
                var errorIcon = document.getElementById(this.ERR_ICON + fieldName);
                var fieldNameEl = document.getElementById(this.FIELD_PREFIX + fieldName); 
                // this.getFormElement(form, this.FIELD_PREFIX + fieldName);
                        //

                if (errorEl != null) {
                    $(errorEl).empty();
                }

                if (errorIcon != null) {
                    $(errorIcon).empty();
                    $(errorIcon).removeClass("errorIcon");
                }

                if (fieldNameEl != null) {
                    if (fieldStatus == 'false') {
                        $(fieldNameEl).addClass("asterisk");
                    } else {
                        $(fieldNameEl).removeClass("asterisk");
                    }
                }

                try {
                    if (fieldStatus == 'false') {
                        if (errorEl != null) {
                            $("<span class='errorMsg'>" + this.getValue(field, "message") + "</span>").appendTo(errorEl);
                        // } else if (errorIcon != null) {
                           // $("<span class='errorMsg'>" + "&nbsp;" + "</span>").appendTo(errorIcon);
                        } else {
                            $("#fieldMsgTemplate #fieldMsg").text(this.getValue(field, "message"));
                            $("#fieldMsgTemplate").clone().prependTo("#pageStatusPlace #fieldList").attr("id", fieldName+"tempId").show();

                            if (errorIcon != null) {
                                $(errorIcon).html("&nbsp;");
                                $(errorIcon).addClass("errorIcon");
                                // $("<span class='errorIcon'>&nbsp;</span>").appendTo(errorIcon);
                            }
                        }
                    }
                } catch (e) {
                    // Ignore if pageStatusPlace element is not present on the page.
                }

                if (fieldType == "text") {
                    $('#'+fieldName).val(this.getValue(field, "value"));
                } else if (fieldType == "checkbox") {
                    document.getElementById(fieldName).checked = this.getValue(field, "value");
                } else if (fieldType == "radio") {
                    var rval = this.getValue(field, "value");

                    $(":radio[@name*=" + fieldName + "]").each(function(i) {
                        if (rval == $(this).val()) {
                            $(this).attr("checked", "check");
                        }
                    });
                } else if (fieldType == "select") {
                    // value from XML
                    var value = this.getValue(field, "value");
                    var el = this.getFormElement(form, fieldName);

                    try {
                        // $("#"+fieldName).val(value);
                        // $(el).val(value);
                        //alert(el.nodeName + " .......... " + fieldName);

                        if (el != undefined && el.nodeName.toUpperCase() == 'SELECT') {
                            var ops = el.options;

                            if (ops != undefined) {
                                for(var k=0; k < ops.length; k++) {
                                    var op = ops[k];

                                    if (op.value == value) {
                                        // Error in IE here

                                        //el.selectedIndex = k;
                                        //el.value = value;

                                        // $(el).attr('selectedIndex', k);

                                        /////$(el).val(value);
                                        //////op.selected = true;

                                        // This method position SELCT properly, but IE report error. (TODO: ???)
                                        $(op).attr('selected', 'true');

                                        break;
                                    }
                                }
                            }
                        }
                    }  catch(e) {
                        //  error on IE6 because select inputs not complete visible

                        // This error raise but element SELECT working.
                        // alert( "fieldType SELECT el=["+el+"], name=[" + fieldName + "], value=["+value+"] error:" + e );
                    }
                } else if (fieldType == "option") {
                    // if (fieldName != lastFieldName) {
                    //     $("#"+fieldName).empty();
                    // }

                    // $("<option value='" + this.getValue(field, "value") + "'>" + this.getValue(field, "message") + "</option>").appendTo("#"+fieldName);
                    var el = this.getFormElement(form, fieldName);

                    if (el.nodeName.toUpperCase() == 'SELECT') {
                        if (fieldName != lastFieldName) {
                            $(el).empty();
                        }

                        $("<option value='" + this.getValue(field, "value") + "'>" + this.getValue(field, "message") + "</option>").appendTo($(el));
                    }
                } else if (fieldType == "list") {
                    if (fieldName != lastFieldName) {
                        $("#"+fieldName).empty();
                    }

                    $("<span>" + this.getValue(field, "message") + "</span><br>").appendTo("#"+fieldName);
                } else if (fieldType == "label") {
                    if (fieldName != lastFieldName) {
                        $("#"+fieldName).empty();
                    }

                    // Old version (before 10.02.2009) there can updated single field.
                    // $("<span>" + this.getValue(field, "value") + "</span>").appendTo("#"+fieldName);
                    // Changes 10.02.2009 on inflotnetwork project for update set of field with specified id.
                    $("span[@id*=" + fieldName + "]").html("<span>" + this.getValue(field, "value") + "</span>");

                    // error, see exception msg -
                    // var el = this.getFormElement(form, fieldName);
                    // $("<span>" + this.getValue(field, "value") + "</span>").appendTo(el);
                } else if (fieldType == "checkboxList") {
                    if (fieldName != lastFieldName) {
                        $("#"+fieldName).empty();
                    }

                    // var fieldStatus = field.getElementsByTagName("status")[0].firstChild.nodeValue;

                    $("<input type='checkbox' value='" + this.getValue(field, "value")
                            + "' checked='" + fieldStatus + "'>"
                            + this.getValue(field, "message") + "<br>")
                            .appendTo("#"+fieldName);
                }

                lastFieldName = fieldName;
            }

            return (pageStatus == 'true') ? this.STATUS_DONE : this.STATUS_PAGE_ERROR;
        } catch (e) {
            alert("ajaxForm.updateFormView() exception  : " + e);
        }
    },

    /**
     *  Gets value by specified form name and fieldName.
     *
     *  @param formName the form name
     *  @param fieldName the element name
     */
    getFormElementValue : function(formName, fieldName) {
        return (this.getFormElement(formName, fieldName)).value;
    },

    /**
     *  Gets value by specified form name and fieldName.
     *
     *  @param formName the form name
     *  @param fieldName the element name
     *  @param value the element value
     */
    setFormElementValue : function(formName, fieldName, value) {
        var el = this.getFormElement(formName, fieldName);

        $(el).val(value);
    },

    /**
     *  Gets DOM element by specified form name and fieldName.
     *
     *  @param formName the form name
     *  @param fieldName the element name
     */
    getFormElement : function(formName, fieldName) {
        var element = null;

        if (formName == null) {
            element = document.getElementById(fieldName);
        } else {
            var myForm = document.forms[formName];

            for (var i=0; i<myForm.elements.length; i++) {
                var el = myForm.elements[i];

                if (el.name == fieldName) {
                    element = el;

                    break;
                }
            }
        }

        return element;
    },

    /**
     *  Gets value from Element by tag name.
     *
     *  @param field the element name
     *  @param tagName the tag name
     */
    getValue : function(field, tagName) {
        var value = "";

        try {
            value = (field.getElementsByTagName(tagName)[0].firstChild != null)
                ? field.getElementsByTagName(tagName)[0].firstChild.nodeValue
                : "";
        } catch (e) {
            // Nothing to do. Ignore this exeption because value can be missed.
            // alert(e);
        }

        return value;
    },

    /**
     * Detect FireFox 3.
     *  http://forums.mozillazine.org/viewtopic.php?f=25&t=705865
     */
    isFireFox3 : function() {
        var ff3 = false;
        /*if ( document.getElementsByClassName ) {
            alert("FireFox 3");
        } */

        if(navigator.oscpu && navigator.userAgent.match("rv:1\.9")) {
            // alert("Nav F3 = " + navigator.userAgent);
            ff3 = true;
        }

        return ff3;
    }

};

// Map the ajaxForm utils namespace to the 'af' one.
var af = ajaxForm;
}

