﻿function ShowRoster(id) {
    $.ajax({
        type: "POST",
        cache : false,
        url: '/Team/Roster',
        data: { teamId: id },
        success: function (response) {
            $('#roster').html('');
            $('#roster').html(response);
            $('#roster').dialog({ modal: true, width: '860px', resizable: false });
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })
}

function ShowPlayerStats(id, teamId) {
    $.ajax({
        type: "POST",
        cache: false,
        url: '/Player/Stats',
        data: { id: id, teamId: teamId },
        success: function (response) {
            $('#stats').html('');
            $('#stats').html(response);
            $('#stats').dialog({ modal: true, width: '625px', resizable: false });
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })
}

function ShowScores(teamId) {
    $.ajax({
        type: "POST",
        cache: false,
        url: '/Team/Results',
        data: { teamId: teamId },
        success: function (response) {
            $('#scores').html('');
            $('#scores').html(response);
            $('#scores').dialog({ modal: true, width: '650px', resizable: false });
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })
}

function DeletePlayer(index, teamMemberId) {
    searchIndex = index;

    if (!confirm('Delete will take place immediately, continue?'))
        return;

    if (teamMemberId > 0) {
        //perform an ajax delete from this team
        $.ajax({
            type: "POST",
            url: "/Team/DeletePlayer",
            data: { teamMemberId: teamMemberId },
            success: function (response) {
                alert(response);

                //clear the player
                if (response == "Complete")
                    SetPlayer('', '', '', '');
            },
            error: function (request, textStatus, errorThrown) {
                alert(textStatus);
            }
        })
    }
    else {
        SetPlayer('', '', '', '');
    }

}

function DeleteSchedule(scheduleId) {

    $.ajax({
        type: "POST",
        url: "/Schedule/Delete",
        data: { scheduleId: scheduleId },
        success: function (response) {
            if (response == "Success") {
                //reload current page
                //alert('Coming soon. To re-create a schedule click the create button and setup a new schedule over the existing.');
                getSchedules();
            }
            else {
                alert("An error occured.");
            }
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })

}

function PlayerLookup(data) {

    $.ajax({
        type: "POST",
        url: "/Player/SearchResult",
        data: data,
        success: function (response) {
            $('#results').html(response);
            $('#results').show();
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })

}

function NewPlayer(destination) {

    var req = '0';
    if (requestId.length > 0)
        req = requestId;

    $.ajax({
        type: "POST",
        url: "/Player/CreateDialog",
        data: { index: searchIndex, requestId: req },
        success: function (response) {
            $(destination).dialog('option', 'title', 'New Player' );
            $(destination).html(response);
            $(destination).show();
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })

}

function SetAjaxResult(url, data, target, title) {

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        cache: false,
        success: function (response) {
            $('#' + target).html('');
            $('#' + target).html(response);
            $('#' + target).show();
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })

}

function GetAjaxValue(url, data, target, callback) {
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        cache: false,
        success: function (response) {
            if (callback != null)
                callback(target, response);
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })
}

function SelectPlayer(rowId) {
//    if(searchIndex === 0)
//        return;

    //put the player info back into the source fields
    var parentRow = $('#' + rowId);

    SetPlayer(parentRow.children('td[name=playerId]').text(), parentRow.children('td[name=playerName]').text(), parentRow.children('td[name=playerPhone]').text(), parentRow.children('td[name=playerEmail]').text());

    $('#dialog').dialog('close');
}

function getDivisions(locationId) {

    //alert(locationId);
    $.ajax({
        url: "/Division/ByLocation",
        data: { id: locationId },
        success: function (data) {
            //alert('success');
            $("#DivisionId").empty();
            $.each(data, function (index, item) {
                $("#DivisionId").append("<option value='" + item.Value + "'>" + item.Text + "</option>");
            });

            //' $('#DivisionId').html(data);
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

function getDivisionsWithTeamCounts(locationId, onSuccess) {

    //alert(locationId);
    $.ajax({
        url: "/Division/ByLocationWithTeamCounts",
        data: { id: locationId },
        success: function (data) {
            //alert('success');
            $("#DivisionId").empty();
            $("#DivisionId").append("<option></option>");
            $.each(data, function (index, item) {
                $("#DivisionId").append("<option value='" + item.Value + "'>" + item.Text + "</option>");
            });

            //' $('#DivisionId').html(data);
            if (onSuccess) onSuccess();
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

function getDivisionsWithCallback(locationId, onSuccess) {

    //alert(locationId);
    $.ajax({
        url: "/Division/ByLocation",
        data: { id: locationId },
        success: function (data) {
            //alert('success');
            $("#DivisionId").empty();
            $.each(data, function (index, item) {
                $("#DivisionId").append("<option value='" + item.Value + "'>" + item.Text + "</option>");
            });

            if (onSuccess) onSuccess();
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

function SavePlayer() {
    var dataToSend = {
        name: $('#PlayerName').val(),
        address: $('#PlayerAddress').val(),
        city: $('#PlayerCity').val(),
        stateId: $('#StateId').val(),
        city: $('#PlayerCity').val(),
        zip: RemoveMask($('#PlayerZip').val()),
        phone: RemoveMask($('#PlayerPhone').val()), 
        email: $('#PlayerEmail').val() };
    var valid = true;

    if (dataToSend.phone == '__________') dataToSend.phone = '';
    if (dataToSend.zip == '_________') dataToSend.zip = '';

    if (dataToSend.name.length == 0) {
        $('#PlayerName_validationMessage').removeClass('field-validation-valid').addClass('field-validation-error').html('Required');
        valid = false;
    }
    else {
        $('#PlayerName_validationMessage').removeClass('field-validation-error').addClass('field-validation-valid').html('');
    }

    if (dataToSend.email.length == 0 & dataToSend.phone.length == 0) {
        $('#PlayerPhone_validationMessage').removeClass('field-validation-valid').addClass('field-validation-error').html('Phone or');
        $('#PlayerEmail_validationMessage').removeClass('field-validation-valid').addClass('field-validation-error').html('Email required');
        valid = false;
    }
    else {
        $('#PlayerPhone_validationMessage').removeClass('field-validation-error').addClass('field-validation-valid').html('');
        $('#PlayerEmail_validationMessage').removeClass('field-validation-error').addClass('field-validation-valid').html('');
    }

    if (!valid)
        return;

    $.ajax({
        type: "POST",
        url: "/Player/SaveNewPlayer",
        data: dataToSend,
        success: function (response) {
            //set the values back to the team page
            SetPlayer(response, dataToSend.name, dataToSend.phone, dataToSend.email);

            //close dialog
            $('#dialog').dialog('close');
        },
        error: function (request, textStatus, errorThrown) {
            alert(textStatus);
        }
    })
}

function RemoveMask(text) {
    if (text == null)
        return text;
    if (jQuery.trim(text).length == 0)
        return text;

    return jQuery.trim(text.replace("(", "").replace(")", "").replace("_", "").replace("-", "").replace(" ", ""));
}

//select add on events
function addItems (list, data) {
    //this.clearOptions();
//    for(i = 0; i < data.length; i++)
//    {
//        var item = data[i];
//        var option = new Option(item.Text, item.Value);
//            list.add(option);
//        }


        $.each(data, function (index, itemData) {
            var option = new Option(itemData.Text, itemData.Value);
            $(list).append(option);
        });
//    });
};

$.fn.clearOptions = function () {
    this
    .find('option')
    .remove()
    .end();
};

