/// <reference path="/JS/jquery-1.5.1-vsdoc.js" />

/*  INIT
----------
$(function ()
{

});
*/


/* Log Console
---------------*/
function LogToConsole(msg)
{
    try { console.info(msg); }
    catch (e) { }
}

/*   Register Form
---------------------*/
function RegisterForm(sender)
{
    var count = 0;
    $("#divValidationSummary").hide();
    $("#divNotify").hide();

    // validazioni
    if (FormValidation())
    {
        Register(sender);
    }
}


/*   Register
----------------*/
function Register(sender)
{
    var count = 0;
    $(sender).fadeOut(800);
    showLoading(sender);
    // recupero il metodo del web service da chiamare
    var wsMethod = $("#hfWsMethod").val();
    LogToConsole("WS Method: '" + wsMethod + "'");
    if (wsMethod == null)
        alert("wsMethod non specificato!");
    // recupero i dati inseriti
    var jsonData = GetJsonData();
    for (o in jsonData) { count++; }
    LogToConsole("jsonData Length: " + count);
    // json da passare al webservice
    var mData = { "data": jsonData };

    // POST AJAX
    $.ajax({
        type: "POST",
        url: "/WS/wsForms.asmx/" + wsMethod,
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: JSON2.stringify(mData),
        dataType: "json",
        success: function (data)
        {
            if (data != null)
            {
                try { gaTrackFormResult(data.d.Status); }
                catch (e) { alert(e); }
                LogToConsole("AJAX Result: " + data.d.Status)

                $("#divNotify").html(data.d.HTML);
                $.fancybox({ 'content': "<div id='notificationFancy'>" + data.d.HTML + "</div>", 'onClosed': function () { divFadeIn("#divNotify"); } });
            }
            else
                LogToConsole("AJAX Result: null");

            removeLoading(sender);
        },
        error: function (data)
        {
            alert("Web-Service Error!!");
            removeLoading(sender);
        }
    });
}


function divFadeIn(id)
{
    $(id).fadeIn(800);
}

function gaTrackFormResult(result)
{
    if (result)
    {
        var gaPage = $("#hfTrackPage").val();
        if (gaPage != null && gaPage != "")
        {
            gaTrackPage(gaPage);
        }
    }
}


/*   Get Json Data
----------------------*/
function GetJsonData()
{
    var d = {};
    $(".form_info input[type=text], .form_info input[type=password], .form_info input[type=checkbox], .form_info input[type=radio], .form_info input[type=hidden]").each(function ()
    {
        var type = $(this).attr("type");
        if (type != "submit")
        {
            var id = $(this).attr("id");
            var value = GetValueFromInput(this);
            if (id != "")
                d[id] = value;
        }
    });
    $(".form_info select").each(function ()
    {
        var id = $(this).attr("id");
        var value = $(this).val();
        if (id != "")
            d[id] = value;
    });

    $(".form_info textarea").each(function ()
    {
        var id = $(this).attr("id");
        var value = $(this).val();
        if (id != "")
            d[id] = value;
    });
    return d;
}


/*  Get Value From Input
---------------------------*/
function GetValueFromInput(input)
{

    var value = null;
    var id = $(input).attr("id");
    var type = $(input).attr("type");

    switch (type)
    {

        case "text":
        case "password":
        case "hidden":
            {
                value = $.trim($(input).val());
                break;
            }

        case "checkbox":
        case "radio":
            {
                value = ($("#" + id + ":checked").size() > 0);
                break;
            }
    }
    return value;
}



/* showLoading
----------------*/
function showLoading(sender)
{
    $("#divNotify").html("<div id=\"loadingContainer\"> <img src='/imgs/loading.gif' /> <span> Registrazione in Corso ... </span> </div>");
    $("#divNotify").show();
    $(sender).fadeOut(500);
}

function showLoadingText(sender, txt)
{
    $("#divNotify").html("<div id=\"loadingContainer\"> <img src='/imgs/loading.gif' /> <span> " + txt + " </span> </div>");
    $("#divNotify").show();
    $(sender).fadeOut(500);
}

/* removeLoading
-----------------*/
function removeLoading(sender)
{
    $("#loadingContainer").remove();
    $(sender).fadeIn(500);
}





/*  Form Validation
------------------------*/
function FormValidation()
{
    // nascondo il summary
    $("#divValidationSummary").hide();
    var singleField;
    var validationResult = true;

    // per ogni campo obbligatorio ...
    $(".required").each(function ()
    {

        // valido il singolo campo
        try
        {
            singleField = ValidateSingleField(this);
        }
        catch (e)
        {
            LogToConsole("Validation '" + $(this).attr("id") + "' Exception: " + e);
            singleField = false;
        }
        validationResult = validationResult && singleField;
    });

    // se non ha superato tutte le validazioni, mostro il summary
    if (!validationResult)
    {
        //$("#divValidationSummary").fadeIn(800);

        var c = $("#divValidationSummary").html();
        $.fancybox({ 'content': "<div id='notificationFancy'>" + c + "</div>", 'onClosed': function () { divFadeIn("#divValidationSummary"); } });
    }

    LogToConsole("Validation Result: " + validationResult);
    return validationResult;
}

/*  Validate Single Field
----------------------------------*/
function ValidateSingleField(field)
{
    var isValid = false;

    // prendo l'attributo 'type' del campo
    var id = $(field).attr("id");
    var type = $(field).attr("type");
    if (type != null && type.length > 0)
    {
        // se il 'type' esiste, è un input, valido in base al tipo
        switch (type)
        {
            case "text":
            case "password":
            case "file":
                {
                    // <input type="text" ...
                    var id = $(field).attr("id");
                    if (id == "txtEmail" || id == "Email")
                        isValid = ValidateTextEmail(field);
                    else
                        isValid = ValidateText(field);
                    break;
                }

            case "checkbox":
                {
                    isValid = ValidateCheckbox(field);  // <input type="checkbox" ...
                    break;
                }
            case "select-one":
                {
                    isValid = ValidateSelect(field);  // <select ...
                    break;
                }
        }
    }
    else
    { /* non è un input */ }

    LogToConsole("FIELD: '" + $(field).attr("id") + "' VALID: " + isValid);
    return isValid;
}


/*  Validate Text
-----------------------*/
function ValidateText(o)
{
    var isValid = true;
    var id = $(o).attr("id");
    var v = $.trim($(o).val());

    setValid(o);
    if (v.length <= 0)
    {
        isValid = false;
        setInvalid(o);
    }
    return isValid;
}

/*
---------------------*/
function ValidateTextEmail(o)
{
    $(o).removeAttr("title");
    var isValid = true;
    isValid = ValidateText(o);

    if (isValid)
    {
        setValid(o);
        var id = $(o).attr("id");
        var email = $(o).val();
        isValid = ValidateEmail(email);

        if (!isValid)
        {
            setInvalid(o);
            $(o).attr("title", "Indirizzo non Valido! - Wrong Address Format!");
        }
    }
    return isValid;
}


/*  Validate Checkbox
---------------------------*/
function ValidateCheckbox(o)
{
    var isValid = true;
    var id = $(o).attr("id");
    var v = $("#" + id + ":checked").size();
    setValid(o);

    if (v <= 0)
    {
        isValid = false;
        setInvalid(o);
    }
    return isValid;
}


function ValidateSelect(o)
{
    var isValid = true;
    var id = $(o).attr("id");
    setValid(o);

    var val = $(o).val();
    var intVal = parseInt(val);
    if (!isNaN(intVal))
    {
        if (intVal < 0)
        {
            isValid = false;
            setInvalid(o);
        }
    }
    else
    {
        if (val == null || (val != null && val == ""))
        {
            isValid = false;
            setInvalid(o);
        }
    }
    return isValid;
}

/* Validate Email
---------------------*/
function ValidateEmail(email)
{
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(email);
}


function setValid(field)
{
    $(field).removeClass("red");
}

function setInvalid(field)
{
    $(field).addClass("red");
}
