
    // script wide parameters
    var step_1_tab_active = true;
    var step_2_tab_active = false;
    var step_3_tab_active = false;
    var step_4_tab_active = false;
    var step_5_tab_active = false;

    // ajax form submission setup
	var form_options = { beforeSubmit: submit_before, success: submit_after };
    var form_options_check_alias = { beforeSubmit: submit_before_check_alias, success: submit_after };

    // response content/data holder
    var returned_content = "";


    /*
     * Master Controller
     */
    $(document).ready(function() {
        log("master controller");
        registrationSetup();
    });


    /*
     * apply submit actions that will guide the user throught the account signup process
     * - Step #1,
     * - - ensure all of the required are filled in
     * - - email is valid
     *
     * - Step #2
     * - - copy sports login to poker
     * - - password check
     */
    function registrationSetup() {

        // form ajax handlers
        // ------------------
        $('#check_alias_form').ajaxForm(form_options_check_alias);
        $('#create_account_form').ajaxForm(form_options);
        $('#register_card_form').ajaxForm(form_options);
        $('#deposit_funds_form').ajaxForm(form_options);


        // mine for the captcha key
        // ------------------------
        //var arr = $(".captcha img").attr("src").split("/");
        //arr = arr[arr.length-1].split(".");
        //$("#create_account_form .captcha_key").attr("value", arr[0]);


        // configure the date picker
        // -------------------------
        $("#date_of_birth_display").datepicker({
            buttonImage: '/images/jquery.calendar.gif',
            buttonImageOnly: true,
            altField: '#date_of_birth',
            altFormat: 'yy-mm-dd',
            buttonText: 'Cal',
            showOn: 'both',
            dateFormat: 'M d, yy',
            changeYear: true,
            firstDay: 1,
            maxDate: '-18y',
            minDate: '-108y',
            defaultDate: '-18y'
        });


        // perform the accordian effect if the tab is enabled
        // --------------------------------------------------
        $("a.step_1").bind("click", function() {
            if (step_1_tab_active) {
                $(".step fieldset").hide();
                $(".step_1 fieldset").show("slow");
                $("a.step").removeClass('current_step');
                $(this).addClass('current_step');
            }
        });
        $("a.step_2").bind("click", function() {
            if (step_2_tab_active) {
                $(".step fieldset").hide();
                $(".step_2 fieldset").show("slow");
                $("a.step").removeClass('current_step');
                $(this).addClass('current_step');
            }
        });
        $("a.step_3").bind("click", function() {
            if (step_3_tab_active) {
                $(".step fieldset").hide();
                $(".step_3 fieldset").show("slow");
                $("a.step").removeClass('current_step');
                $(this).addClass('current_step');
            }
        });
        $("a.step_4").bind("click", function() {
            if (step_4_tab_active) {
                $(".step fieldset").hide();
                $(".step_4 fieldset").show("slow");
                $("a.step").removeClass('current_step');
                $(this).addClass('current_step');
            }
        });
        $("a.step_5").bind("click", function() {
            if (step_5_tab_active) {
                $(".step fieldset").hide();
                $(".step_5 fieldset").show("slow");
                $("a.step").removeClass('current_step');
                $(this).addClass('current_step');
            }
        });


        // step #1 - form validation
        // ------------------------------------------------------------
        // - get local copies of all of the data that must be validated
        // - wipe all previous errors
        // - test each data item and add item to the errors list
        // - if there are errors display div.errors
        // - if there are no errors hide div.errors
        // ------------------------------------------------------------
        $('#step_1_submit').click(function() {
            var validated = true;
            var first_name = $("#first_name").attr("value");
            var last_name = $("#last_name").attr("value");
            var email = $("#email").attr("value");
            var address_1 = $("#address_1").attr("value");
            var address_2 = $("#address_2").attr("value");
            var town_city = $("#town_city").attr("value");
            var county = $("#county").attr("value");
            var country = $("#country").attr("value");
            var home_phone = $("#home_phone").attr("value");
            var date_of_birth = $("#date_of_birth").attr("value");
            var captcha_value = $("#captcha_value").attr("value");

            $("div.step_1 div.errors ul").html('');
            $("div.step_1 dt").removeClass('error');

            if (first_name=="") { validated = false; validation_error("div.step_1", "first_name", "Please enter your first name"); }
            if (last_name=="") { validated = false; validation_error("div.step_1", "last_name", "Please enter your surname"); }
            if (!validate_email(email)) { validated = false; validation_error("div.step_1", "email", "Please enter a valid email"); }
            if (address_1=="") { validated = false; validation_error("div.step_1", "address_1","Please enter your address line #1"); }
            if (address_2=="") { validated = false; validation_error("div.step_1", "address_2", "Please enter your address line #2"); }
            if (town_city=="") { validated = false; validation_error("div.step_1", "town_city", "Please enter your Town/City"); }
            if (county=="") { validated = false; validation_error("div.step_1", "county", "Please enter your County"); }
            if (country=="") { validated = false; validation_error("div.step_1", "country", "Please select your Country"); }
            if (home_phone=="") { validated = false; validation_error("div.step_1", "home_phone", "Please enter your Home Telephone Number"); }
            if (date_of_birth=="") { validated = false; validation_error("div.step_1", "date_of_birth_display", "Please enter your Date Of Birth"); }
            if (captcha_value=="") { validated = false; validation_error("div.step_1", "captcha", "Please enter the security code"); }

            if (!validated)
                $("div.step_1 div.errors").css('display', 'block');
            else {
                step_2_tab_active = true;
                $('#step_1 fieldset').hide("fast");
                $('#step_2 fieldset').show("slow");
                $("div.step_1 div.errors").css('display', 'none');
                $("a.step_1").removeClass('current_step');
                $("a.step_2").addClass('current_step');
            }
        });


        // step #2
        // - form validation
        // - disable inputs
        // - copy data over to create account form
        // - submit form
        // -------------------------
        $('#step_2_submit').click(function() {

            validation_error("div.step_2", "x", "checking the tablename");

            var validated = true;
            var sports_username = $("#sports_username").attr("value");
            var sports_password = $("#sports_password").attr("value");
            var poker_username = $("#poker_username").attr("value");
            var poker_password = $("#poker_password").attr("value");
            var poker_tablename = $("#poker_tablename").attr("value");
            var poker_tablename_availability = $("#poker_tablename_availability").attr("value");
            var security_question = $("#security_question").attr("value");
            var security_answer = $("#security_answer").attr("value");

            $("div.step_2 div.errors ul").html('');
            $("div.step_2 dt").removeClass('error');

            if (sports_username=="") { validated = false; validation_error("div.step_2", "sports_username", "Please enter your Sportsbook ID"); }
            if (sports_password=="") { validated = false; validation_error("div.step_2", "sports_password", "Please enter your Sportsbook Password"); }
            if (poker_username=="") { validated = false; validation_error("div.step_2", "poker_username", "Please enter your Poker ID"); }
            if (poker_password=="") { validated = false; validation_error("div.step_2", "poker_password", "Please enter your Poker Password"); }
            if (poker_tablename=="") { validated = false; validation_error("div.step_2", "poker_tablename", "Please enter your Poker Tablename"); }
            if (poker_tablename_availability!="available") { validated = false; validation_error("div.step_2", "poker_tablename_availability", "Please make sure your Poker Tablename is available"); }
            if (security_question=="") { validated = false; validation_error("div.step_2", "security_question", "Please choose a security question"); }
            if (security_answer=="") { validated = false; validation_error("div.step_2", "security_answer", "Please enter a security answer"); }


            if (!validated)
                $("div.step_2 div.errors").css('display', 'block');
            else {
                $("div.step_1 div.errors").css('display', 'none');
                $("div.step_1 input,.step_1 select,.step_2 input,.step_2 select").attr("disabled", "disabled");
                copy_value("user_currency");
                copy_value("session_spend_max");
                copy_value("session_time_max");
                copy_value("terms_and_conditions");
                copy_value("first_name");
                copy_value("last_name");
                copy_value("email");
                copy_value("address_1");
                copy_value("address_2");
                copy_value("town_city");
                copy_value("county");
                copy_value("postcode");
                copy_value("country");
                copy_value("home_phone");
                copy_value("work_phone");
                copy_value("mobile_phone");
                copy_value("date_of_birth");
                copy_value("captcha_value");
                copy_value("sports_username");
                copy_value("sports_password");
                copy_value("sports_password_retype");
                copy_value("poker_username");
                copy_value("poker_password");
                copy_value("poker_tablename");
                copy_value("poker_tablename_availability");
                copy_value("security_question");
                copy_value("security_answer");
                copy_value("statement_frequency");
                copy_value("first_heard");
                $("#create_account_form").submit();
            }
            return false;
        });

        $("#sports_username").bind("change", function() {
            $("#poker_username").attr("value", $(this).attr("value"));
        });

        $("#sports_password_retype").bind("change", function() {
            if ($(this).attr("value")!=$("#sports_password").attr("value"))
                alert("The passwords entered don't match");
            else
                $("#poker_password").attr("value", $(this).attr("value"));
        });


        // step #3: card details
        // ---------------------------------------------------------------------------------
        $("#skip_card").bind("click", function() {
            $('#step_3 fieldset').hide("fast");
            $('#step_5 fieldset').show("slow");
        });

        $('#step_3_submit').click(function() {
            var validated = true;
            var card_name = $("#card_name").attr("value");
            var card_number = $("#card_number").attr("value");
            var card_type = $("#card_type").attr("value");
            var card_start_month = $("#card_start_month").attr("value");
            var card_start_year = $("#card_start_year").attr("value");
            var card_end_month = $("#card_end_month").attr("value");
            var card_end_year = $("#card_end_year").attr("value");
            var card_cvv = $("#card_cvv").attr("value");

            $("div.step_3 div.errors ul").html('');
            $("div.step_3 dt").removeClass('error');

            if (card_name=="") { validated = false; validation_error("div.step_3", "card_name", "Please enter the name on the Card"); }
            if (card_number=="") { validated = false; validation_error("div.step_3", "card_number", "Please enter the Number on the Card"); }
            if (card_type=="") { validated = false; validation_error("div.step_3", "card_type", "Please select the Card Type"); }
            if (card_start_month=="") { validated = false; validation_error("div.step_3", "card_start_month", "Please enter the Card Start Month"); }
            if (card_start_year=="") { validated = false; validation_error("div.step_3", "card_start_year", "Please enter the Card Start Year"); }
            if (card_end_month=="") { validated = false; validation_error("div.step_3", "card_end_month", "Please enter the Card End Month"); }
            if (card_end_year=="") { validated = false; validation_error("div.step_3", "card_end_year", "Please enter the Card End Year"); }
            if (card_cvv=="") { validated = false; validation_error("div.step_3", "card_cvv", "Please enter the Card CVV"); }

            if (!validated)
                $("div.step_3 div.errors").css('display', 'block');
            else {
                $("div.step_3 div.errors").css('display', 'none');
                $("#register_card_form").submit();
            }
        });


        // step #4: deposit
        // ----------------
        $("#skip_deposit").bind("click", function() {
            $('#step_4 fieldset').hide("fast");
            $('#step_5 fieldset').show("slow");
        });

        $('#step_4_submit').click(function() {
            var validated = true;
            var customer_password = $("#deposit_funds_form .customer_password").attr("value");
            var card_cvv = $("#deposit_funds_form .card_cvv").attr("value");
            var amount = $("#deposit_funds_form .amount").attr("value");

            $("div.step_4 div.errors ul").html('');
            $("div.step_4 dt").removeClass('error');

            if (customer_password=="") { validated = false; validation_error("div.step_4", "customer_password", "Please enter your password"); }
            if (card_cvv=="") { validated = false; validation_error("div.step_4", "card_cvv", "Please the Card CVV number"); }
            if (amount=="") { validated = false; validation_error("div.step_4", "amount", "Please enter the amount"); }

            if (!validated)
                $("div.step_4 div.errors").css('display', 'block');
            else {
                $("div.step_4 div.errors").css('display', 'none');
                $("#deposit_funds_form").submit();
            }
        });
    }


    function submit_before(formData, jqForm, form_options) {
        $("*").css("cursor", "wait");
        log("submit_before, formData = "+formData);
		log("submit_before, jqForm = "+jqForm);
		log("submit_before, form_options = "+form_options);        
    }


    function submit_before_check_alias(formData, jqForm, form_options) {
        $("*").css("cursor", "wait");
        log("submit_before_check_alias, formData = "+formData);
		log("submit_before_check_alias, jqForm = "+jqForm);
		log("submit_before_check_alias, form_options = "+form_options);

        $("#poker_tablename_check").attr("value", "Checking Your Table Name");
        $("#poker_tablename_check").after('<img id="poker_loader" src="/graphics/ajax-loader.gif"/>');        
    }


    function submit_after(responseText, statusText) {
        $("*").css("cursor", "auto");
        log("submit_after, responseText = "+responseText);
        log("submit_after, statusText = "+statusText);
        
        $("#returned_data").html(responseText);
        $("#returned_data div.response > *").each(function(i) {
            try {
                if ($(this).attr("class")=="function") 
                    eval($(this).attr("name")+"("+$(this).text()+")");

                else if ($(this).attr("class")=="content") {                    
                    var selector = $(this).attr("selector");
                    var road = $(this).attr("road");
                    var content = $(this).html();

                    if (road=="replace") $(selector).html(content);
                    else if (road=="append") $(selector).append(content);
                    else if (road=="delete") $(selector).remove();                    
                }

                else
                    alert("INFO: unrecognised element found, "+this.tagName+", class = "+$(this).attr("class")+", id = "+$(this).attr("id"));            
            }
            catch(err) {
                log("ERROR: submit_after error caught ["+i+"]: "+err);
            }
        });
    }


    /*
     * When the poker tablename is not available bind the click event of the new suggestions so that they appear in the poker_tablename field
     */
	function bind_to_suggestions() {
        $("div.poker_tablename_suggestions").css("display", "block");
        $("div.poker_tablename_suggestions li a").bind("click", function() {
            $("#poker_tablename").attr("value", $(this).text());
            tablename_check("available");
            return false;
        });
    }


    /*
     * UTILITY: Debugging function
     */
    function log(message) {
        //console.log(new Date+": "+message);
    }


    /*
     * UTILITY: Debugging function
     */
    function error(message) {
        log("ERROR: "+message);
    }


    /*
     * UTILITY: Debugging function
     */
	function message(message) {
        log("MESSAGE: "+message);
    }


    function tablename_check(resp) {
        $("#poker_loader").remove();        

        $("#poker_tablename_availability").attr("value", resp);
        if (resp=="available")
            $("#poker_tablename_check").attr("value", "Table Name Available");
        else {
            $("#poker_tablename_check").attr("value", "Table Name NOT Available");            
            $("div.poker_tablename_suggestions").css("display", "block");
        }
    }


    function copy_value(sel) {
        $("#create_account_form ."+sel).attr("value", $("#"+sel).attr("value"));
    }


    function create_account_callback(outcome, customer_reference) {
        if (!outcome) {
            $("div.step_2 div.errors").css('display', 'block');
            $(".step_1 input,.step_1 select,.step_2 input,.step_2 select").removeAttr("disabled");
            alert("Your account has NOT been created");
        }
        else {
            $('#step_2 fieldset').hide("fast");
            $('#step_3 fieldset').show("slow");
            step_3_tab_active = true;
            message("Your account has been created");
            $(".customer_reference").attr("value", customer_reference);
        }
    }


    function register_card_callback($outcome) {
        if (!$outcome) 
            alert("Your card has NOT been registered");
        else {
            message("Your card has been registered");
            step_4_tab_active = true;
            $('#step_3 fieldset').hide("fast");
            $('#step_4 fieldset').show("slow");
            $(".step_3 input,.step_3 select,.step_3 input").attr("disabled", "disabled");
            $("card", returned_content).each(function() {
                var hach = '<dt class="card_radio"><label for="card_uid"><span class="card_name">'+$("name", this).text()+'</span><span class="card_number">'+$("number", this).text()+'</span></label></dt><dd class="card_uid"><input type="radio" name="card_uid" value="'+$("uid", this).text()+'" /></dd>';
                $("#choose_card").prepend(hach);
            });
        }
    }


    function deposit_funds_callback($outcome) {
        if (!$outcome)
            alert("There was an error deposting funds.");
        else {
            step_5_tab_active = true;
            $('#step_4 fieldset').hide("fast");
            $('#step_5 fieldset').show("slow");
            $(".step_4 input,.step_4 select,.step_4 input").attr("disabled", "disabled");
            $("div.step_5 .deposit_summary").removeAttr("style");            
            $("div.step_5 .deposit_summary .transaction_id").html($("data[name='transaction_id']", returned_content).html());
            $("div.step_5 .deposit_summary .timestamp").html($("data[name='timestamp']", returned_content).html());
            $("div.step_5 .deposit_summary .auth_code").html($("data[name='auth_code']", returned_content).text());
            $("div.step_5 .deposit_summary .amount").html($("data[name='amount']", returned_content).text());
        }
    }


    function validation_error(step, klass, message) {
        log("step = "+step+", klass = "+klass+", message = "+message);

        $(step+" div.errors ul").append('<li class="'+klass+'">'+message+'</li>');
        $(step+" dt."+klass).addClass('error');
    }

    /*
     * Run email throught this regular expression and retrun boolean result
     *
     * TODO: ensure that there will not be a conflict with other JS file when this is integrated with main system
     */
    function validate_email(eee) {
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        return filter.test(eee);
    }
