﻿
$(function () {

    //For retrieving schools from the school search box
    $("#SchoolSearchField").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "GET",
                url: "Ajax.ashx",
                dataType: "json",
                data: {
                    action: "getschools",
                    name: $("#SchoolSearchField").val(),
                    sessionid: MySessionId
                },
                success: function (data) {

                    if (data.resulttype == "nodata") {
                        ShowQtip("SchoolSearchField", "Well isn't that something...your school wasn't found. However, you can register the school you're looking for and have it added to the list. <a href='RegisterSchool.aspx'>Come on...do it!</a>", "topLeft", "middleRight", "rightTop", "", "keydown");
                        //This will trigger the qtip...
                        $("#SchoolSearchField").focus();

                        //Load results
                        response($.map(data.results, function (item) {
                            return {
                                id: "",
                                value: item.Name
                            }
                        }));
                    }
                    else {
                        //Load results
                        response($.map(data.results, function (item) {
                            return {
                                id: item.GUID,
                                value: item.Name + ", " + item.City + ", " + item.State
                            }
                        }));
                    }
                }
            });
        },
        minLength: 3,
        select: function (event, ui) {
            if (ui.item.id != "") { location.href = "School.aspx?school=" + ui.item.id; }
        },
        open: function () {
            $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
        },
        close: function () {
            $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
        }
    });
});

//For retrieving a user from the database for login purposes
function Login() {
    var ret = "";

    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        async: false, //NECESSARY FOR THIS CALL
        data: {
            action: "getuser",
            name: $("#username").val(),
            password: $("#userpassword").val(),
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "error") {
                ($.map(data.results, function (item) {
                    ret = item.Description;
                }));
            }
            else {
                $.each(data.results, function () {
                    if (this["Guid"].toString().length > 0) {
                        //Refresh the page
                        location.href = "Default.aspx?action=loggedin";
                    }
                });
            }
        },
        failure: function () {
            ret = "Critical Error Attempting Log In";
        }
    });

    return ret;
}

function GetMembers(pAccordion, pSchoolID, pClassOf) {
    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        data: {
            action: "getmembers",
            school: pSchoolID,
            classof: pClassOf,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "error") {
                data.results.each(function (index, val) {
                    alert(val.Description);
                });
            }
            else {
                //var iLoaded = 0;
                $.each(data.results, function () {
                    //Create an h3 for the accordion
                    var h3 = $("<h3 />");

                    //Construct the member name
                    var mName = this.Member.Name.First;
                    if (this.Member.Name.Middle.length > 0) { mName += " " + this.Member.Name.Middle.toString(); }
                    mName += " " + this.Member.Name.Last.toString();

                    if (this.Member.Name.Alias.length > 0) { mName += " (" + this.Member.Name.Alias + ")"; }

                    //Now add the name to the h3
                    h3.append($("<span />").html(mName).addClass("accordionheader"));

                    $("#" + pAccordion).append(h3);

                    //Now add the detail div under the h3
                    var div = $("<div />").css("padding-left", "18px");

                    var hs = $("<span />").attr("id", "m" + this.Member.ID.toString()).css("display", "none").html("memberId=" + this.Member.ID.toString() + ";" + "name=" + mName);
                    div.append(hs);

                    var ul = $("<ul />").addClass("details").addClass("first");
                    ul.append($("<li />")
                        .append($("<label />").html("Member Since:"))
                        .append($("<span />").html(FormatDate(this.Member.AddDate))));

                    ul.append($("<li />")
                        .append($("<label />").html("Birthdate:"))
                        .append($("<span />").html(FormatDate(this.Member.Birthdate))));

                    if (this.Member.Location.length > 0) {
                        ul.append($("<li />")
                        .append($("<label />").html("Location:"))
                        .append($("<span />").html(this.Member.Location)));
                    }

                    if (this.Member.Occupation.length > 0) {
                        ul.append($("<li />")
                        .append($("<label />").html("Occupation:"))
                        .append($("<span />").html(this.Member.Occupation)));
                    }

                    div.append(ul);

                    ul = $("<ul />").addClass("details").addClass("two");

                    var pic;
                    if (this.Member.ProfilePicturePath.length > 0) {
                        pic = $("<img />").attr("src", this.Member.ProfilePicturePath);
                    }
                    else {
                        pic = $("<img />").attr("src", "images/noprofile.png");
                    }

                    pic.attr("width", "200");
                    pic.attr("style", "padding: 3px;border: 1px groove gainsboro;");
                    pic.attr("alt", "Picture of " + this.Member.Name.First);

                    ul.append($("<li />").append(pic));

                    var mli = $("<li />");
                    var msgLink = ($("<a />").html("Send " + this.Member.Name.First + " a Message").attr("mid", this.Member.ID.toString()).attr("mname", mName).attr("href", "#").click(function (evt) {
                        evt.stopPropagation;
                        evt.preventDefault();

                        $("#msgto").attr("mid", parseInt($(this).attr("mid")));
                        $("#msgto").html($(this).attr("mname"));

                        $("#messagesender").dialog(
                        {
                            width: 650,
                            resizable: false,
                            modal: true,
                            buttons: [{ text: "Send", click: function () { return SendMessage(); } }],
                            open: function (evt, ui) {
                                evt.stopPropagation;
                                evt.preventDefault();

                                //alert("Before");
                                CKEDITOR.replace("messagebody", { skin: 'v2' });
                            },
                            close: function () {
                                if (CKEDITOR.instances.messagebody) { CKEDITOR.instances.messagebody.destroy(); }
                            }
                        });


                    }));
                    mli.append(msgLink);
                    ul.append(mli);

                    ul.append(msgLink);
                    div.append(ul);

                    if (this.Member.Biography.length > 0) {
                        $("<p />").html("More About " + this.Member.Name.First + "...<br /><blockquote><i>" + this.Member.Biography + "</i></blockquote>").appendTo(div);
                    }

                    $("#" + pAccordion).append(div);

                    //iLoaded++;
                    //var progress = (iLoaded / data.results.length) * 100;
                    //$("#" + pProgressBar).progressbar("option", "value", progress);
                });

                try { $("#" + pAccordion).accordion("destroy"); } catch (e) { }
                $("#" + pAccordion).accordion({ autoHeight: false });
            }
        }
    });

}

function GetAddressCoordinates(pAddress1, pAddress2, pCity, pState, pCountry) {

    var address = pAddress1.replace(" ", "+") + ",";

    if (pAddress2.length > 0)
    {
        address += pAddress2.replace(" ", "+") + ",";
    }

    address += pCity.replace(" ", "+") + ",";

    if (pState.length > 0)
    {
        address += pState.replace(" ", "+");
    }

    if (pCountry.length > 0)
    {
        address += pCountry.replace(" ", "+");
    }

    var url = location.protocol + "//maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=true&output=json&callback=?";

    $.ajax({
        type: "GET",
        url: url,
        success: function (data) {
            alert(data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Ajax Error: " + xhr.status + "\nMsg: " + xhr.responseText);
        }
    });

}

function UpdateHomePage() {
    var hpText = editor.getData();
    hpText = hpText.replace(/</g, "~lb~").replace(/>/g, "~rb~");

    $.ajax({
        type: "POST",
        url: "Ajax.ashx",
        dataType: "json",
        data: {
            action: "updatehomepage",
            school: SchoolId,
            text: hpText,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "error") {
                data.results.each(function (index, val) {
                    alert(val.Description);
                });
            }
            else {
                $.each(data.results, function () {
                    //if (this["Guid"].toString().length > 0) {
                        //Refresh the page
                        //location.href = "Default.aspx?action=loggedin";
                    //}
                });
            }
        }
    });
}

function RequestMembership(pSchoolID, pClassOf, pIsDefault, pRoles) {
    var ret = "";

    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        async: false,
        data: {
            action: "becomemember",
            school: pSchoolID,
            classof: pClassOf,
            isdefault: pIsDefault,
            roles: pRoles,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "error") {
                data.results.each(function (index, val) {
                    ret = val.Description;
                });
            }
            else {
                //var iLoaded = 0;
                $.each(data.results, function () { });
            }
        },
        failure: function () {
            ret = "Critical Problem Obtaining Membership. Please Try Later!";
        }
    });

    return ret;
}

function ValidateEmail(pEmail) {

    var ret = true;

    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        async: false, //NECESSARY FOR THIS CALL
        data: {
            action: "validateemailformat",
            email: pEmail,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "invalid") {
                ret = false;
            }
            else {
                ret = true;
            }
        },
        failure: function () {
            ret = false;
        }
    });

    return ret;
}

function ValidateUserName(pUserName) {
    var ret = "";

    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        async: false, //NECESSARY FOR THIS CALL
        data: {
            action: "validateusername",
            username: pUserName,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "invalid") {
                ($.map(data.results, function (item) {
                    ret += item.Description;
                }));
            }
            else {
                ret = "";
            }
        },
        failure: function () {
            ret = "Problem Determining Uniqueness...";
        }
    });

    return ret;
}

function Unsubscribe(pUserId, doClassmates, doMessages, doComments, doOthers) {
    var ret = "";
    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        async: false, //NECESSARY FOR THIS CALL
        data: {
            action: "unsubscribe",
            userid: pUserId,
            doclassmates: doClassmates,
            domessages: doMessages,
            docomments: doComments,
            doothers: doOthers,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "error") {
                ($.map(data.results, function (item) {
                    ret += item.Description;
                }));
            }
            else {
                ret = "Your email notification changes will take effect immediately!";
            }
        },
        failure: function () {
            ret = "Your request to unsubscribe from emails failed! Please try again later. If the problem persists please <a href='ContactUs.aspx?subject=Unsubscribe&nbsp;Problem'>contact us</a>.";
        }
    });

    return ret;
}

function RemoveSchool(pSchoolXrefId) {
    var ret = "School removal failed! Please try again later.";

    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        async: false, //NECESSARY FOR THIS CALL
        data: {
            action: "removeschool",
            xrefid: pSchoolXrefId,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "error") {
                ret = "";
                ($.map(data.results, function (item) {
                    ret += item.Description;
                }));
            }
            else {
                ret = ""; //Success
            }
        },
        failure: function () {
            ret = "School removal failed! Please try again later.";
        }
    });

    return ret;
}

function SetDefaultSchool(pSchoolXrefId, pIsDefault) {
    $.ajax({
        type: "GET",
        url: "Ajax.ashx",
        dataType: "json",
        data: {
            action: "setschoolasdefault",
            xrefid: pSchoolXrefId,
            isdefault: pIsDefault,
            sessionid: MySessionId
        },
        success: function (data) {
            if (data.resulttype == "error") {
                var ret = "";
                ($.map(data.results, function (item) {
                    ret += item.Description;
                }));
                alert(ret);
            }
            else {
                $("#savingdata").fadeOut();
            }
        },
        failure: function () {
            alert("School default failed! Please try again later.");
        }
    });
}
