
function manager() {

    this.request = null;
    this.page = 1;

    this.init = function () {

        $(document).ready(function () {
            FormHighlight();
            InitWatermarks();
            LoginEnterKeyHandler();
            manager.facebookLogin();
        });

    };

    this.getPosts = function () {

        manager.page = manager.page + 1;

        var options = {
            type: "GET",
            method: 'GetPosts/' + manager.page,
            callback: function (html) {
                $('.facebook .More').remove();
                $('.facebook .List').append(html);
            }
        };

        manager.makeRequest(options);
    };

    this.facebookLogin = function () {
        if (typeof (FB) !== 'undefined' && typeof (FB.ensureInit) !== 'undefined') {
            FB.ensureInit(function () {

                FB.Connect.ifUserConnected(
                function () {

                    var userId = FB.Connect.get_loggedInUser();

                    if (userId != null) {
                        FB.Facebook.apiClient.users_getInfo(userId, 'uid, first_name, last_name, pic_square', function (result) {
                            $('.facebook .ConnectState').find('.NotConnected').hide().parent().find('.Connected').show().find('.Name').html(result[0].first_name);
                        });
                    }
                }
                ,
                function () {
                    $('.facebook .ConnectState').find('.NotConnected').show().parent().find('.Connected').hide();
                }
            );
            });
        }
    };

    this.post = function (wall) {

        var post =
        {
            WallType: wall,
            Text: $('.facebook .Connected textarea').val()
        };

        var options = {
            type: "POST",
            data: post,
            method: 'Post',
            callback: function (html) {
                $('.Empty').remove();
                $('.List').prepend(html);
            }
        };

        manager.makeRequest(options);

    }

    this.makeRequest = function (options) {

        var url = "/Ajax/" + options.method;

        // Abort Request If Another One Is Made
        if (manager.request != null)
            manager.request.abort();

        manager.request = $.ajax({
            url: url,
            data: $.toJSON(options.data),
            type: options.type == null ? "POST" : options.type,
            processData: true,
            contentType: "application/json",
            timeout: 100000,
            dataType: 'json',
            success: function (data) {
            },
            error: function (data) {
                if (data.status == 200) {
                    options.callback(data.responseText);
                }
                else {
                    alert(data);
                }
            }
        });
    }
}

var manager = new manager();
manager.init();

/**
*   Catch Console Errors
*/
if (typeof (console) === 'undefined') {
    console = new function () { };
    console.log = function () { };
}

/**
*   Initialize Watermarks On Text Input
*/
function InitWatermarks() {
    $('.watermarked')
            .each(function () {
                if ($(this).val() === $(this).attr('title')) $(this).addClass('watermark');
            })
            .focus(function () {
                if ($(this).val() == $(this).attr('title')) {
                    $(this).val('').removeClass('watermark');
                }
            })
            .blur(function () {
                if ($(this).val() == '') {
                    $(this).addClass('watermark').val($(this).attr('title'));
                }
            }).each(function () {
                if ($(this).val() == '') {
                    $(this).addClass('watermark').val($(this).attr('title'));
                }

            });
}

/**
*   Initialize Form Input Highlights
*/
function FormHighlight() {
    $('input[type="text"], input[type="password"], select, textarea, input[type="checkbox"]').focus(function () {
        if ($(this).attr('type') != 'checkbox') {
            $(this).addClass('focus').prevAll('label:first').addClass('focus');
        }
        else {
            $(this).next('label').addClass('focus');
        }
    });

    $('input[type="text"], input[type="password"], select, textarea, input[type="checkbox"]').blur(function () {
        $('input[type="text"], input[type="password"], select, label, textarea, input[type="checkbox"]').removeClass('focus');
    });
}

/**
*   Add Hash To Url
*/
function AddHash(hash) {
    //pageTracker._trackPageview('/market/' + hash);
    if ('#' + hash == window.location.hash) {
        window.location.hash = new String((new Date().getMilliseconds()));
    }
    window.location.hash = hash;
}

/**
*   Global Validation Summary Display
*/
function ValidateResult(result, success, fail) {

    // Test For Authentication
    if (result.Authenticate && !result.IsAuthenticated)
        window.location = '/Logout?ReturnUrl=' + window.location.href;

    // Hide Success Message
    $('.success').hide();

    // Get Validation Container
    $('.validationSummary').hide();
    var validationSummary = $('.' + result.ValidationGroup + ':last').hide();

    // Clear Validation Container
    validationSummary.empty();

    var length = result.Validation != null && result.Validation.Errors != null ? result.Validation.Errors.length : 0;

    if (length == 0) {

        if (result.Success) {
            $('.success').html(result.Result).show();
        }

        if (typeof (success) === 'function') {
            success();
        }
    }
    else {


        for (var i = 0; i < length; i++) {
            validationSummary.append('<li>' + result.Validation.Errors[i].Message + '</li>');
        }

        validationSummary.parent().show().find('*').show();

        if (typeof (fail) === 'function') {
            fail();
        }
    }
}

function LoginEnterKeyHandler() {
    $('.EnterForm').unbind('keyup').bind('keyup', function (e) {
        if (e.keyCode === 13) {
            $(this).find('a').click();
        }
    });
}

function SetDatePicker() {
    // Fixes Date Picker Bug
    $(".datePicker").datepicker({
        onSelect: function (dateText) {
            document.all ?
                      $(this).get(0).fireEvent("onchange")
                : $(this).change();
        }
    });
}

function track(object) {
    if (typeof _gaq != 'undefined') {
        _gaq.push(object);
    }
}

function submission() {

    var model = {

        'Team':
        {
            'Name': $('#Registration_Team_Name').val(),
            'Gender': $('#Registration_Team_Gender').val(),
            'Coordinator':
            {
                'FirstName': $('#Registration_Team_Coordinator_FirstName').val(),
                'LastName': $('#Registration_Team_Coordinator_LastName').val(),
                'Email': $('#Registration_Team_Coordinator_Email').val(),
                'HomePhone': $('#Registration_Team_Coordinator_HomePhone').val(),
                'MobilePhone': $('#Registration_Team_Coordinator_MobilePhone').val(),
                'WorkPhone': $('#Registration_Team_Coordinator_WorkPhone').val(),
                'FaxPhone': $('#Registration_Team_Coordinator_FaxPhone').val(),
                'Address':
                    {
                        'Street': $('#Registration_Team_Coordinator_Address_Street').val(),
                        'StreetCont': $('#Registration_Team_Coordinator_Address_StreetCont').val(),
                        'City': $('#Registration_Team_Coordinator_Address_City').val(),
                        'State': $('#Registration_Team_Coordinator_Address_State').val(),
                        'PostalCode': $('#Registration_Team_Coordinator_Address_PostalCode').val()
                    }
            }
        },
        'TournamentId': parseInt($('#Registration_TournamentId').val())
    };

    $.ajax({
        url: "/Registration",
        data: $.toJSON(model),
        dataType: 'json',
        type: 'POST',
        beforeSend: function (xhr) {
            $("button").button({ label: "Registering...", disabled: true });
        },
        complete: function (xhr, s) {
            $("button").button({ label: "Register", disabled: false }).button("refresh");
        },
        contentType: "application/json; charset=utf-8",
        success: function (result) {

            ValidateResult(result, function () {

                $('div.Form').hide();
                $('.success').show();
                window.location.hash = '#success';

            }, function () {
                window.location.hash = '#validationGroup';
            });
        }
    });
}