﻿/// <reference path="../jquery-1.5-vsdoc.js" />
/// <reference path="../jquery.validate.js" />
/// <reference path="../jquery.validate.unobtrusive.js" />
$(document).ready(function () {

    $(".wizard-step:first").fadeIn(); // show first step
    $(".wizard-step:first").find("input[type='text']:enabled:first").focus();

    // -------------------------------------------------------
    // Start registration process as a new user
    // -------------------------------------------------------
    $("#start-registration").live('click', function () {
        var btnText = $("#start-registration").text();
        $("#start-registration").disableBt();
        $("#start-registration").addClass("long");
        $("#start-registration").text("Please Wait..");
        $.ajax({
            success: function (result) {
                $("#content").html(result);
                $("#start-registration").enableBt();
                $("#start-registration").text(btnText);
                $("#start-registration").removeClass("long");
                $(".wizard-step:first").fadeIn(); // show first step
                $(".wizard-step:first").find("input[type='text']:enabled:first").focus();
            },
            url: '/registration/NewUser',
            type: 'POST'
        });
    });

    // -------------------------------------------------------
    // Start registration process as an existing user
    // -------------------------------------------------------
    $("#login-user").live('click', function () {
        var btnText = $("#login-user").text();
        $("#login-user").disableBt();
        $("#login-user").text("Checking..");
        var formData = $('#login-user-form').serialize();
        $.ajax({
            success: function (result) {
                $("#content").html(result);
                $("#login-user").enableBt();
                $("#login-user").text(btnText);
                $(".wizard-step:first").fadeIn(); // show first step
                $(".wizard-step:first").find("input[type='text']:enabled:first").focus();
            },
            error: function (request, textStatus, errorThrown) {
                //TODO: Need to build proper display here (a la admin site)
                alert("An error occurred");
                $("#login-user").enableBt();
                $("#login-user").text(btnText);
            },
            url: '/registration/LoginUser',
            data: formData,
            type: 'POST'
        });
    });

    // -------------------------------------------------------
    // Forgotten password button pressed
    // -------------------------------------------------------
    $("#forgotten-password").live('click', function () {

        var formData = $('#login-user-form').serialize();
        var btnText = $("#forgotten-password").text();
        $("#forgotten-password").disableBt();
        $("#forgotten-password").text("Sending..");

        $.ajax({
            success: function (result) {
                $("#forgotten-password").enableBt();
                $("#forgotten-password").text(btnText);
                if (result == "OK") {
                    $(".message")
                        .html("Your password has been sent to your address")
                        .addClass("success")
                        .removeClass("errormsg")
                        .show(200);
                    setTimeout(function () {
                        $(".message").hide(200);
                    }, 6000);
                } else {
                    $(".message")
                        .html("An error occurred sending email.. sorry..")
                        .removeClass("success")
                        .addClass("errormsg")
                        .show(200);
                    setTimeout(function () {
                        $(".message").hide(200);
                    }, 6000);
                }
            },
            error: function (request, textStatus, errorThrown) {
                $("#forgotten-password").enableBt();
                $("#forgotten-password").text(btnText);
                $(".message")
                        .html("An error occurred sending email.. sorry..")
                        .removeClass("success")
                        .addClass("errormsg")
                        .show(200);
                setTimeout(function () {
                    $(".message").hide(200);
                }, 6000);
            },
            url: '/registration/LostPassword',
            data: formData,
            type: 'POST'
        });
    });

    // -------------------------------------------------------
    // "BACK" has been pressed? Show previous step
    // -------------------------------------------------------    
    $("#back-step").live('click', function () {

        $("#next-step").text("Next");
        var $step = $(".wizard-step:visible"); // get current step

        // is there any previous step?
        // ----------------------------
        if ($step.prev().hasClass("wizard-step")) {
            $step.hide().prev().fadeIn();  // show it and hide current step
            var $newStep = $(".wizard-step:visible");
            $newStep.find("input[type='text']:enabled:first").focus();

            // disable backstep button?
            //            if (!$step.prev().prev().hasClass("wizard-step")) {
            //                $("#back-step").disableBt();
            //            }
        }

        // else, must be on first page, reload the login page
        else {
            $.ajax({
                success: function (result) {
                    $("#content").html(result);
                    //                    $("#login-user").enableBt();
                    //                    $("#login-user").text(btnText);
                    //                    $(".wizard-step:first").fadeIn(); // show first step
                    //                    $("#back-step").disableBt();
                    //                    $(".wizard-step:first").find("input[type='text']:enabled:first").focus();
                },
                error: function (request, textStatus, errorThrown) {
                    //TODO: Need to build proper display here (a la admin site)
                    alert("An error occurred");
                    //                    $("#login-user").enableBt();
                    //                    $("#login-user").text(btnText);
                },
                url: '/registration/LoginPage',
                type: 'GET'
            });
        }
    });

    // -------------------------------------------------------    
    // "NEXT" has been pressed? Show next step
    // -------------------------------------------------------    
    $("#next-step").live('click', function () {

        var $step = $(".wizard-step:visible"); // get current step
        var action = $(".wizard-step:visible .validationController");

        var formData = $('form').serialize();

        if (!isValid($step)) {
            return;
        }

        // If there's another step - display it
        // ------------------------------------
        if (hasNextStep($step)) {
            showNextStep($step);
        }

        // Last step? Send thru for registration
        // -------------------------------------
        else {
            var btnText = $("#next-step").text();
            $("#next-step").disableBt();
            $("#next-step").addClass("long");
            $("#next-step").text("Registering Team..");
            $.ajax({
                success: function (result) {
                    $("#next-step").enableBt();
                    $("#next-step").removeClass("long");
                    $("#next-step").text(btnText);
                    $('.block').html(result);
                },
                error: function (request, textStatus, errorThrown) {
                    $("#next-step").enableBt();
                    $("#next-step").removeClass("long");
                    $("#next-step").text(btnText);
                    //TODO: Need to indicate an error  
                },
                url: '/registration/registerTeam',
                data: formData,
                type: 'POST'
            });
        }
    });

    // --------------------------------------------------------------------------------------
    // When user leaves txt box, validate against the client if it has remote class attribute
    // --------------------------------------------------------------------------------------
    $(".remote").live('blur', function () {
        var txtBox = this;

        if ($(txtBox).val().length == 0) {
            return;
        }

        var teamOrganiserType = "primary";
        if (txtBox.name.toLowerCase().indexOf("alternate") >= 0) {
            teamOrganiserType = "alternate"
        }

        var formData =
            $('form').serialize() +
            "&field=" + txtBox.name +
            "&teamOrganiserType=" + teamOrganiserType;

        if (!$('form').validate().element(txtBox)) {
            return;
        }

        $("span[data-valmsg-for='" + txtBox.name + "']").removeClass("ok");

        $.ajax({
            beforeSend: function () {
                $("span[data-valmsg-for='" + txtBox.name + "']")
                    .removeClass("ok")
                    .removeClass("field-validation-error")
                    .addClass("field-validation-valid")
                    .addClass("pending")
                    .html('');
            },
            success: function (result) {
                $("span[data-valmsg-for='" + txtBox.name + "']").removeClass("pending");

                if (result == "OK") {
                    $("span[data-valmsg-for='" + txtBox.name + "']").addClass("ok")

                }
                else {
                    $("span[data-valmsg-for='" + txtBox.name + "']")
                        .removeClass("ok")
                        .removeClass("field-validation-valid")
                        .addClass("field-validation-error")
                        .html('<span>' + result + '</span>');
                }
            },
            error: function (request, textStatus, errorThrown) {
                returnValue = false;
            },
            url: '/registration/validateTeamOrganiserField',
            data: formData,
            type: 'POST'
        });
    });

    // -------------------------------------------------------    
    // Tax Invoice Check box checked - so Invoice details
    // -------------------------------------------------------    
    $("#TaxInvoiceRequired").live('click', function () {
        var chk = this;

        if ($(chk).attr('checked')) {
            $('.taxInvoiceProperties').slideDown(500);
            $('.taxInvoiceProperties').find("input[type='text']:enabled:first").focus();
        } else {
            $('.taxInvoiceProperties').slideUp(500);
        }
    });

    // -------------------------------------------------------    
    // User has selected an existing team organiser to use
    // -------------------------------------------------------    
    $(".select-team-organiser").live('click', function (event) {

        // Stop anchor from triggering
        // ---------------------------
        event.preventDefault();

        var formData = $('form').serialize() + "&alternateTeamOrganiserId=" + $(this).getUrlParam('secondaryTeamOrganiserId');

        $.ajax({
            success: function (result) {
                $(".wizard-step:visible").html(result);
                $('body').applyTemplateSetup();
            },
            error: function (request, textStatus, errorThrown) {
                alert("Error occurred");
                $('body').applyTemplateSetup();
                //TODO: Need to indicate an error  
            },
            url: '/registration/selectTeamOrganiser',
            type: 'POST',
            data: formData
        });
    });
});

function isValid($step) {

    // obtain validator
    // ----------------
    var validator = $("form").validate();
    var anyError = false;

    $step.find("input").each(function () {

        // validate every input element inside this step
        // ---------------------------------------------
        if (!validator.element(this)) { 
            anyError = true;
        }
    });

    // Client side error found
    // -----------------------
    if (anyError) {
        return false;
    }

    // Do we need to validate against the server?
    // ------------------------------------------
    if ($step.hasClass("validate")) {

        // Perform server side validation (if required)
        // --------------------------------------------
        return validateAgainstServer($step);
    }

    return true;
}


function showNextStep($step) {

    //if (hasNextStep($step)) { // is there any next step?        

        // Validation is all ok.. show next step
        // -------------------------------------
        $step.hide().next().fadeIn();  // show it and hide current step
        $("#back-step").enableBt();   // recall to show backStep button
        
        var $newStep = $(".wizard-step:visible");
        if (!hasNextStep($newStep)) {
            $("#next-step").text("Register");   // recall to show backStep button
        }
        else {
            $("#next-step").text("Next");   // recall to show backStep button
        }

        $newStep.find("input[type='text']:enabled:first").focus();
        $.uniform.update($('select'));
//    }

//    else { // this is last step, submit form
//        $("form").submit();
//    }
}

function hasNextStep($step) {
    return ($step.next().hasClass("wizard-step"));
}


// Returns true, if valid
// ----------------------
function validateAgainstServer($step) {
    var action = $step.find(".validationController");
    var returnVal = false;

    var formData = $('form').serialize();
    var btnText = $("#next-step").text();
    $("#next-step").disableBt();
    $("#next-step").text("Checking..");

    $.ajax({
        success: function (result) {

            // Validation was successful?
            // ---------------------------
            if (result == "OK") {                
                returnVal = true;
            }

            // Validation failed
            // -----------------
            else {
                $step.html(result);
                $("select, input:checkbox, input:radio, input:file").uniform();
                returnVal = false;
            }

            $("#next-step").enableBt();
            $("#next-step").text(btnText);
        },
        error: function (request, textStatus, errorThrown) {
            $("#next-step").enableBt();
            $("#next-step").text(btnText);
            returnValue = false;
        },
        url: '/registration/' + action.val(),
        data: formData,
        type: 'POST',
        async: false,
        cache: false,
        dataType: 'text'
    });

    return returnVal;
}

























//$(function () {
//   
//    $("#back-step").live('click', function () {
//        $("#next-step").text("Next");
//        var $step = $(".wizard-step:visible"); // get current step
//        if ($step.prev().hasClass("wizard-step")) { // is there any previous step?
//            $step.hide().prev().fadeIn();  // show it and hide current step

//            // disable backstep button?
//            if (!$step.prev().prev().hasClass("wizard-step")) {
//                $("#back-step").disableBt();
//            }
//        }
//    });


//    // attach nextStep button handler       
//    $("#next-step").live('click', function () {

//        var $step = $(".wizard-step:visible"); // get current step
//        var controller = $(".wizard-step:visible .validationController");

//        $('form').validate();
//        if (!$('form').valid()) {
//            return false;
//        }

//        if (!performValidation($step, controller.val())) {
//            return false;
//        }

//        //            var validator = $("form").validate(); // obtain validator
//        //            var anyError = false;
//        //            $step.find("input").each(function () {
//        //                alert(!validator.element(this));
//        //                if (!validator.element(this)) { // validate every input element inside this step
//        //                    anyError = true;
//        //                }
//        //            });

//        //            if (anyError)
//        //                return false; // exit if any error found

//        if ($step.next().hasClass("confirm")) { // is it confirmation?
//            // show confirmation asynchronously
//            $.post("/wizard/confirm", $("form").serialize(), function (r) {
//                // inject response in confirmation step
//                $(".wizard-step.confirm").html(r);
//            });

//        }

//        if ($step.next().hasClass("wizard-step")) { // is there any next step?
//            $step.hide().next().fadeIn();  // show it and hide current step
//            $("#back-step").enableBt();   // recall to show backStep button

//            var $newStep = $(".wizard-step:visible");
//            if (!$newStep.next().hasClass("wizard-step")) {
//                $("#next-step").text("Register");   // recall to show backStep button
//            }
//            else {
//                $("#next-step").text("Next");   // recall to show backStep button
//            }
//        }

//        else { // this is last step, submit form
//            $("form").submit();
//        }


//    });

//});

//function performValidation(wizardDiv, action) {
//            
//    var selectedform =  $('form');
//    var formData = selectedform.serialize();
//    var returnValue = false;

//    $.ajax({
//        success: function (result) {
//            if (result == "OK") {
//                returnValue = true;
//            }
//            wizardDiv.html(result);
//            returnValue = false;
//        },
//        error: function (request, textStatus, errorThrown) { returnValue = false; },
//        url: 'registration/' + action,
//        data: formData,
//        type: 'POST'
//    });

//    return returnValue;
//}
