﻿var myEditor; // Text editor for Events page (Global variable)

$(document).ready(function () {

    $('#navigation li:last-child').addClass('last');

    $('.signature').bind("contextmenu", function (e) {
        return false;
    });

    $.ajaxSetup({
        // Disable caching of AJAX responses
        cache: false
    });


    // Toggle the visibility radio buttons on the My Profile page
    $('.visibility').live('click', function () {
        $(this).parent('li').find('.visibility').removeClass("on");
        $(this).addClass("on");
        var id = $(this).attr("id");
        $(this).parent('li').find("#rb" + id).click();
    });

    // Remember me login
    $('.checkbox').live('click', function () {
        if ($("#iRememberMe").val() == 0) {
            $("#iRememberMe").val("1");
        } else {
            $("#iRememberMe").val("0");
        }

    });

    $('.checkbox').live('click', function () {

        $(this).toggleClass("on", "");

        if ($("#iCheckbox").val() == "0") {
            $("#iCheckbox").val("1");
        } else {
            $("#iCheckbox").val("0");
        }

    });

    $('#announcement a').live('click', function () {

        $("#announcement p.title").fadeOut();
        $("#announcement img").fadeOut();

        $('#announcement').animate({
            top: '0'
        }, 500, function () {
            // Animation complete.
            $('#announcement').addClass("open");
            $("#announcement img").fadeIn();

            $.get("/SubmitTo/LoadAnnouncement.aspx",
                function (data) {

                    $("#announcement p.main").html(data);
                    $("#announcement p.title").fadeIn();
                    $("#announcement p.title a").hide();
                    $("#announcement p.main").fadeIn();

                });

        });

    });

    $('.closeann').live('click', function () {

        $("#announcement p.main").fadeOut();
        $("#announcement img").fadeOut();

        $('#announcement').animate({
            top: '-70'
        }, 500, function () {
            // Animation complete.
            $('#announcement').removeClass("open");
            $("#announcement img").fadeIn();
            $("#announcement p.title").fadeIn();
            $("#announcement p.title a").fadeIn();
        });

    });

    // Set up the tooltips
    $("span[title]").tooltip();

    // Parent Directory save vCard
    $("#pd-save-vcard").live('click', function () {

        $('#frmVcardExport').submit();

    });

    // Opens child details overlay from Parent Directory page
    $('.pd-overlay').live('click', function () {

        var childId = $(this).attr("id").split("_")[0];
        var contactId = $(this).attr("id").split("_")[1];

        $.get("/ParentZone/SubmitTo/LoadChildDetails.aspx", { cid: childId, conId: contactId },
        function (data) {

            $(".childrecord").html("");
            $(".childrecord").append(data);

            $("#childId").val(childId);
            $("#contactId").val(contactId);

            $("#overlay").data("overlay").load();

        });
    });

    // Reset ParentZone password
    $('#aResetPassword').live('click', function () {

        var userName = $("#userName").val();
        var email = $("#email").val();

        if (userName.length == 0) { // no account name entered

            $(".errorwrap.popup").text("Please enter your username.");
            $(".errorwrap.popup").show();
            $("#accName").focus();

        } else if (email.length == 0) { // no email address entered

            $(".errorwrap.popup").text("Please enter your email address.");
            $(".errorwrap.popup").show();
            $("#email").focus();

        } else {

            $.get("/SubmitTo/ResetPassword.aspx", { aName: userName, sEmail: email },
            function (data) {

                if (data.split("_")[0] == 1) {

                    $(".errorwrap.popup").text("Your password has been sent successfully.");
                    $(".errorwrap.popup").show();

                } else {

                    //$(".errorwrap.popup").text("The details provided have not been recognised. Please try again.");
                    $(".errorwrap.popup").text(data.split("_")[1]);
                    $(".errorwrap.popup").show();

                }

            });
        }

    });

    $('.dt-btn.download').live('click', function () {
        $('#frmExcelExport').attr('action', "/ParentZone/SubmitTo/DownloadAsExcel.aspx");
        $('#frmExcelExport').submit();

        return false;
    });

    $('#pz-download').live('click', function () {
        $('#frmExcelDownload').attr('action', "/Admin/SubmitTo/DownloadAsExcel.aspx");
        $('#frmExcelDownload').submit();

        return false;
    });

    $('.dt-btn.print').live('click', function () {
        $(this).attr('href', "/ParentZone/SubmitTo/ParentDirectoryPrint.aspx?classIds=" + $('#frmExcelExport input[name=classIds]').val());
    });

    $('#printbtn').click(function () {
        window.print();

        return false;
    });


    // Event filter
    $("#filter li a").live('click', function () {

        var ids = '';

        if ($(this).attr("id") == 0) {

            if ($(this).attr("class") == "on") {

                $("#filter li a").removeClass("on");

            } else {

                $("#filter li a").addClass("on");
            }

        } else {

            $(this).toggleClass("on");

            if ($(this).attr("class") != "on") {

                $("#filter li a:first").removeClass("on");

            }

        }

        $('#filter li a.on').each(function (index) {

            if ($(this).attr("id") != 0) {
                ids = ids + $(this).attr("id") + ",";
            }
        });

        if ($(this).parents('ul').hasClass('eventfilter')) {
            var eventTypeId = $("#eventTypeId").val();

            $.get("/ParentZone/SubmitTo/LoadEvents.aspx", { idlist: ids, iEventTypeId: eventTypeId },
                function (data) {

                    oTable.fnClearTable();

                    var arr = data.split("__");

                    for (i = 0; i <= arr.length - 2; i++) {

                        oTable.fnAddData([arr[i].split("_")[0], arr[i].split("_")[1]]); /* Row */

                    }

                    //get all rows and then loop through them
                    var aTrs = oTable.fnGetNodes();

                    for (var i = 0; i < aTrs.length; i++) {
                        $(aTrs[i]).find("td:first").addClass("date");
                    }

                });
        } else {
            $('#frmExcelExport input[name=classIds]').val(ids);
            $.get("/ParentZone/SubmitTo/LoadParents.aspx", { idlist: ids },
                function (data) {

                    oTable.fnClearTable();

                    var arr = data.split("__");

                    for (i = 0; i <= arr.length - 2; i++) {

                        oTable.fnAddData([arr[i].split("*")[0], arr[i].split("*")[1], arr[i].split("*")[2], arr[i].split("*")[3], arr[i].split("*")[4], arr[i].split("*")[5]]); /* Row */

                        if (arr.length > 7) {
                            //                            var oSettings = oTable.fnSettings();
                            //                            var nTr = oSettings.aoData[oTable].nTr;
                            //alert("YES");
                        }
                    }

                    /*var i = arr.length - 1;

                    while (i--) {

                    oTable.fnAddData([arr[i].split("_")[0], arr[i].split("_")[1], arr[i].split("_")[2], arr[i].split("_")[3], arr[i].split("_")[4], arr[i].split("_")[5]]); /* Row */

                    /*}*/


                    if (arr.length > 1) {

                        $('.datatable tr').each(function (index) {
                            if ($(this).find("td:first").html != "") {
                                $(this).find("td:first").addClass("bold");
                            }
                        });

                        // This is to white out the repeating data in the previous row
                        $('input[name=whitetext]').each(function () {
                            $(this).parents('tr').find('td').each(function (index) {
                                if (index < 3) {
                                    $(this).css('color', '#fff');
                                }
                            });
                        });

                    }
                });
        }


        return false;
    });


    // Validate the log-in details on My Profile page
    // prior to opening the password reset overlay window
    $('.pwdchange').live('click', function () {

        $(".errormsg").hide();
        $(".errormsg").text("");

        $("#pwd1").val("");
        $("#pwd2").val("");

        var un = $("#sUsername").val();
        var pw = $("#sPassword").val();

        // Validate log-in details prior to permitting a password change
        $.get("/SubmitTo/AuthenticateLogin.aspx", { username: un, password: pw },
           function (data) {
               if (data == 1) {
                   $("#overlay").data("overlay").load();
               } else {
                   $("#invalidlogin").data("overlay").load();
                   //$(".errormsg").text("Invalid username / password");
                   //$(".errormsg").show();
               }
           });
    });


    // Updates the password on the account
    $('#aChangePwd').live('click', function () {

        $(".errormsg").hide();
        $(".errormsg").text("");

        var pwd1 = $("#pwd1").val();
        var pwd2 = $("#pwd2").val();

        if (pwd1 != pwd2) { // Passwords do not match

            $("#errormsg").text("The passwords you entered do not match.");
            $("#errormsg").show();

        } else if (pwd1.length < 8) { // Length of password provided is too small

            $("#errormsg").text("The password must be a minimum of 8 characters long.");
            $("#errormsg").show();

        } else { // Passwords are valid - OK to update

            $.get("/ParentZone/SubmitTo/UpdatePassword.aspx", { password: pwd1 },
            function (data) {

                if (data == 1) {
                    $("#overlay").data("overlay").close();
                    $("#sPassword").val(pwd1);
                } else {
                    $("#errormsg").text("The password must be a minimum of 8 characters long, and contain at least 1 number and 1 capital letter.");
                    $("#errormsg").show();
                }
            });
        }
    });





    // Validates the Primary contact form on My Profile page
    // Displays error message if invalid
    $('#btnPrimary').live('click', function () {

        if ($("#frmPrimary").valid() == 0) {
            $(".errorwrap").show();
        }
        return false;
    });


    // Validates the Emergency contact form on My Profile page
    // Displays error message if invalid
    $('#btnEmergency').live('click', function () {

        if ($("#frmEmergency").valid() == 0) {
            $(".errorwrap").show();
        }
        return false;
    });


    // Validates the Nanny form on My Profile page
    // Displays error message if invalid
    $('#btnNanny').live('click', function () {

        if ($("#frmNanny").valid() == 0) {
            $(".errorwrap").show();
        }
        return false;
    });

    // Opens the add contact overlay
    $('.addnew').live('click', function () {

        // Reset overlay values
        $("#title").val("");
        $("#firstname").val("");
        $("#lastname").val("");
        $("#mobile").val("");
        $("#work").val("");
        $("#home").val("");
        $("#email").val("");

        $("#add-contact-overlay").find(".errorwrap").hide();

        var contactType = $(".tabs .on").text();
        var contactId;

        if (contactType == "Primary") {
            contactId = 1;
        } else if (contactType == "Emergency") {
            contactId = 2;
        } else {
            contactId = 3;
        }

        // Add contact type id to overlay 
        $("#conTypeId").val(contactId);
        $("#conId").val("0");

        // Hide email & visibility fields if contact is not primary
        if (contactId > 1) {
            $(".primaryonly").hide();
        } else {
            $(".primaryonly").show();
        }

        $("#add-contact-overlay").data("overlay").load();
    });


    // Add new contact
    $('#aAddContact').live('click', function () {

        var contactTypeId = $("#conTypeId").val();

        $("#add-contact-overlay").find(".errorwrap").text("");
        $("#add-contact-overlay").find(".errorwrap").hide();

        if ($("#title").val().length == 0) { // Missing username

            $("#title").focus();
            $("#add-contact-overlay").find(".errorwrap").text("Please enter a title for the contact");
            $("#add-contact-overlay").find(".errorwrap").show();

        } else if ($("#firstname").val().length == 0) { // Missing username

            $("#firstname").focus();
            $("#add-contact-overlay").find(".errorwrap").text("Please enter the contacts first name");
            $("#add-contact-overlay").find(".errorwrap").show();

        } else if ($("#lastname").val().length == 0) { // Missing Password

            $("#lastname").focus();
            $("#add-contact-overlay").find(".errorwrap").text("Please enter the contacts last name");
            $("#add-contact-overlay").find(".errorwrap").show();

        } else if ($("#mobile").val().length == 0) {

            $("#mobile").focus();
            $("#add-contact-overlay").find(".errorwrap").text("The enter the contacts mobile number");
            $("#add-contact-overlay").find(".errorwrap").show();

        } else if ($("#work").val().length == 0) {

            $("#work").focus();
            $("#add-contact-overlay").find(".errorwrap").text("The enter the contacts work number");
            $("#add-contact-overlay").find(".errorwrap").show();

        } else if ($("#home").val().length == 0) {

            $("#home").focus();
            $("#add-contact-overlay").find(".errorwrap").text("The enter the contacts home number");
            $("#add-contact-overlay").find(".errorwrap").show();

        } else if ($("#email").val().length > 0 && contactTypeId == 1 && !$("#email").val().match(/^\w[\w|\.|\-]+@\w[\w|\.|\-]+\.[a-zA-Z]{2,4}$/)) {

            $("#email").focus();

            $("#add-contact-overlay").find(".errorwrap").text("Please enter a valid email address, but this field in NOT mandatory");
            $("#add-contact-overlay").find(".errorwrap").show();

        } else {

            var contactId = $("#conId").val();
            var account = $("#iAccountId").val();
            var title = $("#title").val();
            var firstname = $("#firstname").val();
            var lastname = $("#lastname").val()
            var mobile = $("#mobile").val();
            var work = $("#work").val();
            var home = $("#home").val();
            var email = $("#email").val();
            var visibility = $('input:radio[name=rVisibility]:checked').val();

            $.get("/ParentZone/SubmitTo/AddContact.aspx",
            {
                iContactId: contactId,
                iContactTypeId: contactTypeId,
                iAccountId: account,
                sTitle: title,
                sFirstname: firstname,
                sLastname: lastname,
                sMobile: mobile,
                sWork: work,
                sHome: home,
                sEmail: email,
                iVisibility: visibility
            },
            function (data) {

                contactId = data.split("__")[0]

                // Close the overlay
                $("#add-contact-overlay").data("overlay").close();

                // Get parent form  object
                var form = $("#frm" + $('.tabs').find("a.on").text());

                if ($("#" + data.split("__")[0]).length == 0) { // add new contact

                    if (contactTypeId == 1) { // Primary contact - insert before the address div
                        $(data.split("__")[1]).insertBefore($('#address'));
                    } else {

                        if ($(form).children("div:last").length == 0) { // No contacts found

                            $(form).append(data.split("__")[1]);

                        } else { // Add new contact after last contact

                            $(data.split("__")[1]).insertAfter($(form).children("div:last"))
                        }
                    }

                    // Update the numbering of the new contact
                    var lng = form.find('h3.contact:visible').length;
                    $("#" + contactId).find('h3').text("Contact " + lng)

                } else { // update existing contact

                    var contactNo = $("#" + data.split("__")[0]).find("h3").text();
                    $("#" + data.split("__")[0]).replaceWith(data.split("__")[1]);
                    $("#" + data.split("__")[0]).find("h3").replaceWith("<h3>" + contactNo + "</h3>");
                }
                $("span[title]").tooltip();
            });
        }

    });


    // Opens the edit address overlay
    $('.editaddress').live('click', function () {

        var accountId = $("#iAccountId").val();
        $("#addAccId").val(accountId);

        $.get("/ParentZone/SubmitTo/GetAddress.aspx",
            {
                iAccountId: accountId
            },
            function (data) {

                $("#address1").val(data.split("__")[0]);
                $("#address2").val(data.split("__")[1]);
                $("#town").val(data.split("__")[2]);
                $("#county").val(data.split("__")[3]);
                $("#postcode").val(data.split("__")[4]);

            });

        $("#edit-address").data("overlay").load();

    });


    // Saves the address
    $('#saveaddress').live('click', function () {

        if ($("#address1").val().length == 0) {

            $("#address1").focus();
            $("#edit-address").find(".errorwrap").text("Please enter the first line of the address");
            $("#edit-address").find(".errorwrap").show();

        } else if ($("#town").val().length == 0) {

            $("#town").focus();
            $("#edit-address").find(".errorwrap").text("Please enter the name of the town");
            $("#edit-address").find(".errorwrap").show();

        } else if ($("#county").val().length == 0) {

            $("#town").focus();
            $("#edit-address").find(".errorwrap").text("Please enter the name of the county");
            $("#edit-address").find(".errorwrap").show();

        } else if ($("#postcode").val().length == 0) {

            $("#town").focus();
            $("#edit-address").find(".errorwrap").text("Please enter the postcode");
            $("#edit-address").find(".errorwrap").show();

        } else {

            var accId = $("#addAccId").val();
            var address1 = $("#address1").val();
            var address2 = $("#address2").val();
            var town = $("#town").val();
            var county = $("#county").val();
            var postcode = $("#postcode").val();

            $.get("/ParentZone/SubmitTo/SaveAddress.aspx",
                {
                    iAccountId: accId,
                    sAddress1: address1,
                    sAddress2: address2,
                    sTown: town,
                    sCounty: county,
                    sPostcode: postcode
                },
                function (data) {

                    $("#address ul").replaceWith(data);
                    $("#edit-address").data("overlay").close();

                });
        }

    });

    // Opens the edit contact overlay
    $('.editcontact').live('click', function () {

        // Reset overlay values
        $("#title").val("");
        $("#firstname").val("");
        $("#lastname").val("");
        $("#mobile").val("");
        $("#work").val("");
        $("#home").val("");
        $("#email").val("");

        var contactType = $(".tabs .on").text();
        var contactTypeId;

        if (contactType == "Primary") {
            contactTypeId = 1;
        } else if (contactType == "Emergency") {
            contactTypeId = 2;
        } else {
            contactTypeId = 3;
        }

        // Add contact type id to overlay 
        $("#conTypeId").val(contactTypeId);

        // Hide email & visibility fields if contact is not primary
        if (contactTypeId > 1) {
            $(".primaryonly").hide();
        } else {
            $(".primaryonly").show();
        }

        // Get contact id
        var contactId = $(this).parent(".frmsection:first").attr("id");
        $("#conId").val(contactId);

        // Load values and populate the form
        $.get("/ParentZone/SubmitTo/LoadContact.aspx", { id: contactId },
            function (data) {

                $("#title").val(data.split("__")[0]);
                $("#firstname").val(data.split("__")[1]);
                $("#lastname").val(data.split("__")[2]);
                $("#mobile").val(data.split("__")[3]);
                $("#work").val(data.split("__")[4]);
                $("#home").val(data.split("__")[5]);
                $("#email").val(data.split("__")[6]);

                $("#on").removeClass("on");
                $("#off").removeClass("on");

                if (data.split("__")[7] == "True") {
                    $("#rbon").click();
                    $("#on").addClass("on");
                } else {
                    $("#rboff").click();
                    $("#off").addClass("on");
                }

                $("#add-contact-overlay").find(".errorwrap").text("");
                $("#add-contact-overlay").find(".errorwrap").hide();

                $("#add-contact-overlay").data("overlay").load();
            });
    });


    // Toggles the contact tabs on the My Profile page
    $('.tabs').find("a").live('click', function () {

        if ($(this).attr("class") != "addnew") {

            $(".errorwrap").hide();

            $('.tabs').find("a").removeClass("on");
            $(this).addClass("on");

            var tabname = $(this).html();

            $(".formwrap").find("form").hide();

            $("#frm" + tabname).show();
        }
    });


    // Opens the delete contact overlay    
    $('.deletecontact').live('click', function () {

        $("#delete-contact-overlay").data("overlay").load();

        var contactId = $(this).parent(".frmsection:first").attr("id");
        $("#contactId").val(contactId);
    });


    // Deletes the selected contact 
    $('#aConfirmDelete').live('click', function () {

        $("#delete-contact-overlay").data("overlay").close();

        // Delete the contact here
        $.get("/ParentZone/SubmitTo/DeleteContact.aspx", { id: $("#contactId").val() },
            function (data) {

                $("#" + $("#contactId").val()).slideUp('slow', function () {

                    // Re-order contact numbering
                    var form = $("#" + $("#contactId").val()).parent("form:first");
                    var count = 1;

                    form.find('h3.contact').each(function (index) {
                        if ($(this).is(":visible")) {
                            $(this).text("Contact " + count);
                            count++;
                        }
                    });
                });

            });

    });

    // ----------------------------------------------------------
    // ADMIN AREA
    // ----------------------------------------------------------

    // Opens the add admin account overlay
    $('#add-account').live('click', function () {

        // Reset form values
        $("#addaccount").find(".errorwrap").text("");
        $("#addaccount").find(".errorwrap").hide();

        $("#addaccount").find("#accountId").val("0");
        $("#addaccount").find("#adminAccountName").val("");
        $("#addaccount").find("#adminUsername").val("");
        $("#addaccount").find("#adminPassword").val("");
        $("#addaccount").find("#adminRepeatPassword").val("");

        // Open overlay
        $("#addaccount").data("overlay").load();
    });


    // Validates and saves a new admin account
    $('#aSaveAccount').live('click', function () {

        if ($("#adminAccountName").val().length == 0) { // Missing username

            $("#adminAccountName").focus();
            $("#addaccount").find(".errorwrap").text("Please enter a name for the account");
            $("#addaccount").find(".errorwrap").show();

        } else if ($("#adminUsername").val().length == 0) { // Missing username

            $("#adminUsername").focus();
            $("#addaccount").find(".errorwrap").text("Please enter a username for the account");
            $("#addaccount").find(".errorwrap").show();

        } else if ($("#adminPassword").val().length < 8) { // Missing Password

            $("#adminPassword").focus();
            $("#addaccount").find(".errorwrap").text("Password must be a minimum of 8 characters.");
            $("#addaccount").find(".errorwrap").show();

        } else if ($("#adminPassword").val() != $("#adminRepeatPassword").val()) { // Passwords do not match

            $("#adminRepeatPassword").focus();
            $("#addaccount").find(".errorwrap").text("The passwords entered do not match");
            $("#addaccount").find(".errorwrap").show();

        } else {

            var id = $("#accountId").val();
            var name = $("#adminAccountName").val();
            var username = $("#adminUsername").val();
            var password = $("#adminPassword").val();

            $.get("/Admin/SubmitTo/AddAdminAccount.aspx", { accountId: id, accountName: name, adminUsername: username, adminPassword: password },
            function (data) {
                if (data.split("__")[0] > 0) { // Account added ok

                    $("#addaccount").data("overlay").close();

                    var dataarray = new Array();
                    oSettings = oTable.fnSettings();

                    dataarray[0] = $.trim(data.split("__")[1]);
                    dataarray[1] = $.trim(data.split("__")[2]);
                    dataarray[2] = $.trim(data.split("__")[3]);
                    dataarray[3] = $.trim(data.split("__")[4]);
                    dataarray[4] = $.trim(data.split("__")[5]);

                    // Refresh page
                    window.location = "/Admin/Default.aspx"

                } else { // A problem occured / output message                    
                    $("#addaccount").find(".errorwrap").text(data.split("__")[1]);
                    $("#addaccount").find(".errorwrap").show();

                }
            });
        }
    });


    // Opens the edit admin account overlay and populates fields
    $('.edit.ac').live('click', function () {

        // Reset form values
        $("#addaccount").find(".errorwrap").text("");
        $("#addaccount").find(".errorwrap").hide();

        $("#addaccount").find("#adminAccountName").val("");
        $("#addaccount").find("#adminUsername").val("");
        $("#addaccount").find("#adminPassword").val("");
        $("#addaccount").find("#adminRepeatPassword").val("");

        var id = $(this).closest("tr").attr("id");

        $.get("/Admin/SubmitTo/LoadAdminAccount.aspx", { accountId: id },
            function (data) {
                $("#accountId").val(id);
                $("#adminAccountName").val(data.split("__")[0]);
                $("#adminUsername").val(data.split("__")[1]);
                $("#adminPassword").val(data.split("__")[2]);
                $("#adminRepeatPassword").val(data.split("__")[2]);

                // Load the overlay
                $("#addaccount").data("overlay").load();
            });
    });


    // Opens the delete admin account overlay
    $('.delete').live('click', function () {

        var id = $(this).closest("tr").attr("id");
        $("#id").val(id);

        // Load the overlay
        $("#deleteoverlay").data("overlay").load();
    });

    // Opens the account contacts page
    $('.contacts').live('click', function () {

        var id = $(this).closest("tr").attr("id");
        window.location = "/Admin/AccountContacts.aspx?accId=" + id;
    });


    // Deletes the Admin Account
    $('#aDeleteAccount').live('click', function () {
        var id = $("#id").val();

        $.get("/Admin/SubmitTo/DeleteAdminAccount.aspx", { accountId: id },
        function (data) {

            // Close the overlay
            $("#deleteoverlay").data("overlay").close();

            // Refresh page
            window.location = "/Admin/Default.aspx"
        });

    });

    // Enables / disables an admin account
    $('.disable.ac').live('click', function () {

        var obj = this;
        var id = $(this).closest("tr").attr("id");
        $("#id").val(id);

        $.get("/Admin/SubmitTo/ToggleAccount.aspx", { accountId: id },
        function (data) {
            $(obj).toggleClass("off");

            if ($(obj).text() == "enable") {
                $(obj).text("disable")
            } else {
                $(obj).text("enable")
            }
        });
    });


    // Authenticates login details
    $('#bLogin').live('click', function () {

        var un = $("#sUsername").val();
        var pw = $("#sPassword").val();

        $.get("/SubmitTo/AuthenticateAdminLogin.aspx", { username: un, password: pw },
        function (data) {

            if (data == 1) {
                $("#frmLogin").submit();
            } else {
                $(".errorwrap").show();
            }
        });

    });

    // PARENT ZONE ADMIN

    $('#loginbtn').live('click', function () {
        var un = $("#sUsername").val();
        var pw = $("#sPassword").val();
        var rem = $("#iRememberMe").val();

        AuthenticateLogin(un, pw, rem);
    });

    $('#acceptbtn').live('click', function () {
        var un = $("#sUsername").val();
        var pw = $("#sPassword").val();
        var rem = $("#iRememberMe").val();

        $.get("/SubmitTo/AcceptTermsAndConditions.aspx", { username: un, password: pw },
        function (data) {

            if (data == 1) {
                AuthenticateLogin(un, pw, rem);
                $('#frmLogin').submit();
            } else {

                $(".errorwrap").text("Invalid username / password");
                $(".errorwrap").show();

            }

        });
    });

    $('#declinebtn').live('click', function () {
        $("#termsoverlay").data("overlay").close();
    });


    // Opens the add admin account overlay
    $('#add-pz-account').live('click', function () {

        // Reset form values
        $("#addaccount").find(".errorwrap").text("");
        $("#addaccount").find(".errorwrap").hide();

        $("#addaccount").find("#accountId").val("0");
        $("#addaccount").find("#adminAccountName").val("");
        $("#addaccount").find("#adminUsername").val("");
        $("#addaccount").find("#adminPassword").val("");
        $("#addaccount").find("#adminRepeatPassword").val("");

        $("#addaccount").find("#pzAccountName").val("");
        $("#addaccount").find("#pzAddressLine1").val("");
        $("#addaccount").find("#pzAddressLine2").val("");
        $("#addaccount").find("#pzTown").val("");
        $("#addaccount").find("#pzCounty").val("");
        $("#addaccount").find("#pzPostcode").val("");
        $("#addaccount").find("#pzUsername").val("");
        $("#addaccount").find("#pzPassword").val("");
        $("#addaccount").find("#pzRepeatPassword").val("");

        // Open overlay
        $("#addaccount").data("overlay").load();
    });


    // Validates and saves a new ParentZone account
    $('#pzSaveAccount').live('click', function () {

        if ($("#pzAccountName").val().length == 0) { // Missing username

            $("#pzAccountName").focus();
            $("#addaccount").find(".errorwrap").text("Please enter a name for the account");
            $("#addaccount").find(".errorwrap").show();

            //        } else if ($("#pzAddressLine1").val().length == 0) { // Missing username

            //            $("#pzAddressLine1").focus();
            //            $("#addaccount").find(".errorwrap").text("Please enter the first line of the address");
            //            $("#addaccount").find(".errorwrap").show();

            //        } else if ($("#pzTown").val().length == 0) { // Missing username

            //            $("#pzTown").focus();
            //            $("#addaccount").find(".errorwrap").text("Please enter a town");
            //            $("#addaccount").find(".errorwrap").show();

            //        } else if ($("#pzCounty").val().length == 0) { // Missing username

            //            $("#pzCounty").focus();
            //            $("#addaccount").find(".errorwrap").text("Please enter a county");
            //            $("#addaccount").find(".errorwrap").show();

            //        } else if ($("#pzPostcode").val().length == 0) { // Missing username

            //            $("#pzPostcode").focus();
            //            $("#addaccount").find(".errorwrap").text("Please enter a postcode");
            //            $("#addaccount").find(".errorwrap").show();

        } else if ($("#pzUsername").val().length == 0) { // Missing username

            $("#pzUsername").focus();
            $("#addaccount").find(".errorwrap").text("Please enter a username for the account");
            $("#addaccount").find(".errorwrap").show();

        } else if ($("#pzPassword").val().length < 8) { // Missing Password

            $("#pzPassword").focus();
            $("#addaccount").find(".errorwrap").text("Password must be a minimum of 8 characters.");
            $("#addaccount").find(".errorwrap").show();

        } else if ($("#pzPassword").val() != $("#pzRepeatPassword").val()) { // Passwords do not match

            $("#pzRepeatPassword").focus();
            $("#addaccount").find(".errorwrap").text("The passwords entered do not match");
            $("#addaccount").find(".errorwrap").show();

        } else {

            var id = $("#accountId").val();
            var name = $("#pzAccountName").val();
            var address1 = $("#pzAddressLine1").val();
            var address2 = $("#pzAddressLine2").val();
            var town = $("#pzTown").val();
            var county = $("#pzCounty").val();
            var postcode = $("#pzPostcode").val();
            var username = $("#pzUsername").val();
            var password = $("#pzPassword").val();

            $.get("/Admin/SubmitTo/SaveParentZoneAccount.aspx",
                {
                    accountId: id,
                    accountName: name,
                    addressLine1: address1,
                    addressLine2: address2,
                    sTown: town,
                    sCounty: county,
                    sPostcode: postcode,
                    pzUsername: username,
                    pzPassword: password
                },
            function (data) {

                if (data.split("__")[0] > 0) { // Account added ok

                    $("#addaccount").data("overlay").close();

                    window.location = "/Admin/Accounts.aspx"

                } else { // A problem occured / output message

                    $("#addaccount").find(".errorwrap").text(data.split("__")[1]);
                    $("#addaccount").find(".errorwrap").show();

                }
            });
        }
    });


    // Deletes the ParentZone Account
    $('#pzDeleteAccount').live('click', function () {
        var id = $("#id").val();

        $.get("/Admin/SubmitTo/DeleteParentZoneAccount.aspx", { accountId: id },
        function (data) {

            // Close the overlay
            $("#deleteoverlay").data("overlay").close();

            window.location = "/Admin/Accounts.aspx"

        });
    });

    // Enables / disables a ParentZone account
    $('.disable.pz').live('click', function () {

        var obj = this;
        var id = $(this).closest("tr").attr("id");

        $("#id").val(id);

        $.get("/Admin/SubmitTo/ToggleParentZoneAccount.aspx", { accountId: id },
        function (data) {

            $(obj).toggleClass("off");

            if ($(obj).text() == "enable") {
                $(obj).text("disable")
            } else {
                $(obj).text("enable")
            }
        });
    });

    // Opens the edit ParentZone account overlay
    $('.edit.pz').live('click', function () {

        //Reset form values
        $("#addaccount").find(".errorwrap").text("");
        $("#addaccount").find(".errorwrap").hide();

        $("#addaccount").find("#pzAccountName").val("");
        $("#addaccount").find("#pzAddressLine1").val("");
        $("#addaccount").find("#pzAddressLine2").val("");
        $("#addaccount").find("#pzTown").val("");
        $("#addaccount").find("#pzCounty").val("");
        $("#addaccount").find("#pzPostcode").val("");
        $("#addaccount").find("#pzUsername").val("");
        $("#addaccount").find("#pzPassword").val("");
        $("#addaccount").find("#pzRepeatPassword").val("");

        var id = $(this).closest("tr").attr("id");

        $.get("/Admin/SubmitTo/LoadParentZoneAccount.aspx", { accountId: id },
            function (data) {
                $("#accountId").val(id);
                $("#pzAccountName").val(data.split("__")[0]);
                $("#pzUsername").val(data.split("__")[1]);
                $("#pzPassword").val(data.split("__")[2]);
                $("#pzRepeatPassword").val(data.split("__")[2]);
                $("#pzAddressLine1").val(data.split("__")[3]);
                $("#pzAddressLine2").val(data.split("__")[4]);
                $("#pzTown").val(data.split("__")[5]);
                $("#pzCounty").val(data.split("__")[6]);
                $("#pzPostcode").val(data.split("__")[7]);

                // Load the overlay
                $("#addaccount").data("overlay").load();
            });
    });


    // Open class overlay
    $('#addclass').live('click', function () {

        $("#ClassName").val("");
        $("#sParent").val("0");
        $("#classId").val("0");
        $('#sParent').removeAttr('disabled')

        $.get("/Admin/SubmitTo/LoadClassesForDropdown.aspx",
            function (data) {
                $("#sParent").replaceWith(data);
                $("#addclassoverlay").data("overlay").load();
            });
    });

    // save class
    $('#aSaveClass').live('click', function () {

        if ($("#ClassName").val().length == 0) { // Missing username

            $("#ClassName").focus();
            $("#addclassoverlay").find(".errorwrap").text("Please enter a name for the class");
            $("#addclassoverlay").find(".errorwrap").show();

        } else {

            var classId = $("#classId").val();
            var parentId = $('#sParent').val();
            var name = $("#ClassName").val();

            $.get("/Admin/SubmitTo/SaveClass.aspx", { iClassId: classId, sName: name, iParentId: parentId },
            function (data) {

                if (data.split("_")[0] > 0) { // class added ok

                    $("#addclassoverlay").data("overlay").close();

                    window.location = "/Admin/Classes.aspx"

                } else { // duplicate class mame / output message

                    $("#addclassoverlay").find(".errorwrap").text(data.split("_")[1]);
                    $("#addclassoverlay").find(".errorwrap").show();

                }

            });

        }
    });


    // Open delete class overlay
    $('#aDeleteClass').live('click', function () {

        var classId = $("#id").val();

        $.get("/Admin/SubmitTo/DeleteClass.aspx", { iClassId: classId },
            function (data) {

                $("#deleteoverlay").data("overlay").close();

                window.location = "/Admin/Classes.aspx"

            });
    });

    // Opens the edit class account overlay
    $('.edit.class').live('click', function () {

        var id = $(this).closest("tr").attr("id");
        $("#classId").val(id);

        $.get("/Admin/SubmitTo/LoadClass.aspx", { iClassId: id },
            function (data) {

                var parentId = $.trim(data.split("__")[1]);

                $("#ClassName").val(data.split("__")[0]);
                $("#sParent").val(parentId);

                $("#sParent").attr("disabled", "disabled");

                $("#addclassoverlay").data("overlay").load();

            });
    });


    // Opens Add Teacher overlay
    $('#addteacher').live('click', function () {

        $("#teacherId").val("0");
        $("#title").val("");
        $("#firstName").val("");
        $("#lastName").val("");
        $("#addteacheroverlay").find(".errorwrap").hide();

        $("#addteacheroverlay").data("overlay").load();

    });

    // Save Teacher
    $('#aSaveTeacher').live('click', function () {

        if ($("#title").val().length == 0) { // Missing username

            $("#title").focus();
            $("#addteacheroverlay").find(".errorwrap").text("Please enter a title for the teacher");
            $("#addteacheroverlay").find(".errorwrap").show();

        } else if ($("#firstName").val().length == 0) { // Missing username

            $("#firstName").focus();
            $("#addteacheroverlay").find(".errorwrap").text("Please enter a first name for the teacher");
            $("#addteacheroverlay").find(".errorwrap").show();

        } else if ($("#lastName").val().length == 0) { // Missing username

            $("#lastName").focus();
            $("#addteacheroverlay").find(".errorwrap").text("Please enter a last name for the teacher");
            $("#addteacheroverlay").find(".errorwrap").show();

        } else {

            var teacherId = $("#teacherId").val();
            var title = $("#title").val();
            var firstName = $("#firstName").val();
            var lastName = $("#lastName").val();
            var staffType = $("#sType").val();

            $.get("/Admin/SubmitTo/SaveTeacher.aspx", { iTeacherId: teacherId, sTitle: title, sFirstname: firstName, sLastname: lastName, iStaffTypeId: staffType },
            function (data) {

                $("#addteacheroverlay").data("overlay").close();

                window.location = "/Admin/SchoolStaff.aspx"

            });
        }

    });

    // Opens the edit teacher account overlay
    $('.edit.teacher').live('click', function () {

        var id = $(this).closest("tr").attr("id");
        $("#teacherId").val(id);

        $.get("/Admin/SubmitTo/LoadTeacher.aspx", { teacherId: id },
            function (data) {
                $("#title").val(data.split("__")[0]);
                $("#firstName").val(data.split("__")[1]);
                $("#lastName").val(data.split("__")[2]);
                $("#sType").val(data.split("__")[3]);

                // Load the overlay
                $("#addteacheroverlay").data("overlay").load();
            });

    });

    // Deletes a teacher
    $('#aDeleteTeacher').live('click', function () {
        var id = $("#id").val();

        $.get("/Admin/SubmitTo/DeleteTeacher.aspx", { teacherId: id },
            function (data) {

                window.location = "/Admin/SchoolStaff.aspx"
            });

    });

    // Opens Add Teacher overlay
    $('#addClassTeacher').live('click', function () {

        $(".messagewrap").hide();

        var classId = $("#classId").val();

        $.get("/Admin/SubmitTo/DeleteClassTeacher.aspx", { iClassId: classId },
            function (data) {

                $("#anotherselect option").each(function (index) {

                    var staffId = $(this).val();

                    $.get("/Admin/SubmitTo/SaveClassTeacher.aspx", { iClassId: classId, iStaffId: staffId });

                });

                $(".messagewrap").slideDown();

            });
    });


    // Opens add child overlay
    $('#addchild').live('click', function () {

        $("#addchildoverlay").find(".errorwrap").hide();
        $("#childId").val("0");
        $("#firstName").val("");
        $("#lastName").val("");
        $("#defaultEntry").val("");

        // Load the overlay
        $("#addchildoverlay").data("overlay").load();
    });

    // Saves a childs details
    $('#aSaveChild').live('click', function () {

        if ($("#firstName").val().length == 0) { // Missing username

            $("#firstName").focus();
            $("#addchildoverlay").find(".errorwrap").text("Please enter the childs first name");
            $("#addchildoverlay").find(".errorwrap").show();

        } else if ($("#lastName").val().length == 0) { // Missing username

            $("#lastName").focus();
            $("#addchildoverlay").find(".errorwrap").text("Please enter the childs last name");
            $("#addchildoverlay").find(".errorwrap").show();

        } else if ($("#defaultEntry").val().length == 0) { // Missing username

            $("#defaultEntry").focus();
            $("#addchildoverlay").find(".errorwrap").text("Please enter the childs date of birth");
            $("#addchildoverlay").find(".errorwrap").show();

        } else {

            var id = $("#childId").val();
            var fname = $("#firstName").val();
            var lname = $("#lastName").val();
            var dob = $("#defaultEntry").val();
            var classId = $("#sClass").val();

            $.get("/Admin/SubmitTo/SaveChild.aspx", { childId: id, firstname: fname, lastname: lname, dateofbirth: dob, cid: classId },
            function (data) {

                // Close the overlay
                $("#addchildoverlay").data("overlay").close();

                window.location = "/Admin/Children.aspx"

                //                var dataarray = new Array();
                //                oSettings = oTable.fnSettings();

                //                dataarray[0] = $.trim(data.split("__")[1]);
                //                dataarray[1] = $.trim(data.split("__")[2]);
                //                dataarray[2] = $.trim(data.split("__")[3]);
                //                dataarray[3] = $.trim(data.split("__")[4]);
                //                dataarray[4] = $.trim(data.split("__")[5]);

                //                if ($("#" + data.split("__")[0]).length == 0) { // add new child to table

                //                    oTable.fnAddData(dataarray);

                //                    // Add the account id to the new row
                //                    var tr = oTable.fnSettings().aoData[oTable.fnSettings().aoData.length - 1].nTr;
                //                    tr.setAttribute('id', data.split("__")[0]);

                //                    // Add name class to first table cell
                //                    var str = tr.innerHTML.slice(23, tr.innerHTML.length);
                //                    tr.innerHTML = "<td class='child sorting_1'>" + str;

                //                    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
                //                    oTable.fnDraw();

                //                } else { // update existing child

                //                    var aPos;

                //                    // Find index of selected row
                //                    $('.admintable tr').each(function (index) {

                //                        if ($(this).attr("id") == data.split("__")[0]) {
                //                            aPos = oTable.fnGetPosition(this);
                //                            return false;
                //                        }
                //                    });

                //                    oTable.fnUpdate(dataarray, aPos, 0);
                //                }

            });
        }

    });

    // Opens the edit child  overlay
    $('.edit.child').live('click', function () {

        var id = $(this).closest("tr").attr("id");
        $("#childId").val(id);

        $("#addchildoverlay").find(".errorwrap").hide();
        $("#firstName").val("");
        $("#lastName").val("");
        $("#defaultEntry").val("");

        $.get("/Admin/SubmitTo/LoadChild.aspx", { childId: id },
            function (data) {
                $("#firstName").val(data.split("__")[0]);
                $("#lastName").val(data.split("__")[1]);
                $("#sClass").val(data.split("__")[2]);
                $("#defaultEntry").val(data.split("__")[3].substring(0, 10));

                // Load the overlay
                $("#addchildoverlay").data("overlay").load();
            });

    });

    // Deletes a child
    $('#aDeleteChild').live('click', function () {
        var id = $("#id").val();

        $.get("/Admin/SubmitTo/DeleteChild.aspx", { childId: id },
            function (data) {

                // Close the overlay
                $("#deleteoverlay").data("overlay").close();

                window.location = "/Admin/Children.aspx"

            });

    });


    // Adds a child to an account
    $('.add').live('click', function () {

        var childId = $("#childId").val();
        var accId = $(this).closest("tr").attr("id");

        $.get("/Admin/SubmitTo/ToggleChildAccount.aspx", { iChildId: childId, iAccountId: accId, iAction: 1 },
            function (data) {

                var aPos;

                // Find index of selected row
                $('.admintable tr').each(function (index) {

                    if ($(this).attr("id") == accId) {
                        aPos = oTable.fnGetPosition(this);
                        return false;
                    }
                });
                oTable.fnUpdate(data, aPos, 1);
            });

    });

    // Removes a child to an account
    $('.deletechildacc').live('click', function () {

        var childId = $("#childId").val();
        var accId = $(this).closest("tr").attr("id");

        $.get("/Admin/SubmitTo/ToggleChildAccount.aspx", { iChildId: childId, iAccountId: accId, iAction: 0 },
            function (data) {

                var aPos;

                // Find index of selected row
                $('.admintable tr').each(function (index) {

                    if ($(this).attr("id") == accId) {
                        aPos = oTable.fnGetPosition(this);
                        return false;
                    }
                });
                oTable.fnUpdate(data, aPos, 1);

            });

    });


    // Adds a teacher to a class
    $('.addteachertoclass').live('click', function () {

        var classId = $("#classId").val();
        var teacherId = $(this).closest("tr").attr("id");

        $.get("/Admin/SubmitTo/ToggleClassTeacher.aspx", { iClassId: classId, iTeacherId: teacherId, iAction: 1 },
        function (data) {

            var aPos;

            // Find index of selected row
            $('.admintable tr').each(function (index) {

                if ($(this).attr("id") == teacherId) {
                    aPos = oTable.fnGetPosition(this);
                    return false;
                }
            });
            oTable.fnUpdate(data, aPos, 1);
        });

    });

    // Removes a teacher from to a class
    $('.removeteacherfromclass').live('click', function () {

        var classId = $("#classId").val();
        var teacherId = $(this).closest("tr").attr("id");

        $.get("/Admin/SubmitTo/ToggleClassTeacher.aspx", { iClassId: classId, iTeacherId: teacherId, iAction: 0 },
        function (data) {

            var aPos;

            // Find index of selected row
            $('.admintable tr').each(function (index) {

                if ($(this).attr("id") == teacherId) {
                    aPos = oTable.fnGetPosition(this);
                    return false;
                }
            });
            oTable.fnUpdate(data, aPos, 1);
        });

    });

    // Events
    $('#btnNext').live('click', function () {

        setSessionTimeout();

        //var teaser = ($('.uEditorIframe').contents().find('body').html());
        //var teaser = $("#sTeaser").val();
        //teaser = $.trim(teaser)

        //alert(teaser);

        //Validate fields
        if ($("#sTitle").val().length == 0) { // Missing title

            $("#sTitle").focus();
            $(".errorwrap").text("Please enter a title for the event");
            $(".errorwrap").show();

        } else if ($("#sTeaser").val().length == 0) { // Missing teaser

            $("#sTeaser").focus();
            $(".errorwrap").text("Please enter a teaser for the event");
            $(".errorwrap").show();

        } else if ($("#sDateOfEvent").val().length == 0) { // Missing date

            $("#sDateOfEvent").focus();
            $(".errorwrap").text("Please enter a date for the event");
            $(".errorwrap").show();

        } else {

            $(".errorwrap").text("");
            $(".errorwrap").hide();

            $("#eventstab1").hide();
            $("#eventstab2").show();

        }

    });

    $('#btnBack1').live('click', function () {

        setSessionTimeout();

        $(".errorwrap").text("");
        $(".errorwrap").hide();

        $("#eventstab2").hide();
        $("#eventstab1").show();

    });



    $('#btnNext2').live('click', function () {

        setSessionTimeout();

        //var eventinfo = ($('#eventstab2 .uEditorIframe').contents().find('body').html());
        //var eventinfo = $("#sMainInfo").val();
        //alert(eventinfo);
        //eventinfo = $.trim(eventinfo)

        //Validate fields
        //if ($("#sMainInfo").val().length == 0) { // Missing event info

		//$(".errorwrap").text("Please enter the event information");
		//$(".errorwrap").show();

        //} else {

            $(".errorwrap").text("");
            $(".errorwrap").hide();

            $("#eventstab2").hide();
            $("#eventstab3").show();
        //}
    });

    $('#btnBack2').live('click', function () {

        setSessionTimeout();

        $(".errorwrap").text("");
        $(".errorwrap").hide();

        $("#eventstab3").hide();
        $("#eventstab2").show();
    });

    $('.addeventclass').live('click', function () {

        $(this).closest("tr").addClass("selected");
        $(this).closest("td").html("<a href='#' class='deleteeventclass'>remove event from this class</a>");

    });

    $('.deleteeventclass').live('click', function () {

        $(this).closest("tr").removeClass("selected");
        $(this).closest("td").html("<a href='#' class='addeventclass'>link event to this class</a>");

    });

    $(".addallclasses").live('click', function () {

        var link;
        var add = true;

        if ($(".addallclasses").val() == "Select all") {

            $(".addallclasses").val("Clear all");
            link = "<a href='#' class='deleteeventclass'>remove event from this class</a>";

        } else {

            $(".addallclasses").val("Select all");
            link = "<a href='#' class='addeventclass'>link event to this class</a>";
            add = false;
        }

        $(".admintable.events.small").find('tr').each(function (index) {

            if (add) {
                $(this).addClass("selected");
            } else {
                $(this).removeClass("selected");
            }
            $(this).find("td:last").html(link);

        });

    });

    $("#btnSendForApproval").live('click', function () {

        $("#Approved").val("1");

        $("#btnSaveEvent").click();

    });

    $("#btnSaveAndEmail").live('click', function () {

        $("#sendEmail").val("1");

        $("#btnSaveEvent").click();

    });

    $("#btnSavePreview").live('click', function () {

        $("#preview").val("1");
        $("#Approved").val("1");

        $("#btnSaveEvent").click();

    });

    $("#btnSaveEvent").live('click', function () {

        setSessionTimeout();

        var eventId = $("#iEventId").val();
        var title = $("#sTitle").val();
        //var teaser = $('#eventstab1 .uEditorIframe').contents().find('body').html();
        var teaser = $("#sTeaser").val();
        var typeOfEvent = $("#sTypeOfEvent").val();
        var dateOfEvent = $("#sDateOfEvent").val();
        var usefulInfo = $("#sUsefulInfo").val();
        //var mainText = $('#eventstab2 .uEditorIframe').contents().find('body').html();
        var mainText = $('#sMainInfo').val();
        var approved = 1;
        //$('#sMainInfo').wysiwyg("setContent", decodeURIComponent(data.split("__")[5]));
        if ($("#Approved").val() == 1) { approved = 0; }

        $.post("/Admin/SubmitTo/SaveEvent.aspx",
            {
                iEventId: eventId,
                sTitle: title,
                sTeaser: encodeURIComponent(teaser),
                iTypeOfEvent: typeOfEvent,
                dDateOfEvent: dateOfEvent,
                bUsefulInfo: usefulInfo,
                sMainText: encodeURIComponent(mainText),
                bApproved: approved
            },
            function (data) {

                alert(data.split("|")[0])

                var dataarray = new Array();
                oSettings = oTable.fnSettings();

                data = data.split("|")[1]

                dataarray[0] = $.trim(data.split("__")[1]);
                dataarray[1] = $.trim(data.split("__")[2]);
                dataarray[2] = $.trim(data.split("__")[3]);
                dataarray[3] = $.trim(data.split("__")[4]);

                var eId = data.split("__")[0]; // event id

                // Delete current class associations
                $.get("/Admin/SubmitTo/DeleteEventClasses.aspx", { iEventId: eId },
                function (data) {

                    var cIds = '';

                    $(".admintable.events.small").find('tr').each(function (index) {

                        if ($(this).attr("class").indexOf("selected") >= 0) {

                            cIds = cIds + $(this).attr("id") + ","; // class id list

                        }

                    });

                    $.get("/Admin/SubmitTo/SaveEventClass.aspx", { iEventId: eId, sClassIds: cIds },
                    function (data) {

                        if ($("#preview").val() == 1) { // preview event

                            window.location = "/Admin/EventPreview.aspx?id=" + eId;

                        } else if ($("#Approved").val() == 1) { // Send email to approver

                            $.get("/Admin/SubmitTo/SendApproverEmail.aspx", { iEventId: eId },
                            function (data) {

                                alert(data);
                                window.location = "/Admin/Events.aspx"

                            });

                        } else if ($("#sendEmail").val() == 1) { // send emails to contacts

                            $.get("/Admin/SubmitTo/SendContactEmails.aspx", { iEventId: eId },
                            function (data) {

                                alert(data);
                                window.location = "/Admin/Events.aspx"

                            });

                        } else {

                            window.location = "/Admin/Events.aspx"

                        }

                    });

                });

            });

    });

    $(".deleteevent").live('click', function () {

        $("#deleteeventoverlay").data("overlay").load();

        var eventId = $(this).parent().parent().attr("id");
        $("#eventid").val(eventId);
    });

    $("#DeleteEvent").live('click', function () {

        var eventId = $("#eventid").val();

        $("#deleteeventoverlay").data("overlay").close();

        // Delete the event here
        $.get("/Admin/SubmitTo/DeleteEvent.aspx", { id: eventId },
            function (data) {

                window.location = "/Admin/Events.aspx"

            });
    });


    $("#add-new-event").live('click', function () {

        // Reset form values
        $("#sTitle").val("");
        //$('#eventstab1 .uEditorIframe').contents().find('body').html("");
        $("#sTypeOfEvent").val("1");
        $("#sDateOfEvent").val("");
        $("#sUsefulInfo").val("0");
        //$("#eventstab2 .uEditorIframe").contents().find('body').html("");
        //$("#eventstab1 h3").text("Add a new event > Step 1");
        //$("#eventstab2 h3").text("Add a new event > Step 2");
        //$("#eventstab3 h3").text("Add a new event > Step 3");

        // Loop through class table and reset
        $(".admintable.events.small").find('tr').each(function (index) {

            $(this).removeClass("selected");
            $(this).find(".deleteeventclass").text("link event to this class");
            $(this).find(".deleteeventclass").toggleClass("addeventclass");

        });

        $("#eventstable").hide();
        $("#eventstab1").show();
        $("#eventstab2").hide();
        $("#eventstab3").hide();
        $(".content.events").show();

    });

    $(".edit.event").live('click', function () {

        //$("#eventstab1 h3").text("Edit an event > Step 1");
        //$("#eventstab2 h3").text("Edit an event > Step 2");
        //$("#eventstab3 h3").text("Edit an event > Step 3");

        var eventId = $(this).parent().parent().attr("id");
        $("#iEventId").val(eventId);

        $.get("/Admin/SubmitTo/LoadEvent.aspx", { id: eventId },
            function (data) {

                $("#sTitle").val(data.split("__")[0]);
                //$('#eventstab1 .uEditorIframe').contents().find('body').html(decodeURIComponent(data.split("__")[1]));
                $("#sTeaser").val(decodeURIComponent(data.split("__")[1]));

                $("#sTypeOfEvent").val(data.split("__")[2]);
                $("#sDateOfEvent").val(data.split("__")[3]);

                if (data.split("__")[4] == "True") {

                    $("#sUsefulInfo").val("1");

                } else {

                    $("#sUsefulInfo").val("0");
                }

                //$('#eventstab2 .uEditorIframe').contents().find('body').html(decodeURIComponent(data.split("__")[5]));
                // myEditor.setEditorHTML(decodeURIComponent(data.split("__")[5])); ;
                $('#sMainInfo').wysiwyg("setContent", decodeURIComponent(data.split("__")[5]));

                var classArray = data.split("__")[6].split(",");

                for (i = 0; i <= classArray.length - 1; i++) {

                    $(".admintable.events.small").find('tr').each(function (index) {

                        if ($(this).attr("id") == classArray[i]) {

                            $(this).addClass("selected");

                            var obj = $(this).find(".addeventclass");
                            $(obj).text("remove event from this class");
                            $(obj).removeClass("addeventclass");
                            $(obj).addClass("deleteeventclass");
                        }
                    });
                }

                $("#eventstable").hide();
                $(".content.events").show();

            });

    });

    // Opens the announcement overlay from Announcements page
    $('#add-announcement').live('click', function () {
        $("#annId").val("0");
        $("#sTitle").val("");
        $("#word_count").val("");
        $("#cbActive").attr('checked', false);

        $("#addannouncement").data("overlay").load();
    });

    $('#aSaveAnnouncement').live('click', function () {
        if ($("#sTitle").val().length == 0) {

            $("#sTitle").focus();
            $(".errorwrap").text("Please enter a title for the announcement");
            $(".errorwrap").show();

        } else if ($("#word_count").val().length == 0) {

            $("#word_count").focus();
            $(".errorwrap").text("Please enter the announcement");
            $(".errorwrap").show();

        } else {

            annId = $("#annId").val();
            title = $("#sTitle").val();
            ann = $("#word_count").val();
            active = $("#cbActive").is(':checked');

            $.get("/Admin/SubmitTo/SaveAnnouncement.aspx", { iAnnId: annId, sTitle: title, sAnnouncement: ann, bActive: active },
            function (data) {

                window.location = "/Admin/announcements.aspx"

            });

            $("#addannouncement").data("overlay").close();
        }
    });

    // Opens the edit announcement overlay
    $('.edit.announcement').live('click', function () {

        var annId = $(this).parent().parent().attr("id");
        $("#annId").val(annId);

        $.get("/Admin/SubmitTo/LoadAnnouncement.aspx",
            {
                iAnnId: annId
            },
            function (data) {

                $("#sTitle").val(data.split("__")[0]);
                $("#word_count").val(data.split("__")[1]);

                if ($.trim(data.split("__")[3]).length == 4) {
                    $("#cbActive").attr('checked', true);
                } else {
                    $("#cbActive").attr('checked', false);
                }
            });

        $("#addannouncement").data("overlay").load();

    });

    // Opens the delete announcement overlay
    $('.delete.announcement').live('click', function () {

        $("#aDeleteAnnouncement").data("overlay").load();

    });

    // Opens the delete announcement overlay
    $('#aDeleteAnnouncement').live('click', function () {

        var annId = $("#id").val();

        $.get("/Admin/SubmitTo/DeleteAnnouncement.aspx",
            {
                iAnnId: annId
            },
            function (data) {

                window.location = "/Admin/announcements.aspx"

            });

        $("#deleteoverlay").data("overlay").close();
    });

    $("#add-useful-info").live('click', function () {
        $("#infoTitle").val("");
        $("#infoFile").val("")
        $("#info-overlay").data("overlay").load();
    });

    $("#aSaveUsefulInfo").live('click', function () {

        if ($("#infoTitle").val().length == 0) {

            $("#infoTitle").focus();
            $(".errorwrap").text("Please enter a title for the information");
            $(".errorwrap").show();

        } else if ($("#infoFile").val().length == 0) {

            $(".errorwrap").text("Please select a file");
            $(".errorwrap").show();

        } else {

            $('#frmInfo').submit();

        }
    });

    $("#aDeleteUsefulInfo").live('click', function () {

        var itemId = $(this).parent().parent().attr("id").split("_")[1];
        $("#infoid").val(itemId);

        $("#deleteinfooverlay").data("overlay").load();

        //        
    });

    $("#DeleteInfo").live('click', function () {

        var itemId = $("#infoid").val();

        $.get("/Admin/SubmitTo/DeleteUsefulInfo.aspx",
        {
            iId: itemId
        },
        function (data) {

            window.location = "/Admin/UsefulInfo.aspx"

        });

    });


    /*== Move overlay html to body ==*/
    $('.overlay').each(function () {
        var divId = $(this).attr('id');
        $('body').append("<div id='" + divId + "' class='overlay' style='display:none;'>" + $(this).html() + "</div>");
        $(this).remove();
    });
});

function AuthenticateLogin(un, pw, rem) {
    $.get("/SubmitTo/AuthenticateLogin.aspx", { username: un, password: pw, remember: rem },
        function (data) {
            
            if (data == 1) {

                $('#frmLogin').submit();

            } else if (data == -1) {

                $(".errorwrap.popup").text("");
                $(".errorwrap.popup").hide();

                $("#overlay").data("overlay").load();

            } else if (data == 2) {

                $("#termsoverlay").data("overlay").load();

            } else {

                $(".errorwrap").text("Invalid username / password");
                $(".errorwrap").show();

            }
        });

}


$("#addtocalendar").live('click', function () {
    //get all rows and then loop through them
    var aTrs = oTable.fnGetFilteredNodes();
    var anchor;
    var href;
    var idList = '';

    // loop through table rows and gather all event ids
    for (var i = 0; i < aTrs.length; i++) {
        //$(aTrs[i]).find("td:first").addClass("date");

        anchor = $(aTrs[i]).find("a:first");

        href = $(anchor).attr("href");

        idList += href.split("=")[1] + "_";
    }

    $("#sIdList").val(idList);

    $('#frmAddToCalendar').submit();
});

/* Timeout feature for events page */
var timeout = 0;

function setSessionTimeout() {
    if (timeout != 0) {
        clearInterval(timeout);
    }
    timeout = setInterval("EndSession()", 1740000);
}

function EndSession() {
    window.location = "/Admin/Logout.aspx"
}


//function SaveEventInfo(html) {
//    
//    setSessionTimeout();
//    alert(html);
//    var eventId = $("#iEventId").val();
//    var title = $("#sTitle").val();
//    //var teaser = $('#eventstab1 .uEditorIframe').contents().find('body').html();
//    var teaser = $("#sTeaser").val();
//    var typeOfEvent = $("#sTypeOfEvent").val();
//    var dateOfEvent = $("#sDateOfEvent").val();
//    var usefulInfo = $("#sUsefulInfo").val();
//    //var mainText = $('#eventstab2 .uEditorIframe').contents().find('body').html();
//    //var mainText = encodeURIComponent(html);
//    //var mainText = $("#sMainInfo").val();
//    var approved = 1;
//    
//    if ($("#Approved").val() == 1) { approved = 0; }
//   
//    $.post("/Admin/SubmitTo/SaveEvent.aspx",
//        {
//            iEventId: eventId,
//            sTitle: title,
//            sTeaser: teaser,
//            iTypeOfEvent: typeOfEvent,
//            dDateOfEvent: dateOfEvent,
//            bUsefulInfo: usefulInfo,
//            sMainText: html,
//            bApproved: approved
//        },
//        function (data) {
//                    
//            alert(data.split("|")[0])

//            var dataarray = new Array();
//            oSettings = oTable.fnSettings();

//            data = data.split("|")[1]

//            dataarray[0] = $.trim(data.split("__")[1]);
//            dataarray[1] = $.trim(data.split("__")[2]);
//            dataarray[2] = $.trim(data.split("__")[3]);
//            dataarray[3] = $.trim(data.split("__")[4]);

//            var eId = data.split("__")[0]; // event id

//            // Delete current class associations
//            $.get("/Admin/SubmitTo/DeleteEventClasses.aspx", { iEventId: eId },
//            function (data) {

//                var cIds = '';

//                $(".admintable.events.small").find('tr').each(function (index) {

//                    if ($(this).attr("class").indexOf("selected") >= 0) {

//                        cIds = cIds + $(this).attr("id") + ","; // class id list

//                    }

//                });

//                $.get("/Admin/SubmitTo/SaveEventClass.aspx", { iEventId: eId, sClassIds: cIds },
//                function (data) {

//                    if ($("#preview").val() == 1) { // preview event

//                        window.location = "/Admin/EventPreview.aspx?id=" + eId;

//                    } else if ($("#Approved").val() == 1) { // Send email to approver

//                        $.get("/Admin/SubmitTo/SendApproverEmail.aspx", { iEventId: eId },
//                        function (data) {

//                            alert(data);
//                            window.location = "/Admin/Events.aspx"

//                        });

//                    } else if ($("#sendEmail").val() == 1) { // send emails to contacts

//                        $.get("/Admin/SubmitTo/SendContactEmails.aspx", { iEventId: eId },
//                        function (data) {

//                            alert(data);
//                            window.location = "/Admin/Events.aspx"

//                        });

//                    } else {

//                        window.location = "/Admin/Events.aspx"

//                    }

//                });

//            });

//        });

//}

