/**
* @fileOverview
* <h2>Automatic Form Validation</h2>
* Automatic Form Validation is a custom-coded JavaScript/AJAX validation form using SOA
* @author <a href="mailto:alberto.picca@areaprofessional.net">Ing. Alberto Picca</a>
* @name Automatic Form Validation
* @version 1.6.3
* @date 01/10/2011
* @update date:14/11/2011
*    @ change:
*           a) allow user to create more forms using the same logic (passing form name)
*/


/**
*@ declare object 
*/
var $j = jQuery; // jQuery.noConflict();


$j.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $j.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


/**
* @description This function is first calling form 
* @
*/
function doSendForm(pFormID) {
    try {
        doCallAjaxContactForm(pFormID);
    } catch (e) {
        alert('Errore durante la chiamata Ajax - Contattare il web manager' + e);
    }
     
}


/**
* @description : 
* @
*/
function doCallAjaxContactForm(pFormID) {
    $j('#' + pFormID + ' #' + divMessageResult).html('');
    
    // 'this' refers to the current submitted form
    //var str = $j('#' + formID + ' input[id!=__VIEWSTATE]').serialize(); //#ajax-contact-form;

    var str = $j('#' + pFormID + ' [id!=__VIEWSTATE]').serializeObject();

    // calling show loader
    doShowLoader(pFormID);

    try {
        $j.ajax({
            type: 'GET',
            dataType: 'jsonp',
            url: cms_handler_form,
            data: str,
            crossDomain: true,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Content-type", "application/jsonp; charset=utf-8");
                xhr.setRequestHeader("GUID", getCurrentGuid(pFormID));
            },
            success: function (response) {
                ContactFormHandler(response, pFormID);
            },
            error: function (xhr, status, error) {
                $j('#' + pFormID + ' #' + divMessageResult).html('Errore ' + xhr.status);
            },
            complete: function (xhr) {
                doHideLoader(pFormID);
            }

        });
    }
    catch (e) {
        alert('Errore durante la chiamata Ajax - Contattare il web manager' + e);
        }


}



/**
* @description : get current guid ID server-side
* @
*/
function getCurrentGuid(pFormID) {
    return $j('#' + pFormID + ' #' + imgCaptchaID).attr('guid');
}




/**
* @description : show dynamic loader
* @
*/
function doShowLoader(pFormID) 
{
    $j('#' + pFormID + ' #' + divLoaderID).css('visibility', 'visible');
    $j('#' + pFormID + ' #' + divMessageResult).html("Invio richiesta in corso");
}


/**
* @description : hide dynamic loader
* @
*/
function doHideLoader(pFormID) {
    $j('#' + pFormID + ' #' + divLoaderID).css('visibility', 'hidden');
}


/**
* @description : handler of response ajax calling
* @
*/
function ContactFormHandler(req, pFormID) {
    try {

        var msg = req.msg;
        var status = req.status;
        var errorField = req.errorField;

        var sErrorField = errorField; 
        var sStatus = status; 
        var sMessage = msg;

        // visualizzazione del messaggio di errore
        $j('#' + pFormID + ' #' + divMessageResult).html("<strong>" + sMessage + "</strong>");

        if (status == "OK") {
            doResetContactForm(pFormID);
        }
        else {

            var oElement = $j('#' + pFormID + ' #' + errorField);
            //alert(oElement);
            if (oElement != null) {
                oElement.css('background-color', color_error);
                oElement.attr('onkeypress', 'onElementClick(this)');
                oElement.focus();
            }
        }

        // caricamento dell'immagine
        doReloadCaptcha(pFormID);

        // hide loader
        doHideLoader(pFormID);
    }
    catch (e) {
        alert('Errore durante la chiamata Ajax' + e);
    }
}



/**
* @description : reload captcha image
* @
*/
function doReloadCaptcha(pFormID) {
    try {
        $j.ajax({
            type: 'GET',
            dataType: 'jsonp',
            url: cms_handler_makeGuid,
            data:null,
            crossDomain: true,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("Content-type", "application/jsonp; charset=utf-8");
            },
            success: function (response) {
                doApplyGuid(response, pFormID);
            },
            error: function (xhr, status, error) {
                $j('#' + pFormID + ' #' + divMessageResult).html('Errore caricamento immagine ' + xhr.status);
            }

        });
    }
    catch (e) {
        alert('Errore durante la chiamata Ajax - Contattare il web manager' + e);
    }
}


/**
* @description : finally load image from server
* @
*/
function doApplyGuid(req, pFormID) {
    var sGuid = req.guid;
    var objImage = $j('#' + pFormID + ' #' + imgCaptchaID);

    objImage.attr('guid', sGuid);
    objImage.attr('src', cms_handler_captcha + "&time=" + new Date().getTime() + "&guid=" + sGuid);

    $j('#' + pFormID + ' #' + idContainerGuid).val(sGuid);
}


// Reset della form
function doResetContactForm(pFormID) {

    doResetContactFormBackgroundColor(pFormID);

    $j('#' + pFormID + ' input[type="radio"]').val('');
    $j('#' + pFormID + ' input[type="text"]').val('');
    $j('#' + pFormID + ' input[type="checkbox"]').checked == false;
    $j('#' + pFormID + ' textarea').val('');

}


/**
* @description : reset all normal style of object
* @
*/
function doResetContactFormBackgroundColor(pFormID) {

    $j('#' + pFormID + ' input[type="radio"]').css('background-color', color_normal);
    $j('#' + pFormID + ' input[type="text"]').css('background-color', color_normal);
    $j('#' + pFormID + ' input[type="checkbox"]').css('background-color', color_normal);
    $j('#' + pFormID + ' textarea').css('background-color', color_normal);

}



function onElementClick(obj) {
    obj.style.backgroundColor = color_normal;
}
