﻿// Global Variables       
var AjaxHandlerLocation = "/AjaxHandlers/";
var RootFolder = "/";
var me;

// Global Functions
function CurrentPlayerName()
{
    var PlayerName = "";
    
    $.ajax({
        type: "GET",
        url: AjaxHandlerLocation + "PlayerName.ashx",
        dataType: "xml",
        async: false,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
            RTRBox.toggleCloseButton(true);
        },
        success: function(data, textStatus) {
            // Check for programmed error
            if ($("error", data).text() != "")
            {
                RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                RTRBox.toggleCloseButton(true);
            }
            else
            {
                PlayerName = $("playername", data).text();
            }
        }
    });
    
    return PlayerName;
}

function CurrentPlayerID()
{
    var PlayerID = 0;
    
    $.ajax({
        type: "GET",
        url: AjaxHandlerLocation + "PlayerID.ashx",
        dataType: "xml",
        async: false,
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
            RTRBox.toggleCloseButton(true);
        },
        success: function(data, textStatus) {
            // Check for programmed error
            if ($("error", data).text() != "")
            {
                RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                RTRBox.toggleCloseButton(true);
            }
            else
            {
                PlayerID = parseInt($("playerid", data).text());
            }
        }
    });
    
    return PlayerID;
}

function CurrentPageName()
{
    var sPath = window.location.pathname;
    sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    return sPage;
}

function submitForm(event)
{
    if (event.keyCode == 13)
    {
        var button = document.getElementById('btnLogin');   
        button.click();
    }
}

RBPDisabled = function()
{
    this.init();
}

$.extend(RBPDisabled.prototype,
{
   init: function()
   {
       $.each($(".disabled"), function(index, value)
       {
          $(value).attr("readonly", "readonly");
       });
   } 
});

Authenticate = function()
{}

$.extend(Authenticate.prototype,
{
    check: function()
    {
        var accepted_domains = new Array("rakebackpartners.com", "localhost");
        var domaincheck = document.domain;
        var accepted = false;
        
        for (i = 0; i < accepted_domains.length; i++)
        {
            if (domaincheck.indexOf(accepted_domains[i]) != -1)
            {
                accepted = true;
                break;
            }
        }
        
        return accepted;
    }
});

RBPLogin = function()
{
}

$.extend(RBPLogin.prototype,
{    
    // Class Variables
    LoggedIn: null,
    
    init: function()
    {
        LoggedIn = false;
    },
    
    CheckLoginStatus: function()
    {
        $.ajax({
            type: "POST",
            url: AjaxHandlerLocation + "LogIn.ashx",
            data: { 'login' : false },
            dataType: "xml",
            async: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
                RTRBox.toggleCloseButton(true);
            },
            success: function(data, textStatus) {
                // Check for programmed error
                if ($("error", data).text() != "")
                {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                    RTRBox.toggleCloseButton(true);
                }
                else
                {
                    if ($("loggedin", data).text() == "true")
                    {
                        $("#LoggedIn").show();
                        //$("[name=PlayerName]").html(CurrentPlayerName());
                        $("#CurrentPlayerName").html(CurrentPlayerName());
                        Login.LoggedIn = true;
                    }
                    else
                    {
                        $("#NotLoggedIn").show();
                        Login.LoggedIn = false;
                    }
                }
            }
        }); 
    },
    
    AncillaryLogin: function(Username, Password)
    {
        // Perform Login, if login fails, alert user
        if (this.Login(Username, Password))
        {
            document.location.href = RootFolder + "SiteSelection.aspx";
        }
        else
        {
            RTRBox.toggle('<p style="color: Red; font-weight: bold;">Your login was unsuccessful, please retry.</p>', true);
            RTRBox.toggleCloseButton(true);
        }
    },
    
    AutoLogin: function(RakebackPartnerID)
    {
        // Perform Login if not already logged in
        if (!this.LoggedIn)
            this.Login('', '', RakebackPartnerID)
            
        document.location.href = RootFolder + "SiteSelection.aspx";
    },
    
    Logout: function()
    {
        $.ajax({
            type: "GET",
            url: AjaxHandlerLocation + "Logout.ashx",
            dataType: "xml",
            async: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
                RTRBox.toggleCloseButton(true);
            },
            success: function(data, textStatus) {
                // Check for programmed error
                if ($("error", data).text() != "")
                {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                    RTRBox.toggleCloseButton(true);
                }
                else
                {
                    $('#LoggedIn').hide();
                    $('#NotLoggedIn').show();
                    $.cookie("SignUpRemember", null);
                    document.location.href = RootFolder + "Default.aspx";
                }
            }
        });
    },
    
    Login: function(Username, Password, RakebackPartnerID)
    {
        var Authenticated = null;
        
        $.ajax({
            type: "POST",
            url: AjaxHandlerLocation + "LogIn.ashx",
            data: { 
                'login' : true,
                'username' : $.trim(Username),
                'password' : $.trim(Password),
                'rakebackpartnerid' : RakebackPartnerID
            },
            dataType: "xml",
            async: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
                RTRBox.toggleCloseButton(true);
            },
            success: function(data, textStatus) {
                // Check for programmed error
                if ($("error", data).text() != "")
                {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                    RTRBox.toggleCloseButton(true);
                }
                else
                {
                    if ($("authenticated", data).text() == "false")
                    {
                        Authenticated = false;
                    }
                    else
                    {
                        Authenticated = true;                   
                    }
                }
            }
        }); 
        
        return Authenticated;
    } 
});

RBPSignUp = function()
{
    this.init();
}

$.extend(RBPSignUp.prototype, 
{
    // Object variables
    // Get Array of Hosting Type radios
    HostingTypeRadios: null,
    
    // Specify JSON object of textboxes for each radio
    TextboxLink: null,
    
    // Specify Reverse JSON object of which radio is parent for which textbox
    RadioLink: null,
    
    // Specify JSON object for the terms and conditions checkbox for each radio button
    TandCBoxLink: null,
    
    // Specify Array of Sign Up Buttons
    SignupButtons: null,
    
    // Specify Existing Member variable
    ExistingMember: null,
    
    // The URL the user wants
    URL: "",
        
    init: function()
    {
        this.HostingTypeRadios = $("[name=HostingOption]");
        this.TextboxLink = { 
            "Radios" : {
                "radSubDomain" : Array("txtSubDomain_Host", "txtSubDomain_Domain", "txtSubDomain_TLD"),
                "radFullDomain" : Array("txtFullDomain_Domain", "txtFullDomain_TLD"),
                "radRBPSubDomain" : Array("txtRBPDomain_Host")
            },
            "Validators" : [
                {
                    "radSubDomain" : "SubDomainValidator",
                    "radFullDomain" : "FullDomainValidator",
                    "radRBPSubDomain" : "RBPSubDomainValidator"
                },
                {
                    "radSubDomain" : "SubDomainTaken",
                    "radFullDomain" : "FullDomainTaken",
                    "radRBPSubDomain" : "RBPSubDomainTaken"
                },
                {
                    "radSubDomain": "SubDomainBelongsToUser",
                    "radFullDomain": "FullDomainBelongsToUser",
                    "radRBPSubDomain": "RBPSubDomainBelongsToUser"
                }
            ]
        };
        this.RadioLink = {
            "txtSubDomain_Host" : "radSubDomain", "txtSubDomain_Domain" : "radSubDomain", "txtSubDomain_TLD" : "radSubDomain",
            "txtFullDomain_Domain" : "radFullDomain", "txtFullDomain_TLD" : "radFullDomain",
            "txtRBPDomain_Host" : "radRBPSubDomain"
        };
        this.TandCBoxLink = {
            "radSubDomain" : "chkSubDomain",
            "radFullDomain" : "chkFullDomain",
            "radRBPSubDomain" : "chkRBPSubDomain"
        };
        this.SignupButtons = new Array("btnSubDomain", "btnFullDomain", "btnRBPSubDomain");
        this.ExistingMember = false;
        
        me = this;
        
        // Check if this is the SignUp Page, if it is, see if the player is already logged in and show just the Your Website Details section
        if (CurrentPageName().toLowerCase() == "signup.aspx")
        {
            me.CheckData();
        }
    },
    
    CheckData: function()
    {        
        // Show remembered data
        if ($.cookie("SignUpRemember") != null)
        {
            var RememberObject = JSON.parse($.cookie("SignUpRemember"));
            if (Login.LoggedIn)
            {
                // Existing Member
                me.ExistingMemberShow();
                $("#ExistingMemberLogin").hide();
            }
            else
            {
                // New Member
                me.NewMemberShow();
                
                $("#txtUsername").val(RememberObject.txtUsername);
                $("#txtFirstName").val(RememberObject.txtFirstName);
                $("#txtLastName").val(RememberObject.txtLastName);
                $("#txtMemberEmailAddress").val(RememberObject.txtEmail);
                $("#txtEmail").val(RememberObject.txtEmail);
                $("#txtTelephone").val(RememberObject.txtTelephone);
            }
            
            $('#txtWebsiteName').val(RememberObject.txtWebsiteName);
            $('#txtCompanyName').val(RememberObject.txtCompanyName);
            $('#' + RememberObject.SelectedHostingType).attr('checked', 'checked');
            me.SelectHostingType($('#' + RememberObject.SelectedHostingType));
            
            // Put DomainParts into local variable to as not to break the cookie
            var DomainParts = RememberObject.DomainParts.split('&');
            $.each(DomainParts, function(index, value) {
                var TextBoxParts = value.split('=');
                $('#' + TextBoxParts[0]).val(TextBoxParts[1]);
            });
            
            if ($('#' + me.TandCBoxLink[RememberObject.SelectedHostingType]).is(':checked'))
                $('#' + me.TandCBoxLink[RememberObject.SelectedHostingType]).removeAttr('checked');
                
            // Scroll window to the top
            window.scroll(0,0);
        }
        else
        {
            // Show appropriate panels if logged in or not
            if (Login.LoggedIn)
            {
                $('#ExistingMember').hide();
                $('#YourWebsiteDetails').show();
                $('#txtWebsiteName').focus();
                me.ExistingMember = true;
            }
            else
            {
                $('#ExistingMember').show();
                $('#txtMemberEmailAddress').focus();
                me.ExistingMember = false;
            }
        }
    },
    
    ShowCheckEmailButton: function()
    {
        if ($("#btnCheckEmailAddress").is(":hidden"))
            $("#btnCheckEmailAddress").show();
    },
        
    btnCheckEmailAddress_Click: function()
    {        
        if ($.trim($('#txtMemberEmailAddress').val()) == "")
        {
            $('#EmailCheckValidator').show();
            $('#ExistingMemberLogin').hide();
            $('#AccountDetails').hide();
            $('#YourDetails').hide();
            $('#YourWebsiteDetails').hide();
        }
        else
        {
            // Show Please Wait Screen
            RTRBox.pleaseWait();
            
            $('#EmailCheckValidator').hide();
            
            $.ajax({
                type: "POST",
                url: AjaxHandlerLocation + "SignUp_EmailAddress.ashx",
                data: { 'Email' : $.trim($('#txtMemberEmailAddress').val()) },
                dataType: "xml",
                async: false,
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
                    RTRBox.toggleCloseButton(true);
                },
                success: function(data, textStatus) {
                    // Check for programmed error
                    if ($("error", data).text() != "")
                    {
                        RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                        RTRBox.toggleCloseButton(true);
                    }
                    else
                    {
                        if ($("existingmember", data).text().toLowerCase() == "true")
                        {
                            me.ExistingMemberShow();
                            $("#YourWebsiteDetails").hide();
                        }
                        else
                        {
                            me.NewMemberShow();
                        }
                    }
                }
            });
            
            // Close Please Wait Screen
            RTRBox.close();
        }
    },
    
    ExistingMemberShow: function()
    {
        $("#ExistingMemberLogin").show();
        $("#txtMemberUsername").focus();
        $("#AccountDetails").hide();
        $("#YourDetails").hide();
        $("#YourWebsiteDetails").show();
        $("#btnCheckEmailAddress").hide();
    },
    
    NewMemberShow: function()
    {
        $("#ExistingMemberLogin").hide();
        $("#AccountDetails").show();
        $("#YourDetails").show();
        $("#YourWebsiteDetails").show();
        $("#btnCheckEmailAddress").hide();
        $("#txtUsername").focus();
        $("#txtEmail").val($.trim($("#txtMemberEmailAddress").val()));
    },
    
    btnMemberLogin_Click: function()
    {
        if ($.trim($('#txtMemberUsername').val()) != "" && $.trim($('#txtMemberPassword').val()) != "")
        {
            // Show Please Wait Screen
            RTRBox.pleaseWait();
            
            $('#ExistingMemberLoginValidator').hide();
            
            var Username = $.trim($('#txtMemberUsername').val());
            var Password = $.trim($('#txtMemberPassword').val());
            
            if (Login.Login(Username, Password))
            {
                $('#ExistingMemberLogin').hide();
                $('#YourWebsiteDetails').show();
                $('#txtWebsiteName').focus();
                
                me.ExistingMember = true;
                
                // Change Ancillary to show logged in
                Login.CheckLoginStatus();
            }
            else
            {
                $('#ExistingMemberLoginIncorrect').show();
            }
            
            // Close Please Wait Screen
            RTRBox.close();
        }
        else
        {
            $('#ExistingMemberLoginValidator').show();
        }
    },
    
    SelectHostingType: function(hostingTypeRadio)
    {   
        // Loop through each Radio, clear it's validators and if it isn't the selected one then make sure it's textboxes are emptied and set to disabled
        $.each(me.HostingTypeRadios, function(index, value)
        {
            $("#" + me.TextboxLink.Validators[0][value.id]).hide();
            $("#" + me.TextboxLink.Validators[1][value.id]).hide();
            
            if ($(value).attr('id') != $(hostingTypeRadio).attr('id'))
            {
                $.each(me.TextboxLink.Radios[$(value).attr('id')], function(index, value)
                {
                    $("#" + value).val('').addClass('disabled').attr('readonly', 'readonly');
                });
                $("#" + me.TandCBoxLink[$(value).attr('id')]).attr('disabled', 'disabled').attr('checked', '');
            }
        });
        
        // Now enable the textboxes and checkbox that is needed for the selected HostingType
        $.each(me.TextboxLink.Radios[$(hostingTypeRadio).attr('id')], function(index, value)
        {
            $("#" + value).val('').removeClass('disabled').removeAttr('readonly');
            $("#" + me.TandCBoxLink[$(hostingTypeRadio).attr('id')]).removeAttr('disabled');
        });
        
        // Now disable all the signup buttons as they are dependant on the checkboxes
        $.each(me.SignupButtons, function(index, value)
        {
            $("#" + value).attr('disabled', 'disabled');
        });
    },
    
    ActivateHostingType : function(Textbox)
    {
        // Check Appropriate radio button
        var RadioButtonID = me.RadioLink[$(Textbox).attr("id")];
        $("#" + RadioButtonID).attr("checked", "checked");
        
        if ($(Textbox).is('.disabled'))
            me.SelectHostingType($("#" + RadioButtonID));
    },
    
    ValidateForm: function()
    {
        // Show Please Wait Screen
        RTRBox.pleaseWait();
        
        var FormValid = true;
        var SelectedHostingType;
        var FormErrors = new Array();
        
        // Empty URL  Variable
        me.URL = "";
        
        // If Account Details are needed
        if ($("#AccountDetails").is(":visible"))
        {
            // Check Username was given
            if ($.trim($("#txtUsername").val()) == "")
            {
                $("#rfvUsername").show();
                FormValid = false;
                FormErrors.push($("#rfvUsername").text());
            }
            else
            {
                $("#rfvUsername").hide();
            }
            
            // Check Password was given
            if ($.trim($("#txtPassword").val()) == "")
            {
                $("#rfvPassword").show();
                FormValid = false;
                FormErrors.push($("#rfvPassword").text());
            }
            else
            {
                $("#rfvPassword").hide();
            }
            
            // Check Confirm Password was given
            if ($.trim($("#txtConfirmPassword").val()) == "")
            {
                $("#rfvConfirmPassword").show();
                FormValid = false;
                FormErrors.push($("#rfvConfirmPassword").text());
            }
            else
            {
                $("#rfvConfirmPassword").hide();
                
                // Check that the Password does confirm
                if ($.trim($("#txtPassword").val()) != $.trim($("#txtConfirmPassword").val()))
                {
                    $("#PasswordValidator").show();
                    FormValid = false;
                    FormErrors.push($("#PasswordValidator").text());
                }
                else
                {
                    $("#PasswordValidator").hide();
                }
            }
        }
        
        // If personal details are needed
        if ($("#YourDetails").is(":visible"))
        {
            // Check firstname is given
            if ($.trim($("#txtFirstName").val()) == "")
            {
                $("#rfvFirstName").show();
                FormValid = false;
                FormErrors.push($("#rfvFirstName").text());
            }
            else
            {
                $("#rfvFirstName").hide();
            }
            
            // Check lastname is given
            if ($.trim($("#txtLastName").val()) == "")
            {
                $("#rfvLastName").show();
                FormValid = false;
                FormErrors.push($("#rfvLastName").text());
            }
            else
            {
                $("#rfvLastName").hide();
            }
            
            // Check email is given
            if ($.trim($("#txtEmail").val()) == "")
            {
                $("#rfvEmail").show();
                FormValid = false;
                FormErrors.push($("#rfvEmail").text());
            }
            else
            {
                $("#rfvEmail").hide();
                
                // Check given email is valid
                if (!$("#txtEmail").val().match(/^\S+@\S+\.\S{2,4}$/))
                {
                    $("#revEmail").show();
                    FormValid = false;
                    FormErrors.push($("#revEmail").text());
                }
                else
                {
                    $("#revEmail").hide();
                }
            }
            
            // Check Confirm Email is given
            if ($.trim($("#txtConfirmEmail").val()) == "")
            {
                $("#rfvConfirmEmail").show();
                FormValid = false;
                FormErrors.push($("#rfvConfirmEmail").text());
            }
            else
            {
                $("#rfvConfirmEmail").hide();
                
                // Check that the Email does confirm
                if ($.trim($("#txtEmail").val()) != $.trim($("#txtConfirmEmail").val()))
                {
                    $("#EmailValidator").show();
                    FormValid = false;
                    FormErrors.push($("#EmailValidator").text());
                }
                else
                {
                    $("#EmailValidator").hide();
                }
            }
            
            // Check telephone is given
            if ($.trim($("#txtTelephone").val()) == "")
            {
                $("#rfvTelephone").show();
                FormValid = false;
                FormErrors.push($("#rfvTelephone").text());
            }
            else
            {
                $("#rfvTelephone").hide();
            }
        }
        
        // If Website Details are needed
        if ($("#YourWebsiteDetails").is(":visible"))
        {
            // Check Website Name is given
            if ($.trim($("#txtWebsiteName").val()) == "")
            {
                $("#rfvWebsiteName").show();
                FormValid = false;
                FormErrors.push($("#rfvWebsiteName").text());
            }
            else
            {
                $("#rfvWebsiteName").hide();
                
                // Check for start with http://
                if ($("#txtWebsiteName").val().substring(0, 7).toLowerCase() == "http://")
                    $("#txtWebsiteName").val($("#txtWebsiteName").val().substring(7));
                    
                // Check for start with www.
                if ($("#txtWebsiteName").val().substring(0, 4).toLowerCase() == "www.")
                    $("#txtWebsiteName").val($("#txtWebsiteName").val().substring(4));
                    
                //
                if ($.trim($("#txtWebsiteName").val()).match("[&,?,:]"))
                {
                    $("#rfvRegexWebsiteName").show();
                    FormValid = false;
                    FormErrors.push($("#rfvRegexWebsiteName").text());
                }
            }
        }
        
        // Check that whichever HostingOption was selected, it's textboxes are filled
        $.each(me.HostingTypeRadios, function(index, value)
        {
            if (value.checked)
            {
                SelectedHostingType = value.value;
                var FilledBox = true;
                
                $.each(me.TextboxLink.Radios[value.id], function(index, textbox)
                {
                    if ($.trim($("#" + textbox).val()) == "")
                    {
                        FilledBox = false;
                    }
                    else
                    {
                        if ($.trim($("#" + textbox).val()).substring(0, 4).toLowerCase() == "www.")
                            $("#" + textbox).val($("#" + textbox).val().substring(4));
                        me.URL += $.trim($("#" + textbox).val()) + ".";
                    }
                });
                
                // Remove the trailing dot from the URL
                me.URL = me.URL.substring(0, me.URL.length - 1);
                
                if (!FilledBox)
                {
                    $("#" + me.TextboxLink.Validators[0][value.id]).show();
                    FormValid = false;
                    FormErrors.push($("#" + me.TextboxLink.Validators[0][value.id]).text());
                }
                else
                {
                    $("#" + me.TextboxLink.Validators[0][value.id]).hide();
                    
                    // We know the textboxes were filled properly, now check that the URL given isn't already in use
                    $.ajax({
                        type: "POST",
                        url: AjaxHandlerLocation + "SignUp_URL.ashx",
                        data: { 'URL' : me.URL,
                                'PlayerID': CurrentPlayerID(),
                                'HostingType': SelectedHostingType
                                },
                        dataType: "xml",
                        async: false,
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            FormErrors.push("Error: " + textStatus + "<br />" + errorThrown);
                            FormValid = false;
                        },
                        success: function(data, textStatus) {
                            // Check for programmed error
                            if ($("error", data).text() != "")
                            {
                                FormErrors.push("Error: " + $("error", data).text());
                                FormValid = false;
                            }
                            else if ($("url", data).text() == "belongs_to_user") 
                            {
                                $("#" + me.TextboxLink.Validators[1][value.id]).show();
                                FormErrors.push($("#" + me.TextboxLink.Validators[2][value.id]).text());
                                FormValid = false;
                            }
                            else
                            {
                                if ($("url", data).text() == "taken")
                                {
                                    $("#" + me.TextboxLink.Validators[1][value.id]).show();
                                    FormErrors.push($("#" + me.TextboxLink.Validators[1][value.id]).text());
                                    FormValid = false;
                                }
                                else
                                {
                                    $("#" + me.TextboxLink.Validators[1][value.id]).hide();
                                }
                            }
                        }
                    });
                }
            }
        });
        
        // Validation is now complete, test FormValid variable to determine whether to continue or to show errors
        // The Validation of the new user is done within Signing Up. This is the only bit of Validation not done here
        if (FormValid)
        {
            me.SignupPlayer(SelectedHostingType);
        }
        else
        {
            // Show Errors
            var ErrorString = '<h3 style="color: Red; font-weight: bold;"> There were problems with your entry</h3><ul>';
            $.each(FormErrors, function(index, value) {
                ErrorString += '<li>' + value + '</li>';
            });
            ErrorString += "</ul>"
            RTRBox.toggle(ErrorString);
	    RTRBox.toggleCloseButton(true);
        }
    },
    
    ConfirmTandC: function(TheCheckbox, TheButton)
    {
        if ($(TheCheckbox).is(":checked"))
            $(TheButton).removeAttr("disabled");
        else
            $(TheButton).attr("disabled", "disabled");
    },
    
    RememberDetails: function(SelectedHostingTypeID)
    {
        var RememberObject, DomainParts = "", URL = "", SelectedHostingType;
        
        RememberObject = {
            txtUsername             : null,
            txtPassword             : null,
            txtFirstName            : null,
            txtLastName             : null,
            txtEmail                : null,
            txtTelephone            : null,
            txtWebsiteName          : null,
            txtCompanyName          : null,
            SelectedHostingType     : null,
            SelectedHostingTypeID   : null,
            DomainParts             : null,
            URL                     : null,
            TemplateID              : null
        };
        
        // Determine Selected Hosting Type
        $.each(me.HostingTypeRadios, function(index, value) {
            if (value.checked)
                SelectedHostingType = value;
        });
        
        // If not logged in we need to get the user details
        if (!Login.LoggedIn)
        {
            RememberObject.txtUsername = $("#txtUsername").val();
            RememberObject.txtPassword = $("#txtPassword").val();
            RememberObject.txtFirstName = $("#txtFirstName").val();
            RememberObject.txtLastName = $("#txtLastName").val();
            RememberObject.txtEmail = $("#txtEmail").val();
            RememberObject.txtTelephone = $("#txtTelephone").val();        
        }
        
        // Domain Parts
        $.each(me.TextboxLink.Radios[$(SelectedHostingType).attr('id')], function(index, value)
        {
            DomainParts += value + "=" + $('#' + value).val() + "&";
            URL += $('#' + value).val() + ".";
        });
        
        // Clear Last & from DomainParts
        DomainParts = DomainParts.substring(0, DomainParts.length - 1);
        URL = URL.substring(0, URL.length - 1);
        
        // Extend RememberObject with Website Details
        RememberObject.txtWebsiteName = $("#txtWebsiteName").val();
        RememberObject.txtCompanyName = $("#txtCompanyName").val();
        RememberObject.SelectedHostingType = $(SelectedHostingType).attr('id');
        RememberObject.DomainParts = DomainParts;
        RememberObject.URL = URL;
        
        if (SelectedHostingTypeID)
            RememberObject.SelectedHostingTypeID = SelectedHostingTypeID;
        
        // Store RememberObject in Cookie
        $.cookie("SignUpRemember", JSON.stringify(RememberObject));
    },
    
    SignupPlayer: function(SelectedHostingType)
    {
        // Hide MemberCode validation.
        $("#MemberAlreadyExists").hide();
                
        // Check if this user already exists, if they are trying a new sign up
        if (!Login.LoggedIn)
        {
            $.ajax({
                type: "POST",
                url: AjaxHandlerLocation + "SignUp_CheckForExistingAccount.ashx",
                data: { 
                    'Username'  : $('#txtUsername').val(),
                    'Email'     : $('#txtEmail').val()
                },
                dataType: "xml",
                async: false,
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
		    RTRBox.toggleCloseButton(true);
                },
                success: function(data, textStatus) {
                    // Check for programmed error
                    if ($("error", data).text() != "")
                    {
                        RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '</p>', true);
                        RTRBox.toggleCloseButton(true);
                    }
                    else
                    {
                        // Check if this user already existed
                        if ($("exists", data).text() == "true")
                        {
                            $("#ExistingMemberLogin").show();
                            $("#MemberAlreadyExists").show();
                            $("#AccountDetails").hide();
                            $("#YourDetails").hide();
                            $("#YourWebsiteDetails").hide();
                            $("#txtMemberEmailAddress").val($("#txtEmail").val());
                            $("#btnCheckEmailAddress").hide();
                        }
                        else
                        {
                            // Sign Up is fine, add to RememberObject and proceed
                            me.RememberDetails(SelectedHostingType);
                            document.location.href = "./ChooseTemplate.aspx";
                        }
                    }
                }
            });
        }
        else
        {
            // The user was already logged in, remember and proceed
            me.RememberDetails(SelectedHostingType);
            document.location.href = "./ChooseTemplate.aspx";
        }
    }
});

RBPTemplate = function()
{ }

$.extend(RBPTemplate.prototype,
{
    SelectTemplate: function(TemplateID, SelectingMain) {
        RTRBox.pleaseWait();
    
        // Collect Remember Object out of Cookie
        var RememberObject = JSON.parse($.cookie("SignUpRemember"));
        
        // Add TemplateID into Remember Object
        RememberObject.TemplateID = TemplateID;
        
        // Add Remember Object back into cookie
        $.cookie("SignUpRemember", JSON.stringify(RememberObject));
        
        if (!SelectingMain)
        {
            // Check to see if this Template has Child Templates, unless this is a Child Template call and we are selecting the Main Template
            $.ajax({
                type: "POST",
                url: AjaxHandlerLocation + "Template_HasChildren.ashx",
                data: {
                    "TemplateID" : TemplateID
                },
                dataType: "xml",
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + textStatus + '<br />' + errorThrown + '</p>', true);
                    RTRBox.toggleCloseButton(true);
                },
                success: function(data, textStatus) {
                    // Check for programmed error
                    if ($("error", data).text() != "")
                    {
                        RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                        RTRBox.toggleCloseButton(true);
                    }
                    else
                    {
                        if ($("haschildren", data).text() == "true")
                            document.location.href = './ChooseSubTemplate.aspx?TemplateID=' + TemplateID;
                        else
                            Domain.CreateAccount();
                    }
                }
            });
        }
        else
        {
            Domain.CreateAccount();
        }
        
        return false;
    }
});

RBPDomain = function()
{
    this.init();
}

$.extend(RBPDomain.prototype,
{
    // Object Variables
    DomainCreationHTML: null,
    
    init: function()
    {
        this.DomainCreationHTML = '<div id="sitecreation"> \
                                       <img src="images/rtrbox/loading.gif" alt="wait" class="imageLeft" \/> \
                                       Please Wait while your shiny new Rakeback Site is being created... \
                                   </div>';
    },
    
    CreateAccount: function()
    {
        RTRBox.clearContent('#pleasewait');
        RTRBox.loading();
        RTRBox.toggle(this.DomainCreationHTML);
        
        // Get Remember Object
        var RememberObject = JSON.parse($.cookie("SignUpRemember"));
        var ClassReference = this;
        var RakebackPartnerID = 0;
        
        // Sign Up Player and Create RBP Account
        RTRBox.appendContent('#sitecreation', 'Creating Account.....');
        $.ajax({
            type: "POST",
            url: AjaxHandlerLocation + "SignUp_CreateAccount.ashx",
            data: {
                "ExistingMember"    : Login.LoggedIn,
                "FirstName"         : RememberObject.txtFirstName,
                "LastName"          : RememberObject.txtLastName,
                "Email"             : RememberObject.txtEmail,
                "Username"          : RememberObject.txtUsername,
                "Password"          : RememberObject.txtPassword,
                "Telephone"         : RememberObject.txtTelephone,
                "URL"               : RememberObject.URL,
                "WebsiteName"       : RememberObject.txtWebsiteName,
                "CompanyName"       : RememberObject.txtCompanyName,
                "HostingType"       : RememberObject.SelectedHostingTypeID,
                "TemplateID"        : RememberObject.TemplateID,
                "PlayerID"          : CurrentPlayerID()
            },
            async: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                RTRBox.toggle('<p style="color: Red; font-weight: bold;">An error occurred during the creation of your website, please contact support</p>', true);
                RTRBox.toggleCloseButton(true);
            },
            success: function(data, textStatus) {
                // Check for programmed error
                if ($("error", data).text() != "")
                {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                    RTRBox.toggleCloseButton(true);
                }
                else
                {
                    if ($("status", data).text() == "success")
                    {
                        RakebackPartnerID = parseInt($("rakebackpartnerid", data).text());
                        RTRBox.appendContent('#pleasewait', 'Complete<p />');
                    }
                }
            },
            complete: function(XMLHttpRequest, textStatus) {
                ClassReference.CreateDomain(RakebackPartnerID);
            }
        });
    },
    
    CreateDomain: function(RakebackPartnerID) {
        RTRBox.appendContent('#pleasewait', 'Creating Domain.....');
        
        $.ajax({
            type: "POST",
            url: AjaxHandlerLocation + "SignUp_CreateDomain.ashx",
            data: {
                "RakebackPartnerID" : RakebackPartnerID
            },
            async: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                RTRBox.toggle('<p style="color: Red; font-weight: bold;">An error occurred during the creation of your website, please contact support</p>', true);
                RTRBox.toggleCloseButton(true);
            },
            success: function(data, textStatus) {
                // Check for programmed error
                if ($("error", data).text() != "")
                {
                    RTRBox.toggle('<p style="color: Red; font-weight: bold;">' + $("error", data).text() + '</p>', true);
                    RTRBox.toggleCloseButton(true);
                }
                else
                {
                    // Empty the remember me cookie
                    $.cookie("SignUpRemember", null);
                    
                    if ($("status", data).text() == "0")
                    {
                        RTRBox.appendContent('#pleasewait', 'Complete<p />');
                        document.location.href = "./SignUpComplete.aspx?RakebackPartnerID=" + RakebackPartnerID;
                    }
                    else
                    {
                        RTRBox.appendContent('#pleasewait', 'Not Complete<p />');
                        document.location.href = "./SignUpComplete.aspx?RakebackPartnerID=" + RakebackPartnerID + "&failedcompletion=true";
                    }
                }
            }
        });
    }
});

// Initialisers
var SignUp, Disabled, Auth, Login, Template, Domain;
$(document).ready(function() {
    // Check the agent is allowed to use these scripts
    Auth = new Authenticate();
    if (!Auth.check())
    {
        alert("Un-authorised Script Access");
        document.location.href = "http://www.rakebackpartners.com";
    }
    
    // Check if Cookies are Enabled
    if (!CookiesEnabled())
    {
        RTRBox.toggle('<p style="color: Red; font-weight: bold;">Your Browser is set to not allow Cookies. Rakeback Partners needs cookies in order to function properly. Please enable Cookies and come back to us soon!</p>', false);
	RTRBox.toggleCloseButton(false);
    }
    
    // Check Current Login Status
    Login = new RBPLogin();
    Login.CheckLoginStatus();
    
    // Assign Disabled Textboxes the correct classes
    Disabled = new RBPDisabled();
    
    // Build SignUp Validation groups
    SignUp = new RBPSignUp();
    
    // Build Template Object
    Template = new RBPTemplate();
    
    // Build Domain Object
    Domain = new RBPDomain();
});