/**
*   Initialize Page
*/
$(document).ready(function() {
    FormHighlight();
    InitWatermarks();
    LoginEnterKeyHandler();
});

/**
*   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;
}

/**
*   Login
*/
function Login() {

    var username = $('.Username').val();

    var login = {
        'Username': (username == 'Username' ? '' : username),
        'Password': $('.Password').val(),
        'RememberMe': false
    };

    $.ajax({
        url: "/Login",
        data: $.toJSON(login),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {

            ValidateResult(result, function() {
                window.location = result.Result;
            });
        }
    });
}


/**
*   Join
*/
function Join() {

    $.ajax({
        url: "/Join",
        data: { email: $('#email .Email').val(), name: $('#email .Name').val() },
        type: 'POST',
        success: function (result) {
            $('#email .Before').hide();
            $('#email .After').show();
        }
    });
}

/**
*   Login
*/
function Register() {

    var model = {
        'FirstName': $('#Registration_FirstName').val(),
        'LastName': $('#Registration_LastName').val(),
        'UserName': $('#Registration_UserName').val(),
        'Password': $('#Registration_Password').val(),
        'ConfirmPassword': $('#Registration_ConfirmPassword').val(),
        'Email': $('#Registration_Email').val()
    };

    $.ajax({
        url: "/Register",
        data: $.toJSON(model),
        dataType: 'json',
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        success: function(result) {

            ValidateResult(result, function() {
                window.location = result.Result;
            });
        }
    });
}

/**
*   Global Validation Summary Display
*/
function ValidateResult(result, success, fail) {

    // Get Validation Container
    var validationSummary = $('.' + result.ValidationGroup + ':last').hide();

    // Clear Validation Container
    validationSummary.empty();

    var length = result.ModelState.length;

    if (length == 0) {
        if (typeof (success) === 'function') {
            success();
        }
    }
    else {


        for (var i = 0; i < length; i++) {
            validationSummary.append('<li>' + result.ModelState[i].Value.Errors[0].ErrorMessage + '</li>');
        }

        validationSummary.parent().andSelf().filter('*').show();

        if (typeof (fail) === 'function') {
            fail();
        }
    }
}

function LoginEnterKeyHandler() {
    $('.Form').unbind('keyup').bind('keyup', function(e) {
        if (e.keyCode === 13) {
            $(this).find('a').click();
        }
    });
}