﻿var MySectors = new Array();

var Core = new function () {

    this.RegisterAccount = new function () {

        this.BackToStep1 = function BackToStep1() {
            ShowStep("#Step2", "#Step1", "#RegistrationForm", 600, 300);
        }

        this.BackToStep2 = function BackToStep2() {
            ShowStep("#Step3", "#Step2", "#RegistrationForm", 600, 650);
        }

        this.BackToStep3 = function BackToStep3() {
            ShowStep("#Step4", "#Step3", "#RegistrationForm", 600, 650);
        }

        this.CreateCompanySectors = function CreateCompanySectors(data) {
            $('#divCompanySectors').empty();

            if (data.d.length == 0) {
                alert('No company sectors found');
            }

            for (var i = 0; i < data.d.length; i++) {
                var cb = document.createElement("input");
                cb.type = "checkbox";
                cb.nextSibling = data.d[i].CompanySectorID;
                cb.id = "checkboxName" + i;
                cb.value = data.d[i].CompanySectorID;
                cb.checked = cb.defaultChecked = false;

                var answerLabel = document.createElement('label');
                answerLabel.appendChild(cb);
                answerLabel.setAttribute('class', 'divSectorOption');
                answerLabel.appendChild(document.createTextNode(data.d[i].Name));

                $('#divCompanySectors').append(answerLabel);
            }
        }

        this.DisplayThankYou = function DisplayThankYou() {

            $("#RegistrationForm").load('/assets/forms/ThankYou.htm');
        }

        this.DisplayError = function DisplayError(Message) {

            $("#RegistrationForm").html('There was an error while attempting to register your account. <br /><br /><strong>' + Message + '</strong>');
        }

        this.DisplayCompanyName = function DisplayCompanyName() {
            $("#hypAddCompany").hide();
            $("#trCompanyName").show();
        }

        this.DisplayAddressInput = function DisplayAddressInput() {
            if ($("#trAddress").css("display") == "none") {

                $("#trAddress").show();
                $("#trAddressTown").show();
                $("#trAddressRegion").show();
                $("#trAddressPostcode").show();
                $("#trCountry").show();
            }
            else {

                $("#trAddress").hide();
                $("#trAddressTown").hide();
                $("#trAddressRegion").hide();
                $("#trAddressPostcode").hide();
                $("#trCountry").hide();
            }

            // Reset any active validation errors
            $("#txtPostCode").attr('class', 'RegForm');
            $("#drpAddress").attr('class', 'RegForm');
        }

        this.DisplaySectorSearch = function DisplaySectorSearch() {
            if ($("#trSearchSector").css("display") == "none") {
                $("#trSearchSector").fadeIn();
            }
            else {
                $("#trSearchSector").fadeOut();
            }
        }

        this.FindPostCode = function FindPostCode() {
            if ($("#txtPostCode").val().length < 5) {
                alert('Postcode invalid');
                return;
            }

            RunPreloader('#spnPostcodeAnywhere');
            PostcodeAnywhere_Interactive_Find_v1_10Begin('NA96-BF93-EZ67-AM96', $.trim($("#txtPostCode").val()), 'English', 'None', '')
        }

        this.LoadSurveyQuestions = function LoadSurveyQuestions(SurveyId) {
            $.ajax({
                type: "POST"
		            , url: "/Code/IceBlue.svc/GetRegistrationQuestions"
                    , contentType: "application/json; charset=utf-8"
		            , dataType: "json"
		            , data: JSON.stringify({ SurveyId: SurveyId })
		            , success: function (data) {
		                Core.RegisterAccount.LoadSurvey(SurveyId, data);
		            }
		            , error: function (data) {
		                Core.RegisterAccount.DisplayError((data.statusText) + " " + (data.status));
		            }
            });
        }

        this.LoadSurvey = function LoadSurvey(SurveyId, data) {

            if (data != null) {

                var Html = '<div id="divSurveyQuestions">';
                Html += '<p>Please fill out the following questions to complete your registration.</p>';

                for (var i = 0; i < data.d.length; i++) {

                    Html += '<p><strong>';
                    Html += data.d[i].Question;
                    Html += '</strong>';
                    Html += '<br />';

                    if (data.d[i].Type == 'YesNo') {
                        Html += '<input type="radio" name="group-' + data.d[i].ConstructionQstId + '" id="group-' + data.d[i].ConstructionQstId + '" value="Yes"> Yes';
                        Html += '<input type="radio" name="group-' + data.d[i].ConstructionQstId + '" id="group-' + data.d[i].ConstructionQstId + '" value="No"> No';
                    }
                    Html += '</p>';
                }

                Html += '</div>';

                Html += '<input type="hidden" value="' + SurveyId + '" id="hidSurveyId" />';
                Html += '<input type="button" value="Save Answers" id="btnSaveSurveyAnswers" />';

                $("#Step4a").html(Html);

                $("#Step4").fadeOut('fast', function () {
                    $("#Step4").hide();
                    $("#Step4a").fadeIn('fast', function () {
                        $("#Step4a").show();
                    });
                });

                return;
            }

            // If we're still executing here, there was a problem loading the question set.
            // Load thank you page as normal - registration handled by WCF service
            Core.RegisterAccount.DisplayThankYou();

        }

        this.LoadSectors = function LoadSectors() {

            $.ajax({
                type: "POST"
		    , url: "/Code/IceBlue.svc/ViewParentLevelSectors"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({})
		    , success: function (data) {
		        Core.RegisterAccount.LoadSectorsService(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
            });
        }

        this.LoadCompanySectors = function LoadCompanySectors() {

            $.ajax({
                type: "POST"
		    , url: "/Code/IceBlue.svc/ViewCompanySectors"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({})
		    , success: function (data) {
		        Core.RegisterAccount.CreateCompanySectors(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
            });
        }

        this.LoadSectorsService = function LoadSectorsService(data) {
            var ddl = document.getElementById('selSectors');

            if (!ddl.options.length > 0) {

                ddl.options.length = 0;

                for (var i = 0; i < data.d.length; i++) {
                    var theOption = new Option;
                    theOption.text = data.d[i].sec_Name;
                    theOption.value = data.d[i].SectorId;
                    ddl.options[(i + 1)] = theOption;
                }
            }
        }

        this.LoadChildSectors = function LoadChildSectors() {

            var siteSectors = {
                ParentSectorId: $("#selSectors").val()
            }

            RunPreloader('#spnLoadChildSectors');

            $.ajax({
                type: "POST"
		    , url: "/Code/IceBlue.svc/ViewChildLevelSectors"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteSectors: siteSectors })
		    , success: function (data) {
		        StopPreloader('#spnLoadChildSectors');
		        Core.RegisterAccount.LoadSectorsChildService(data);
		    }
		    , error: function (data) {
		        StopPreloader('#spnLoadChildSectors');
		        alert((data.statusText) + " " + (data.status));
		    }
            });
        }

        this.LoadSectorsChildService = function LoadSectorsChildService(data) {
            $('#divChildSectorsReg').empty();

            if (data.d.length == 0) {
                alert('No sectors found');
            }

            for (var i = 0; i < data.d.length; i++) {
                var cb = document.createElement("input"); // create input node
                cb.type = "checkbox";
                cb.name = data.d[i].SectorId;
                cb.id = "checkboxName" + i;
                cb.value = data.d[i].SectorId;
                cb.checked = cb.defaultChecked = false;

                var answerLabel = document.createElement('label');
                answerLabel.appendChild(cb);
                answerLabel.setAttribute('class', 'divSectorOption');
                answerLabel.appendChild(document.createTextNode(data.d[i].sec_Name));

                $('#divChildSectorsReg').append(answerLabel);
            }
        }

        this.NewAccountStep1 = function NewAccountStep1() {

            Core.RegisterAccount.NewAccountHideAll();
            $("#Step1").show();
        }

        this.NewAccountStep2 = function NewAccountStep2() {

            var Error = false;

            if ($("#txtEmail").val().length == 0) {
                $('#txtEmail').attr('class', 'RegFormError');
                Error = true;
            }

            if ($("#txtConfEmail").val().length == 0) {
                $('#txtConfEmail').attr('class', 'RegFormError');
                Error = true;
            }

            if ($("#txtPwd").val().length == 0) {
                $('#txtPwd').attr('class', 'RegFormError');
                Error = true;
            }

            if ($("#txtConfPwd").val().length == 0) {
                $('#txtConfPwd').attr('class', 'RegFormError');
                Error = true;
            }

            if (!validateEmail($("#txtEmail").val())) {
                $('#spnError').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError').html('Enter a valid email address');
                Error = true;
            }

            if ($("#txtEmail").val() != $("#txtConfEmail").val()) {
                $('#spnError').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError').html('Your email addresses do not match');
                Error = true;
            }

            if ($("#txtPwd").val() != $("#txtConfPwd").val()) {
                $('#spnError').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError').html('Your passwords do not match');
                Error = true;
            }

            if (!validatePassword($("#txtPwd").val())) {
                $('#spnError').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError').html('Your password is invalid, please enter a new password.  Passwords need to be at least 6 characters in length.');
                Error = true;
            }

            if (Error) {
                return;
            }


            // Don't call this service, if we're already errored
            var siteAccount = {
                Email: $("#txtEmail").val()
            };

            RunPreloader('#spnEmailAvailability', 'Validating email address, please wait.');

            $.ajax({
                type: "POST"
		    , url: "/Code/IceBlue.svc/IsAvailable"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ SiteAccount: siteAccount })
		    , success: function (data) {
		        Core.RegisterAccount.NextStepAfterValidation(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
            });
        }

        this.NewAccountStep3 = function NewAccountStep3() {

            var Error = false;

            if ($("#selTitle").val().length == 0) {
                $('#selTitle').attr('class', 'RegFormError');
                Error = true;
            }

            if ($("#txtFirstName").val().length == 0) {
                $('#txtFirstName').attr('class', 'RegFormError');
                Error = true;
            }

            if ($("#txtSurname").val().length == 0) {
                $('#txtSurname').attr('class', 'RegFormError');
                Error = true;
            }

            if ($("#txtTel").val().length == 0) {
                $('#txtTel').attr('class', 'RegFormError');
                Error = true;
            }

            if (Error) {
                return;
            }

            ShowStep("#Step2", "#Step3", "#RegistrationForm");
        }

        this.NewAccountStep4 = function NewAccountStep4() {

            var Error = false;

            if ($("#trAddress").css("display") == "none") {
                if ($("#txtPostCode").val().length == 0) {
                    $('#txtPostCode').attr('class', 'RegFormError');
                    Error = true;
                }

                if (IsNullOrEmpty($("#drpAddress").val())) {
                    $('#drpAddress').attr('class', 'RegFormError');
                    Error = true;
                }
            }
            else {

                if (IsNullOrEmpty($("#txtAddress1").val())) {
                    $('#txtAddress1').attr('class', 'RegFormError');
                    Error = true;
                }

                if (IsNullOrEmpty($("#txtTown1").val())) {
                    $('#txtTown1').attr('class', 'RegFormError');
                    Error = true;
                }

                if (IsNullOrEmpty($("#txtRegion1").val())) {
                    $('#txtRegion1').attr('class', 'RegFormError');
                    Error = true;
                }

                if (IsNullOrEmpty($("#txtPostcode1").val())) {
                    $('#txtPostcode1').attr('class', 'RegFormError');
                    Error = true;
                }

                if ($("#selCountry1").val().length == 0) {
                    $('#selCountry1').attr('class', 'RegFormError');
                    Error = true;
                }

            }

            if ($("#selUserTypes").val().length == 0) {
                $('#selUserTypes').attr('class', 'RegFormError');
                Error = true;
            }

            if (Error) {
                return;
            }

            ShowStep("#Step3", "#Step4", "#RegistrationForm");

            Core.RegisterAccount.LoadSectors();

            if ($('#hidSiteId').val() == '8') { Core.RegisterAccount.LoadCompanySectors(); }
        }

        this.NewAccountHideAll = function NewAccountHideAll() {
            $("#Step1").hide();
            $("#Step2").hide();
            $("#Step3").hide();
            $("#Step4").hide();
        }

        this.NextStepAfterValidation = function NextStepAfterValidation(data) {

            StopPreloader();

            if (!data.d) {
                Error = true;
                $('#spnError').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError').html('This email address already exists, please supply a new one');
                $('#txtEmail').attr('class', 'RegFormError');
                $('#txtConfEmail').attr('class', 'RegFormError');
            }
            else {
                ShowStep("#Step1", "#Step2", "#RegistrationForm");
            }
        }

        this.RegisterMyAccount = function RegisterMyAccount() {

            var Error = false;

            if (!$('#chkCookies').attr('checked')) {
                $('#spnError4').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError4').html('Please read and accept the privacy policy');
                Error = true;
            }

            if (!$('#chkTermsAndConditions').attr('checked')) {
                $('#spnError4').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError4').html('Please read and accept the terms and conditions');
                Error = true;
            }

            if ($("#divChildSectorsReg input").size() == 0) {
                $('#spnError4').attr('Style', 'color: Red; visibility: visible;');
                $('#spnError4').html('You must choose at least one sector that your business belongs in.');
                Error = true;
            }

            if ($('#hidSiteId').val() == '8') {
                if ($("#divCompanySectors input").size() == 0) {
                    $('#spnError4').attr('Style', 'color: Red; visibility: visible;');
                    $('#spnError4').html('You must choose at least on company sector for your business.');
                    Error = true;
                }
            }

            if (Error) {
                return;
            }

            RunPreloader("#PreLoaderReg");

            var siteAccount = {
                Email: $("#txtEmail").val(),
                Password: $("#txtPwd").val(),
                Title: $("#selTitle").val(),
                Forename: $("#txtFirstName").val(),
                Surname: $("#txtSurname").val(),
                JobTitle: $("#txtJobTitle").val(),
                Telephone: $("#txtTel").val(),
                Mobile: $("#txtMobile").val(),
                UserTypeId: $("#selUserTypes").val(),
                CompanyName: $("#txtCompanyName").val(),
                AddressPlaceId: $("#drpAddress").val(),
                AboutYou: $("#txtAboutYou").val(),
                AboutCompany: $("#txtAboutCompany").val(),
                Website: $("#txtWeb").val(),
                ManualAddress: false,

                MyProperty: '',
                Address1: $("#txtAddress1").val(),
                Address2: $("#txtAddress2").val(),
                Address3: $("#txtAddress3").val(),
                Town: $("#txtTown1").val(),
                County: $("#txtRegion1").val(),
                Postcode: $("#txtPostcode1").val(),
                Country: $("#selCountry1").val(),

                Sectors: null,
                CompanySectors: null
            };

            if ($("#txtAddress1").val().length > 0 && $("#txtPostcode1").val().length > 0) {
                // We have a manual address that's been added
                siteAccount.ManualAddress = true;
            }

            var Sectors = [];

            var myDiv = document.getElementById("divChildSectorsReg");
            var inputArr = myDiv.getElementsByTagName("input");

            for (var i = 0; i < inputArr.length; i++) {
                if (inputArr[i].checked) {
                    var MySectors = {
                        SectorId: inputArr[i].value
                    };
                    Sectors.push(MySectors);
                }
            }

            siteAccount.Sectors = Sectors;


            // New Company Sector Section...
            if ($('#hidSiteId').val() == '8') {
                var CompanySectors = [];
                var MySectorDiv = document.getElementById("divCompanySectors");
                var CompanySectorsArr = MySectorDiv.getElementsByTagName("input");

                for (var i = 0; i < CompanySectorsArr.length; i++) {
                    if (CompanySectorsArr[i].checked) {
                        varAnswers = {
                            CompanySectorID: CompanySectorsArr[i].value
                        };
                        CompanySectors.push(varAnswers);
                    }
                }

                siteAccount.CompanySectors = CompanySectors;
            }

            $.ajax({
                type: "POST"
		    , url: "/Code/IceBlue.svc/RegisterMe"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteAccount: siteAccount })
		    , success: function (data) {
		        Core.RegisterAccount.SaveRegistrationService(data);
		    }
		    , error: function (data) {
		        DisplayError((data.statusText) + " " + (data.status));
		    }
            });
        }

        this.RegisterNewAccount = function RegisterNewAccount() {

            $.ajax({
                type: "POST"
		    , url: "/Code/IceBlue.svc/LoadUserTypes"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({})
		    , success: function (data) {

		        $("#Step1").load('/assets/forms/Step1.htm'
                    , function () {
                        $("#Step2").load('/assets/forms/Step2.htm'
                            , function () {
                                $("#Step3").load('/assets/forms/Step3.htm'
                                    , function () {
                                        $("#Step3 #tdUserType").html(data.d);
                                        $("#Step4").load('/assets/forms/Step4.htm', function () {
                                            Core.RegisterAccount.NewAccountStep1();
                                        });
                                    });

                            });

                    });

		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
            });

        }

        this.SaveRegistrationService = function SaveRegistrationService(data) {

            if (data != null) {

                if (data.d == 'Registered...') {

                    // Load thank you page - registration handled by WCF service
                    Core.RegisterAccount.DisplayThankYou();

                }
                else if (data.d == 'Survey1' || data.d == 'Survey2') {

                    var SurveyId;

                    // "construction" SurveyId = 1
                    // "environmental" SurveyId = 2

                    if (data.d == 'Survey1') SurveyId = 1;
                    if (data.d == 'Survey2') SurveyId = 2;


                    // Load survey questionnaire
                    Core.RegisterAccount.LoadSurveyQuestions(SurveyId);

                }
                else {

                    // Load thank you page - registration handled by WCF service
                    Core.RegisterAccount.DisplayError(data.d);
                }
            }
        }

        this.SaveSurvey = function SaveSurvey() {

            // loop through all answers in div divSurveyQuestions

            var QuestionAnswers = [];

            var myDiv = document.getElementById("divSurveyQuestions");

            if (myDiv != null) {

                var inputArr = myDiv.getElementsByTagName("input");

                if (inputArr != null && inputArr.length > 0) {

                    for (var i = 0; i < inputArr.length; i++) {

                        if (inputArr[i].checked) {

                            var QuestionAnswer = {
                                QuestionId: inputArr[i].id.split('-')[1],
                                Answer: inputArr[i].value,
                                UserEmail: $("#txtEmail").val()
                            };

                            QuestionAnswers.push(QuestionAnswer);
                        }
                    }

                    $.ajax({
                        type: "POST"
		        , url: "/Code/IceBlue.svc/SubmitRegistrationAnswers"
                , contentType: "application/json; charset=utf-8"
		        , dataType: "json"
		        , data: JSON.stringify(
                {
                    QuestionAnswers: QuestionAnswers,
                    SurveyId: parseInt($('#hidSurveyId').val())
                })
		        , success: function (data) {
		            Core.RegisterAccount.DisplayThankYou();
		        }
		        , error: function (data) {
		            Core.RegisterAccount.DisplayError((data.statusText) + " " + (data.status));
		        }
                    });
                }
            }
        }

        this.SearchSectors = function SearchSectors() {

            var siteSectors = {
                SectorName: $("#txtRegSearchSectors").val()
            }

            RunPreloader('#spnRegSearchSector');

            $.ajax({
                type: "POST"
		    , url: "/Code/IceBlue.svc/SearchChildLevelSectors"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteSectors: siteSectors })
		    , success: function (data) {
		        StopPreloader('#spnRegSearchSector');
		        Core.RegisterAccount.LoadSectorsChildService(data);
		    }
		    , error: function (data) {
		        StopPreloader('#spnRegSearchSector');
		        alert((data.statusText) + " " + (data.status));
		    }
            });
        }

        this.ToggleSectors = function ToggleSectors(Option) {
            var myDiv = document.getElementById("divChildSectorsReg");
            var inputArr = myDiv.getElementsByTagName("input");

            for (var i = 0; i < inputArr.length; i++) {
                if (Option) {
                    inputArr[i].checked = true;
                }
                else {
                    inputArr[i].checked = false;
                }
            }
        }
    }
}


// Detect any clicks on the registration form

$(function () {

    $("#btnNextStep2").live('click', function () {
        Core.RegisterAccount.NewAccountStep2();
    });

    $("#btnGoBackStep2").live('click', function () {
        Core.RegisterAccount.BackToStep1();
    });

    $("#btnGoNextStep3").live('click', function () {
        Core.RegisterAccount.NewAccountStep3();
    });

    $("#btnFindPostCode").live('click', function () {
        Core.RegisterAccount.FindPostCode();
    });

    $("#hypAddCompany").live('click', function () {
        Core.RegisterAccount.DisplayCompanyName();
    });

    $("#hypAddAddress").live('click', function () {
        Core.RegisterAccount.DisplayAddressInput();
    });

    $("#btnGoBackToStep2").live('click', function () {
        Core.RegisterAccount.BackToStep2();
    });

    $("#btnGoNextStep4").live('click', function () {
        Core.RegisterAccount.NewAccountStep4();
    });

    $('#selSectors').live('change', function () {
        Core.RegisterAccount.LoadChildSectors();
    });

    $("#hypCantFindSector").live('click', function () {
        Core.RegisterAccount.DisplaySectorSearch();
    });

    $("#btnSearchSector").live('click', function () {
        Core.RegisterAccount.SearchSectors();
    });

    $("#ToggleSelectAll").live('click', function () {
        Core.RegisterAccount.ToggleSectors(true);
    });

    $("#ToggleSelectNone").live('click', function () {
        Core.RegisterAccount.ToggleSectors(false);
    });

    $("#btnBack3").live('click', function () {
        Core.RegisterAccount.BackToStep3();
    });

    $("#btnSignUp").live('click', function () {
        Core.RegisterAccount.RegisterMyAccount();
    });

    $("#btnSaveSurveyAnswers").live('click', function () {
        Core.RegisterAccount.SaveSurvey();
    });
     
});


$(function () {

    $(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
    $.ajaxSetup({
        // Disable caching of AJAX responses    
        cache: false
    });

    $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
    $(".accordion").accordion();

    $("#txtEmail").live('click', function () {
        $(this).attr('class', 'RegForm');
        $('#spnEmailError').empty();
        $('#spnError').attr('Style', 'color: Red; visibility: hidden;');
    });

    $("#txtConfEmail").live('click', function () {
        $(this).attr('class', 'RegForm');
        $('#spnEmailError').empty();
        $('#spnError').attr('Style', 'color: Red; visibility: hidden;');
    });

    $("#txtPwd").live('click', function () {
        $(this).attr('class', 'RegForm');
        $('#spnPasswordError').empty();
        $('#spnError').attr('Style', 'color: Red; visibility: hidden;');
    });

    $("#txtConfPwd").live('click', function () {
        $(this).attr('class', 'RegForm');
        $('#spnPasswordError').empty();
        $('#spnError').attr('Style', 'color: Red; visibility: hidden;');
    });

    $("#selTitle").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtFirstName").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtSurname").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtJobTitle").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtTel").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtMobile").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#selUserTypes").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtPostCode").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#drpAddress").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#selSectors").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#divChildSectors").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtAddress1").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtTown1").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtRegion1").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtPostcode1").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#selCountry1").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtContactFrom").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#txtContactBody").live('click', function () { $(this).attr('class', 'RegForm'); });
    $("#aLookupContact").live('click', function () { LookupContact(); });

    $("#divForgotPwd").dialog();
    $("#divForgotPwd").dialog({
        width: 470,
        height: 160,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    })
    $("#divForgotPwd").dialog("close");

    $("#divNewMsg").dialog();
    $("#divNewMsg").dialog({
        width: 540,
        height: 340,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    })
    $("#divNewMsg").dialog("close");

    $("#Email0").hide();
    $("#Email1").hide();
    $("#Email2").hide();

    $("#PostCodeChange1").hide();
    $("#PostCodeChange2").hide();
    $("#PostCodeChange3").hide();


    $("#btnChangeEmail").toggle(function () {
        $("#Email0").show('fast');
        $("#Email1").show('fast');
        $("#Email2").show('fast');
        $("#btnChangeEmail").val('Hide Email');
    }, function () {
        $("#Email0").hide('fast');
        $("#Email1").hide('fast');
        $("#Email2").hide('fast');
        $("#btnChangeEmail").val('Change Email');
    });

    $("#btnChangeAddress").toggle(function () {
        $("#btnChangeAddress").val('Hide Address');
        $("#PostCodeChange1").show('fast');
        $("#PostCodeChange2").show('fast');
        $("#PostCodeChange3").show('fast');


    }, function () {
        $("#btnChangeAddress").val('Change Address');
        $("#PostCodeChange1").hide('fast');
        $("#PostCodeChange2").hide('fast');
        $("#PostCodeChange3").hide('fast');
    });

    $('.ImageDialog').hide();

    // Dialog Link
    $('#devs img').click(function () {
        // SetImage();
        $('.mainimage').attr("src", $(this).attr("src"));
        //$('#ImageDialog').dialog('open');
        var pos1 = getScrollingPosition();
        $('.ImageDialog').css("top", pos1[1] + 20);
        $('.ImageDialog').fadeIn("slow");
        return false;
    });

    // Dialog Link
    $('#information img').click(function () {
        // SetImage();
        $('.mainimage').attr("src", $(this).attr("src"));
        //$('#ImageDialog').dialog('open');
        var scrollpos = getScrollingPosition();

        var pos1 = getScrollingPosition();
        $('.ImageDialog').css("top", pos1[1] + 20);
        $('.ImageDialog').show();
        return false;
    });

    $('#CloseDiv').click(function () {
        $('.ImageDialog').hide();
    });

});


function getScrollingPosition() {

    var position = [0, 0];

    if (typeof window.pageYOffset != 'undefined') {
        position = [window.pageXOffset, window.pageYOffset];
    }
    else if (typeof document.documentElement.scrollTop != 'undefined' && document.documentElement.scrollTop > 0) {
        position = [document.documentElement.scrollLeft, document.documentElement.scrollTop];
    }
    else if (typeof document.body.scrollTop != 'undefined') {
        position = [document.body.scrollLeft, document.body.scrollTop];
    }

    return position;
}

function RunPreloader(Id, Message) {
    if (Message === undefined) { Message = "" }
    $(Id).html('<img src="/assets/images/ajax-loader.gif" alt="Loading" /> ' + Message);
}

function StopPreloader(Id) {
    $(Id).html('');
}

function LookupContact() {

    $("#divLookupContact").dialog("close").dialog("destroy");
    $("#divLookupContact").dialog({
        width: 600,
        height: 340,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    }).dialog("open");

    $("#divLookupContact").load('/assets/forms/AddressBook.htm');
}

function SearchContacts() {
    var siteAccount = {
        Forename: $('#txtContactSearch').val()
    };

    this.RunPreloader('#spnAddressBookLoader');

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/SearchContacts"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ SiteAccount: siteAccount })
		    , success: function (data) {
		        StopPreloader('#spnAddressBookLoader');
		        $('#divLookupContactResults').html(data.d);
		    }
		    , error: function (data) {
		        StopPreloader('#spnAddressBookLoader');
		        $("#divLookupContactResults").html((data.statusText) + " " + (data.status));
		    }
    });
}

function SelectContact() {
    var UserIdName = $('input[name=LookupUserGroup1]:checked').val()
    var myArray = UserIdName.split(':');

    $('#hidUuserId').attr('value', myArray[0]);
    $('#txtTo').attr('value', myArray[1]);

    $("#divLookupContact").dialog("close").dialog("destroy");
}

function ContactForm() {
    $("#divContact").dialog();
    $("#divContact").dialog({
        width: 540,
        height: 390,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    });

    $("#divContact").dialog("close");
    $("#divContact").load('/assets/forms/Contact.htm');
    $("#divContact").dialog("open");
}

function UpdateAddress() {

    $("#divUpdateAddress").dialog();
    $("#divUpdateAddress").dialog({
        width: 530,
        height: 150,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: false,
        open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); }
    })

    $("#divUpdateAddress").dialog("close");
    //$("#divUpdateAddress").load('/assets/forms/UpdateAddress.htm');
    $("#divUpdateAddress").dialog("open");
    $("#divUpdateAddress").parent().appendTo($("form:first"));
}

function RemoveUser(UserId) {

    var siteAccount = {
        UserId: UserId
    };

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/RemoveUser"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteAccount: siteAccount })
		    , success: function (data) {

		        MsgBox('Remove user', 'We have emailed a delete user confirmation request to ' + data.d.Forename + ' ' + data.d.Surname + '.  This user must confirm that you are able to delete their account.');
		    }
		    , error: function (data) {

		    }
    });
}

function DisplayUser(UserId) {

    var siteAccount = {
        UserId: UserId
    };

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/MemberProfile"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteAccount: siteAccount })
		    , success: function (data) {
		        LoadProfile(data);
		    }
		    , error: function (data) {

		        $("#divForgotPwd").html((data.statusText) + " " + (data.status));
		    }
    });
}

function LoadProfile(data) {
    //$("#divUserProfile").load('/assets/forms/UserProfile.htm');

    if (data != null) {

        $("#divLoadMyProfile").load('/assets/forms/UserProfile.htm'
        , function () {
            if (!IsNullOrEmpty(data.d.Image)) {
                $("#divProfileImage").html('<img src="/Upload/' + data.d.Image + '">');
            }

            $("#lblProfileName").html(data.d.Forename + ' ' + data.d.Surname);
            $("#lblProfileJobTitle").html(data.d.JobTitle);
            $("#lblProfileCompany").html(data.d.CompanyName);
            $("#lblProfileTel").html(data.d.Telephone);
            $("#lblProfileMob").html(data.d.Mobile);

            if (!IsNullOrEmpty(data.d.AboutYou)) {
                $("#lblProfileAbout").html(data.d.AboutYou);
            }
            else {
                $("#lblProfileAbout").html('There is no more information to display.');
            }

            $("#aPmLink").click(function () {
                DisplayNewMailMsgTo(data.d.UserId, data.d.Forename + " " + data.d.Surname);
            });

            $("#divLoadMyProfile").dialog("close").dialog("destroy");
            $('#divLoadMyProfile').attr('title', data.d.Forename + ' ' + data.d.Surname);
            $("#divLoadMyProfile").dialog({
                width: 620,
                height: 400,
                resizable: false,
                autoOpen: false,
                modal: true,
                closeOnEscape: true
            });

            $("#divLoadMyProfile").dialog("close");
            $("#divLoadMyProfile").dialog("open");
        });
    }
    else {
        return;
    }
}

function MsgBox(Title, Message) {

    $('#divMsgBox').attr('title', Title);

    $("#divMsgBox").dialog();
    $("#divMsgBox").dialog({
        width: 430,
        height: 130,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    })

    $("#divMsgBox").dialog("close");
    $("#divMsgBoxInner").html(Message);
    $("#divMsgBox").dialog("open");
}

function CloseMsgBox() {
    $("#divMsgBox").dialog("close");
    return;
}

function UserLogin() {
    $("#divLogin").dialog();
    $("#divLogin").dialog({
        width: 400,
        height: 300,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    })
    $("#divLogin").dialog("close");
    $("#divLogin").dialog("open");
    $("#divLogin").parent().appendTo($("form:first"));
    return false;
}

function DisplayNewMailMsg() {
    $("#divNewMsg").load('/assets/forms/MailBox.htm'
        , function () {
            $("#divNewMsg").dialog("open");
            $('#TextArea1').html('');
            $('#txtTo').html('');
        });
}

function DisplayNewMailMsg(ShowContactSearch) {
    $("#divNewMsg").load('/assets/forms/MailBox.htm'
        , function () {
            $("#divNewMsg").dialog("open");
            $('#TextArea1').html('');
            $('#txtTo').html('');

            if (ShowContactSearch) {
                // Display contact search box
                LookupContact();
            }
        });
}

function DisplayNewMailMsgTo(UserId, NameToShow) {

    $("#divNewMsg").dialog("close").dialog("destroy");
    $("#divNewMsg").dialog({
        width: 540,
        height: 340,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    });
    $("#divNewMsg").dialog("open");

    $("#divNewMsg").load('/assets/forms/MailBox.htm'
        , function () {
            if (IsNullOrEmpty(NameToShow)) {
                NameToShow = 'Unknown user';
            }

            $('#TextArea1').html('');
            $('#txtTo').attr('value', NameToShow);
            $('#hidUuserId').attr('value', UserId);
        });
}

function NewAccount() {
    window.location.href = '/Register.aspx';
}

function validatePassword(Password) {

    if (Password.length < 6) {
        return false;
    }

    return true;
}

function AddMySector(SectorId, SectorName) {
    $('#divSelectedChildren').append('Test');

}

function ResetStep4Error() {
    $('#spnError4').attr('Style', 'color: Red; visibility: hidden;');
}

function ResetPwd() {
    $("#divForgotPwd").dialog("open");
}

function ResetPassword() {

    if ($("#txtForgot").val().length == 0) {
        alert("Please supply a valid email address.");
        return;
    }

    if (!this.validateEmail($("#txtForgot").val())) {
        alert("Please supply a valid email address.");
        return;
    }

    var siteAccount = {
        Email: $("#txtForgot").val()
    };

    this.RunPreloader("#PreLoaderPwd");

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/ForgotPwd"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ SiteAccount: siteAccount })
		    , success: function (data) {
		        StopPreloader("#PreLoaderPwd");
		        $("#divForgotPwd").html(data.d);
		    }
		    , error: function (data) {
		        StopPreloader("#PreLoaderPwd");
		        $("#divForgotPwd").html((data.statusText) + " " + (data.status));
		    }
    });
}

function SendMail() {

    var siteMessage = {
        MsgTo: $("#hidUuserId").val(),
        MsgSubject: $("#txtSubject").val(),
        MsgBody: $("#TextArea1").val()
    };

    RunPreloader('#spnSendingMessage');

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/SendMsg"
        , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteMessage: siteMessage })
		    , success: function (data) {
		        StopPreloader('#spnSendingMessage');
		        SentMsgServiceSucceeded(data);
		    }
		    , error: function (data) {
		        StopPreloader('#spnSendingMessage');
		        $("#spnMessage").html((data.statusText) + " " + (data.status));
		    }
    });
}

function SentMsgServiceSucceeded(data) {
    if (data.d == "Sent") {
        $("#divNewMsg").dialog("close");
        MsgBox('Message sent', 'Your message has been sucsessfully sent');
    }
    else {
        $("#spnMessage").html(data.d);
    }
}

function ViewMail(MailId) {

    var siteMessage = {
        MailId: MailId
    }

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/ViewMsg"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteMessage: siteMessage })
		    , success: function (data) {
		        ViewMailService(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}

function ReplyMail(MailId) {

    var siteMessage = {
        MailId: MailId
    }

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/ViewMsg"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteMessage: siteMessage })
		    , success: function (data) {
		        ReplyMailService(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}

function ReplyMailService(data) {
    $("#divNewMsg").load('/assets/forms/MailBox.htm'
        , function () {
            $("#divNewMsg").dialog();
            $("#divNewMsg").dialog({
                width: 540,
                height: 340,
                resizable: false,
                autoOpen: false,
                modal: true,
                closeOnEscape: true
            });

            $("#divNewMsg").dialog("close");

            var ReplyText = "\r\n\r\n\r\n";

            var MyDate = ConvertFromWCFDateTime(data.d.DateSent).toString();
            ReplyText += (MyDate) + ": ";
            ReplyText += (data.d.Body);

            $('#TextArea1').html(ReplyText);
            $('#txtTo').attr('value', data.d.FirstName);
            $('#txtSubject').attr('value', "Re: " + data.d.Subject);
            $('#hidUuserId').attr('value', data.d.FromUserId);
            $('#hidUuserId').attr('value', data.d.UserId);

            $("#divNewMsg").dialog("open");
        });
}

function ViewMailService(data) {
    $("#divViewMsg").load('/assets/forms/ViewMessage.htm'
        , function () {
            $("#divViewMsg").dialog();
            $("#divViewMsg").dialog({
                width: 540,
                height: 360,
                resizable: false,
                autoOpen: false,
                modal: true,
                closeOnEscape: true
            });

            $("#divViewMsg").dialog("close");

            $('#spnMsgFrom').html(data.d.FirstName);
            $('#spnMsgSubject').html(data.d.Subject);
            $('#spnMsgMessage').html(data.d.Body);

            var MyDate = ConvertFromWCFDateTime(data.d.DateSent).toString();

            $('#spnMsgDate').html(MyDate);

            $("#divViewMsg").dialog("open");

            // Close any active message boxes
            $("#divNewMsg").dialog("close");

            $("#aReplyLink").live('click', function () {
                $("#divViewMsg").dialog("close").dialog("destory");
                ReplyMail(data.d.MailId);
            });
        });
}

function UpdateMyAccount() {

}

function ToggleSelect(Option) {
    var myDiv = document.getElementById("divChildSectorsInner");
    var inputArr = myDiv.getElementsByTagName("input");

    for (var i = 0; i < inputArr.length; i++) {
        if (Option) {
            inputArr[i].checked = true;
        }
        else {
            inputArr[i].checked = false;
        }
    }

}

function UpdateDetails() {

    var siteAccount = {
        //Email: $("#txtEmail").val(),
        CompanyName: $("#txtUpdateCompanyName").val(),
        AddressPlaceId: $("#drpUpdateAddress").val()
    };

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/UpdateDetails"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ SiteAccount: siteAccount })
		    , success: function (data) {
		        $("#divUpdateAddress").dialog("close");
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}

function CancelDetails() {

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/CancelDetails"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({})
		    , success: function (data) {
		        $("#divUpdateAddress").dialog("close");
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}

function ChangeServiceMethod(MethodName) {

    var autoComplete = $find("autoservices");
    autoComplete.set_serviceMethod(MethodName);
}

function SendContactForm() {

    var siteMessage = {
        MsgFrom: $("#txtContactFrom").val(),
        MsgSubject: $("#txtContactSubject").val(),
        MsgBody: $("#txtContactBody").val()
    }

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/ContactForm"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteMessage: siteMessage })
		    , success: function (data) {
		        $("#divContact").dialog("close");
		        MsgBox('Message sent', 'Your message has been sucsessfully sent');
		    }
		    , error: function (data) {

		    }
    });
}

function ChangePassword() {
    $("#divChangeMyPassword").dialog();
    $("#divChangeMyPassword").dialog({
        width: 530,
        height: 300,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: false
    })

    $("#divChangeMyPassword").dialog("close");

    $("#divChangeMyPassword").dialog("open");
    $("#divChangeMyPassword").parent().appendTo($("form:first"));
}

function ShowStep(HideStep, ShowStep, FormName) {
    if ($(HideStep).is(":visible")) {
        $(HideStep).fadeOut('fast', function () {
            $(HideStep).hide();
            $(ShowStep).fadeIn('fast', function () {
                $(ShowStep).show();
            });
        });
    }
}

/*
Postcode functions
*/

function PostcodeAnywhere_Interactive_Find_v1_10Begin(Key, SearchTerm, PreferredLanguage, Filter, UserName) {
    var script = document.createElement("script"),
        head = document.getElementsByTagName("head")[0],
        url = "http://services.postcodeanywhere.co.uk/PostcodeAnywhere/Interactive/Find/v1.10/json.ws?";

    // Build the query string
    url += "&Key=" + encodeURI(Key);
    url += "&SearchTerm=" + encodeURI(SearchTerm);
    url += "&PreferredLanguage=" + encodeURI(PreferredLanguage);
    url += "&Filter=" + encodeURI(Filter);
    url += "&UserName=" + encodeURI(UserName);
    url += "&CallbackFunction=PostcodeAnywhere_Interactive_Find_v1_10End";

    script.src = url;

    // Make the request
    script.onload = script.onreadystatechange = function () {
        if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
            script.onload = script.onreadystatechange = null;
            if (head && script.parentNode)
                head.removeChild(script);
        }
    }

    head.insertBefore(script, head.firstChild);
}

function PostcodeAnywhere_Interactive_Find_v1_10End(response) {
    // Test for an error
    if (response.length == 1 && typeof (response[0].Error) != "undefined") {
        // Show the error message
        alert(response[0].Description);
    }
    else {
        // Check if there were any items found
        if (response.length == 0) {
            alert("Sorry, there were no results");
        }
        else {
            //FYI: The output is an array of key value pairs (e.g. response[0].Id), the keys being:
            //Id
            //StreetAddress
            //Place

            var ddl = document.getElementById('drpAddress');
            ddl.options.length = 0;

            var i;

            for (i = 0; i < response.length; i++) {
                var theOption = new Option;
                theOption.text = response[i].StreetAddress + ', ' + response[i].Place;
                theOption.value = response[i].Id;
                ddl.options[i] = theOption;
            }
        }
    }
    StopPreloader('#spnPostcodeAnywhere');
}

/*
Helper functions
*/

function validateEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    if (emailPattern.test(elementValue) == false) {
        return false;
    }
    return true;
}

// /Date(-2208988800000+0000)/ Represents 01/01/1900 00:00:00, Minimum Date
function ConvertFromWCFDateTime(value) {
    if (IsNullOrEmpty(value)) return "";
    if (value.toString().indexOf("/Date(") == -1) return "";
    if (value == "/Date(-2208988800000+0000)/") return "";

    var string = new String(value.toString());

    while (string.indexOf("/") > -1)
        string = string.replace("/", "");
    $("#divNewMsg").dialog("open");
    return eval("new " + string);
}

function ConvertToWCFDateTime(value) {
    if (IsNullOrEmpty(value)) return "/Date(-2208988800000+0000)/";

    return "/Date(" + value.getTime().toString() + "+" + value.getTimezoneOffset().toString() + ")/";
}

function IsNullOrEmpty(value) {
    return value == undefined || value == null || value == "";
}

function IsNumeric(value) {
    if (IsNullOrEmpty(value)) return false;

    var isNumeric = false;

    try {
        isNumeric = !isNaN(value);
    }
    catch (exception) { }

    return isNumeric;
}

/*
End Helper functions
*/

