
    /*
     * Author: Karl O'Leary,
     * Company: Emagine Media, http://www.emagine.ie
     * Description: Handle the validation and logic of the registration form
     *
     * Change Log:
     */


    // 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;
	var returned_content = "";


    /*
     * Setup
     */
    function registrationSetup() {
        logger("registrationSetup");


        // form ajax handlers
        // ------------------
        $("#create_account").ajaxForm({beforeSubmit: submit_before, success: create_account_callback});
        $('#register_card').ajaxForm({beforeSubmit: submit_before, success: register_card_callback});
        $('#deposit_funds').ajaxForm({beforeSubmit: submit_before, success: deposit_funds_callback});


        // 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',
            yearRange: '1900:1993',
            showOn: 'both',
            dateFormat: 'M d, yy',
            changeYear: true,
            firstDay: 1,
            maxDate: '-16y',
            minDate: '-108y',
            defaultDate: '-16y'
        });


        // 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 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");
            

            $("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 (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 (!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() {
            var validated = true;
            var sports_username = $("#sports_username").attr("value");
			// Need to check if username starts with "nul"
			var sports_username_substring = sports_username.substring(3,0).toLowerCase();
            var sports_password = $("#sports_password").attr("value");
            var sports_password_retype = $("#sports_password_retype").attr("value");
            var security_question = $("#security_question").attr("value");
            var security_answer = $("#security_answer").attr("value");
            var captcha_value = $("#captcha_value").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_username_substring=="nul") { validated = false; validation_error("div.step_2", "sports_username", "Your username cannot start with " + sports_username_substring.toUpperCase()); }
            if (sports_password=="" || sports_password.length<6) { validated = false; validation_error("div.step_2", "sports_password", "Please enter a Sportsbook Password 6 characters or longer"); }
            if (!contains_a_number(sports_password)) { validated = false; validation_error("div.step_2", "sports_password", "Please enter a Sportsbook Password containing numbers and letters"); }
            if (sports_password_retype=="") { validated = false; validation_error("div.step_2", "security_question_retype", "Please re-enter your Sportsbook Password"); }
            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 an answer to your security question"); }
            if (captcha_value=="") { validated = false; validation_error("div.step_2", "captcha", "Please enter the security code"); }

            if (!validated)
                $("div.step_2 div.errors").css('display', 'block');

            else { 
                $("#create_account").submit();
                $("div.step_1 div.errors").css('display', 'none');
                $("div.step_1 input,.step_1 select,.step_2 input,.step_2 select").attr("disabled", "disabled");                
            }

            return false;
        });

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


        // step #3: card details
        // ---------------------------------------------------------------------------------
        $("#skip_card").bind("click", function() {
            $("div.step_3 input,.step_3 select").attr("disabled", "disabled");
            $('#step_3 fieldset').hide("fast");
            $('#step_5 fieldset').show("slow");
            step_5_tab_active = true;
            highlight_step("step_5");
        });

        $('#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 {                
                $("#register_card").submit();
                $("div.step_3 div.errors").css('display', 'none');
                $("div.step_3 input,.step_3 select").attr("disabled", "disabled");
            }
        });


        // step #4: deposit
        // ----------------
        $("#skip_deposit").bind("click", function() {
            $("div.step_4 input,.step_4 select").attr("disabled", "disabled");
            $('#step_4 fieldset').hide("fast");
            $('#step_5 fieldset').show("slow");
            step_5_tab_active = true;
            highlight_step("step_5");
        });

        $('#step_4_submit').click(function() {
            var validated = true;
            var password = $("#deposit_funds_form .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 (password=="") { validated = false; validation_error("div.step_4", "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").submit();
            }
        });

        // in the case where step #5 is the current_step
        // the this will indicate that the user has returned from their 3ds bank site
        if ($("a.step_5").hasClass("current_step")) {
            $(".transaction_details").css("display", "block");
            $("div.step input,div.step select").attr("disabled", "disabled");
            step_2_tab_active = true;
            step_3_tab_active = true;
            step_4_tab_active = true;
            step_5_tab_active = true;
            
            
            display_loggedin_bar($("#username").text(), $("dl.transaction_details .amount").text());
        }
    }





    /*
     * Highlight the current step
     */
    function contains_a_number(str) {
        if (str.indexOf("0")!=-1)
            return true;
        else if (str.indexOf("1")!=-1)
            return true;
        else if (str.indexOf("2")!=-1)
            return true;
        else if (str.indexOf("3")!=-1)
            return true;
        else if (str.indexOf("4")!=-1)
            return true;
        else if (str.indexOf("5")!=-1)
            return true;
        else if (str.indexOf("6")!=-1)
            return true;
        else if (str.indexOf("7")!=-1)
            return true;
        else if (str.indexOf("8")!=-1)
            return true;
        else if (str.indexOf("9")!=-1)
            return true;
        else
            return false;
    }


    /*
     * Highlight the current step
     */
    function highlight_step(step) {
        $("a.step").removeClass("current_step");
        $("a."+step).addClass("current_step");
    }

    /*
     * Handle the AJAX call back from the create_account action.
     */
    function create_account_callback(responseText, statusText) {        
        logger("create_account_callback, responseText = "+responseText);
        logger("create_account_callback, statusText = "+statusText);

        $("#returned_data").html(responseText);
        $("*").css("cursor", "auto");

        var outcome = $("#returned_data div.response").attr("outcome");        

        // display the logged-in status, enable step #3, update the login bar
        if (outcome=="success") {            
            $('#step_2 fieldset').hide("fast");
            $('#step_3 fieldset').show("slow");
            step_3_tab_active = true;
            logger("Your account has been created");
            highlight_step("step_3");
            
            $("#returned_data div.output").each(function(i) {
                var bbb = $(this).text();
                if (bbb.indexOf("customer_reference")==0)
                    display_loggedin_bar(bbb.substr(19,bbb.length-1), "0.00");
            });
            
            $("input.customer_reference").attr("value", $("#username").text());
        }

        // display the errors & enable the input fields
        else if (outcome=="failure") {
            validation_error("div.step_2", "bbb", "Please fix all of the errors in Steps 1 and 2 before continuing");

            $(".step_1 input,.step_1 select,.step_2 input,.step_2 select").removeAttr("disabled");
            $("#returned_data div.error").each(function(i) {

                // step #1                
                if ($(this).text()=="first_name:empty") validation_error("div.step_1", "first_name", "Please enter your first name");
                else if ($(this).text()=="last_name:empty") validation_error("div.step_1", "last_name", "Please enter your surname");
                else if ($(this).text()=="email:invalid") validation_error("div.step_1", "email", "Please enter a valid email address");
                else if ($(this).text()=="address_1:empty") validation_error("div.step_1", "address_1", "Please enter your address in line #1");
                else if ($(this).text()=="address_2:empty") validation_error("div.step_1", "address_2", "Please enter your address in line #2");
                else if ($(this).text()=="town_city:empty") validation_error("div.step_1", "town_city", "Please enter a value for Town/City");
                else if ($(this).text()=="country:empty") validation_error("div.step_1", "country", "Please select a country");
                else if ($(this).text()=="postcode:empty") validation_error("div.step_1", "postcode", "Please enter your UK postal address");
                else if ($(this).text()=="home_phone:empty") validation_error("div.step_1", "home_phone", "Please enter a home phone number");
                else if ($(this).text()=="data_of_birth:invalid") validation_error("div.step_1", "data_of_birth", "Please enter your date of birth");
                else if ($(this).text()=="user_currency:empty") validation_error("div.step_1", "user_currency", "Please select your prefered currency");
                else if ($(this).text()=="terms_and_conditions:not_checked") validation_error("div.step_1", "terms_and_conditions", "Please read and Terms and Conditions and check the box");              

                // step #2
                else if ($(this).text()=="sports_username:unavailable") validation_error("div.step_2", "sports_username", "Please enter a different Sportsbook ID");
                else if ($(this).text()=="sports_username:wrong_length") validation_error("div.step_2", "sports_username", "Please enter a Sportsbook ID that is between 6 and 8 characters long");
                else if ($(this).text()=="sports_password:dont_match") validation_error("div.step_2", "sports_password_retype", "Please make sure both passwords match");
                else if ($(this).text()=="sports_password:too_short") validation_error("div.step_2", "sports_password", "Please make sure your Sportsbook Password is at least 6 characters long");
                else if ($(this).text()=="captcha:incorrect") validation_error("div.step_2", "captcha", "Please enter the correct Security Code");
            });
        }
    }


    function register_card_callback(responseText, statusText) {
        logger("register_card_callback, responseText = "+responseText);
        logger("register_card_callback, statusText = "+statusText);

        $("#returned_data").html(responseText);
        $("*").css("cursor", "auto");

        var outcome = $("#returned_data div.response").attr("outcome");

        // enable the next step, mine the returned data and add the cards to the form
        if (outcome=="success") {
            $('#step_3 fieldset').hide("fast");
            $('#step_4 fieldset').show("slow");
            step_4_tab_active = true;
            highlight_step("step_4");

            $("#returned_data div.card").each(function(){
                $("#card_list").append("<li><input name=\"card_uid\" type=\"radio\"  value=\""+$("div.uid", this).text()+"\">"+$("div.name", this).text()+" : "+$("div.number", this).text()+"</li>");
            });   

            logger("Your card has been registered");
        }

        // display the errors & enable the input fields
        else if (outcome=="failure") {
            $(".step_3 input,.step_3 select").removeAttr("disabled");
            $("#returned_data div.error").each(function(i) {
                validation_error("div.step_3", "bbb", $(this).text());
            });
        }
    }


    function deposit_funds_callback(responseText, statusText) {
        logger("deposit_funds_callback, responseText = "+responseText);
        logger("deposit_funds_callback, statusText = "+statusText);

        $("#returned_data").html(responseText);
        $("*").css("cursor", "auto");
        
        var outcome = $("#returned_data div.response").attr("outcome");

        // possible outcomes
        // - success, choosen card is fine redirect to bank for signin
        //   - save new form after current form and hide it
        //   - show the redirect message
        //   - after 5 seconds redirect the user
        // - success, choosen card is not 3DS transaction has been completed
        // - error, something has failed somewhere along the way
        if (outcome=="success") {
            var status = "not_3ds_card";
            var amount = "";
            var reference = "";
            var timestamp = "";
            var customer = "";

            $("#returned_data div.output").each(function(i) {
                var pieces = ($(this).html()).split("=");

                if (pieces[0]=="redirect_form") {
                    $("#deposit_funds").after(pieces[1]);
                    $("#redirect_header").css("display", "block");
                }

                else if (pieces[0]=="status")
                    status = pieces[1];

                else if (pieces[0]=="amount")
                    amount = pieces[1];

                else if (pieces[0]=="reference")
                    reference = pieces[1];

                else if (pieces[0]=="customer")
                    customer = pieces[1];

                else if (pieces[0]=="timestamp")
                    timestamp = pieces[1];
            });


            if (status=="not_3ds_card") {
                step_5_tab_active = true;
                $('#step_4 fieldset').hide("fast");
                $('#step_5 fieldset').show("slow");

                $(".transaction_details").css("display", "block");
                $("dl.transaction_details .reference").html(reference);
                $("dl.transaction_details .amount").html(amount);
                $("dl.transaction_details .timestamp").html(timestamp);
                display_loggedin_bar(customer, amount);
                highlight_step("step_5");
            }

            else if (status=="3ds_card") {
                $("#redirect_form").oneTime("5s", function() {
                    $(this).submit();
                });
            }
        }

        else {
            /*
            logger("There was an error deposting funds.");
            $(".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) {
        logger("step = "+step+", klass = "+klass+", message = "+message);

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

    /*
     * Used by the Captcha.asp
     */
    function asp_captcha_refresh_image(valImageId) {
        var objImage = document.images[valImageId];
        if (objImage == undefined) {
            return;
        }
        var now = new Date();
        objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
    }
