﻿$(function () {

    $(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
    $.ajaxSetup({
        // Disable caching of AJAX responses    
        cache: false
    });

});


var MySectors = new Array();

$(document).ready(function () {

    $("#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');
    });

});


function RunPreloader(Id) {
    $(Id).html('<img src="/assets/images/ajax-loader.gif" alt="Loading" />');
}


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: 460,
        height: 160,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    })

    $("#divMsgBox").dialog("close");
    $("#divMsgBoxInner").html(Message);
    $("#divMsgBox").dialog("open");
}


function MsgBox(Title, Message, Width, Height) {

    if (IsNullOrEmpty(Width)) {
        Width = 460;
    }

    if (IsNullOrEmpty(Height)) {
        Height = 160;
    }


    $('#divMsgBox').attr('title', Title);

    $("#divMsgBox").dialog();
    $("#divMsgBox").dialog({
        width: Width,
        height: Height,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    })

    $("#divMsgBox").dialog("close");
    $("#divMsgBoxInner").html(Message);
    $("#divMsgBox").dialog("open");
}


function CloseMsgBox() {
    $('#divMsgBox').fadeOut('fast', function () {
        $("#divMsgBox").dialog("close");
    });
}


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() {

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/LoadUserTypes"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: null
		    , 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 () { NewAccountStep1(); });
                                    });

                            });

                    });

		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });

}


function ShowStep(HideStep, ShowStep, FormName, Width, Height) {
    if ($(HideStep).is(":visible")) {
        $(HideStep).fadeOut('fast', function () {
            $(HideStep).hide();
            $(FormName).dialog().dialog("close");
            $(FormName).dialog({
                width: Width,
                height: Height,
                resizable: false,
                autoOpen: false,
                modal: true,
                closeOnEscape: true
            })
            $(FormName).dialog("open");
            $(ShowStep).fadeIn('fast', function () {
                $(ShowStep).show();
            });
        });
    }
}


function NewAccountStep1() {

    $("#RegistrationForm").dialog("close").dialog("destroy");
    $("#RegistrationForm").dialog({
        width: 600,
        height: 300,
        resizable: false,
        autoOpen: false,
        modal: true,
        closeOnEscape: true
    }).dialog("open");

    $("#Step1").show();

    if ($('#Step2').is(":visible")) {
        $('#Step2').hide();
    }

    if ($('#Step3').is(":visible")) {
        $('#Step3').hide();
    }

    if ($('#Step4').is(":visible")) {
        $('#Step4').hide();
    }
}


function BackToStep1() {
    ShowStep("#Step2", "#Step1", "#RegistrationForm", 600, 300);
}

function BackToStep2() {
    ShowStep("#Step3", "#Step2", "#RegistrationForm", 600, 650);
}

function BackToStep3() {
    ShowStep("#Step4", "#Step3", "#RegistrationForm", 600, 650);
}


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 (Error) {
        return;
    }


    // Don't call this service, if we're already errored
    var siteAccount = {
        Email: $("#txtEmail").val()
    };

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/IsAvailable"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ SiteAccount: siteAccount })
		    , success: function (data) {
		        NextStepAfterValidation(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });

}


function NextStepAfterValidation(data) {
    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", 600, 650);
    }
}


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", 600, 650);
}


function AddMySector(SectorId, SectorName) {
    $('#divSelectedChildren').append('Test');
}


function ResetStep4Error() {
    $('#spnError4').attr('Style', 'color: Red; visibility: hidden;');
}


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", 600, 650);
    LoadSectors();
}


function ResetPwd() {
    $("#divForgotPwd").dialog("open");
}


function ResetPassword() {

    if ($("#txtForgot").val().length == 0) {
        MsgBox("Error", "Please supply a valid email address.");
        return;
    }

    if (!this.validateEmail($("#txtForgot").val())) {
        MsgBox("Error", "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 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;
}


function FindPostCode() {
    if ($("#txtPostCode").val().length < 5) {
        MsgBox('Error', 'Postcode invalid.  Please try again.');
        return;
    }

    RunPreloader('#spnPostcodeAnywhere');
    this.PostcodeAnywhere_Interactive_Find_v1_10Begin('NA96-BF93-EZ67-AM96', $.trim($("#txtPostCode").val()), 'English', 'None', '');
}


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');
}


/**
* Register users account
*/
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 (Error) {
        return;
    }

    this.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
    };

    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;

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/RegisterMe"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({ siteAccount: siteAccount })
		    , success: function (data) {
		        SaveRegistrationService(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}


function SaveRegistrationService(data) {
    // Load thank you page - registration handled by WCF service

    if ($("#Step4").is(":visible")) {
        $("#Step4").fadeOut('fast', function () {
            $("#Step4").hide();
            if (IsNullOrEmpty(data)) {
                $("#RegistrationForm").html("We're sorry, but an error has occured during your registration process.  Please call 01384 563050 for support");
            }
            else {
                if (data.d == "Registered...") {
                    $("#RegistrationForm").load('/assets/forms/ThankYou.htm');
                }
                else {
                    $("#RegistrationForm").html(data.d)
                }
            }
            $("#RegistrationForm").dialog().dialog("close");
            $("#RegistrationForm").dialog({
                width: 600,
                height: 350,
                resizable: false,
                autoOpen: false,
                modal: true,
                closeOnEscape: true
            })
            $("#RegistrationForm").dialog("open");
            $("#RegistrationForm").fadeIn('fast', function () {
                $("#RegistrationForm").show();
            });
        });
    }
}


function DisplayCompanyName() {
    $("#hypAddCompany").hide();
    $("#trCompanyName").show();
}


function DisplaySectorSearch() {
    if ($("#trSearchSector").css("display") == "none") {
        $("#trSearchSector").show();
    }
    else {
        $("#trSearchSector").hide();
    }
}


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');
}


function LoadSectors() {

    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/ViewParentLevelSectors"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: JSON.stringify({})
		    , success: function (data) {
		        LoadSectorsService(data);
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}


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;
        }
    }
}


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');
		        LoadSectorsChildService(data);
		    }
		    , error: function (data) {
		        StopPreloader('#spnLoadChildSectors');
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}


function LoadSectorsChildService(data) {
    $('#divChildSectorsReg').empty();

    if (data.d.length == 0) {
        alert('No sectors found');
    }

    var i;
    for (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);
    }
}


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');
		        LoadSectorsChildService(data);
		    }
		    , error: function (data) {
		        StopPreloader('#spnRegSearchSector');
		        alert((data.statusText) + " " + (data.status));
		    }
    });
}




function UpdateMyAccount() {

}


function divChildSectorsReg(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;
        }
    }

}


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 DisplayUserNotice(Title, Content) {
    $(document).ready(function () {

        $('#divDynamic').append('<div id="divNoticeBox"></div>');
        $('#divNoticeBox').attr('Title', Title).attr('style', 'display: none;');

        $("#divNoticeBox").dialog("close").dialog("destroy");
        $("#divNoticeBox").dialog({
            width: 530,
            height: 300,
            resizable: false,
            autoOpen: false,
            modal: true,
            closeOnEscape: false,
            open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); }
        });
        $("#divNoticeBox").dialog("open")

        $("#divNoticeBox").html(Content + '<br /><p style="text-align: right;"><input type="button" onclick="AcknowledgeNoticeBox()" value="Close" /></p>');
    });
}


function AcknowledgeNoticeBox() {
    $.ajax({
        type: "POST"
		    , url: "/Code/IceBlue.svc/AcknowledgeNoticeBox"
            , contentType: "application/json; charset=utf-8"
		    , dataType: "json"
		    , data: null
		    , success: function (data) {
		        $("#divNoticeBox").dialog("close");
		    }
		    , error: function (data) {
		        alert((data.statusText) + " " + (data.status));
		        $("#divNoticeBox").dialog("close");
		    }
    });
}
