﻿var originalSchoolList;
var thisScreenName;
var addSchool = true;
var DEFAULT_AVATAR = "/_images/community/avatars/BTFE_avatar_01.jpg";

function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
        yScroll = self.pageYOffset;
        xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll, yScroll)
}

$(document).ready(function() {
    $('#community_navigation > ul > li').hover(
        function(e) {
            $(this).children('ul').show();
            $(this).children('a:first').css('background', '#514ea1');
            $(this).children('a:first').css('color', '#fff');
        },
        function(e) {
            $(this).children('ul').hide();
            if ($(this).attr('class') == "") {
                $(this).children('a:first').css('background', '#f0efea');
                $(this).children('a:first').css('color', '#79755a');
            }
        }
    );

    setupUserSummaryLinks();
    setupAdditionalSchools();
    setupSchoolUserList();

    // We want to cancel the event and do the school search
    $("input#zip").keypress(function(event) {
        if (event.keyCode == 13) {
            DoSchoolSearch();
            return false;
        } 
    });

});

function setupSchoolUserList() {
    if ($("#ActiveSchoolMembers").length < 1) return;

    $("a.active-school-users").click(LoadActiveSchoolUsers);
}

function LoadActiveSchoolUsers(e) {
    $("#ActiveSchoolMembers ul").html("");
    $("#ActiveSchoolMembers h4").html($(this).html());

    $.post("/_handlers/CommunityActiveUsers.ashx", { sid: $(this).attr("rel") }, InjectActiveUsers, "json");
    $('#ActiveSchoolMembers').jqm({ modal: true, title: "School Community Members" }).jqmShow();

    return false;
}

function InjectActiveUsers(SchoolActiveUsers) {
    if (SchoolActiveUsers.length < 1) {
        $("#ActiveSchoolMembers ul").html("<li><p>There are no active users for this school.</p></li>");
    }

    var listItems = "";
    for (var i = 0; i < SchoolActiveUsers.length; i++) {
        listItems += "<li>\n<div class='avatar-holder'>\n";
        if (SchoolActiveUsers[i].AvatarUrl == null || SchoolActiveUsers[i].AvatarUrl == "") {
            listItems += "<img src='" + DEFAULT_AVATAR + "' />\n";
        } else {
            listItems += "<img src=\"" + SchoolActiveUsers[i].AvatarUrl + "\" />\n";
        }
        for (var z = 0; z < SchoolActiveUsers[i].RoleNames.length; z++) {
            listItems += "<span class=\"user-flags\">" + SchoolActiveUsers[i].RoleNames[z] + "</span>\n";
        }
        listItems += "</div>\n<div>\n";
        listItems += "<h6><a href='#' class='user-summary'>" + SchoolActiveUsers[i].DisplayName + "</a></h6>\n";
        listItems += "<span>" + SchoolActiveUsers[i].NumberOfPosts + " posts</span>\n";
        listItems += "<p>" + SchoolActiveUsers[i].Biography + "</p>";
        listItems += "</div>\n"
        listItems += "</li>";
    }
    $("#ActiveSchoolMembers ul").html(listItems);
    $("#ActiveSchoolMembers h6 a.user-summary").click(function() {
        showUserSummaryFromSchoolUsersList($(this).html()); 
    });
}

function HandleSchoolSearchResponse(schoolList) {
    if (typeof (schoolList) == 'undefined') {
        alert("There was an error submitting your search.");
        return;
    }
    $("#SchoolsSubText").html("We found " + schoolList.length + " schools.");

    if (schoolList.length > 0) {
        $("#SchoolsSubText").html($("#SchoolsSubText").html() + " Please select one and continue.");
        $("#SchoolSearchByZip").hide();
        $("#SchoolSearchResults").show();
        for (var i = 0; i < schoolList.length; i++) {
            $("#SchoolSearchResults select").append("<option value='" + schoolList[i].id + "'>" + schoolList[i].name + " - " + schoolList[i].location + "</option>");
        }
    }
}

function DoSchoolSearch() {
    var zipRegEx = new RegExp(/^[0-9]{5}$/);
    if (!zipRegEx.test($('input#zip').attr('value'))) {
        alert("Please enter a valid zip code.");
        return false;
    }
    $("#AdditionalSchoolsHead").html("School results");
    $.post('/_handlers/CommunitySchoolSearch.ashx', { zip: $('input#zip').attr('value') }, HandleSchoolSearchResponse, 'json');

    return false;
}

function setupAdditionalSchools() {
    if ($("#AdditionalSchools").length < 1) return;
    
    // We're going to save the original schools in case they want to reset the form
    originalSchoolList = $("#AdditionalSchools ul").html();

    $("a.remSchool").click(removeSchool);
    $("a.not-listed").click(LoadSchoolNotListedPopup);
    $("#SchoolNotListed").jqm({ modal: true, trigger: 'a.not-listed', title: "ADDITIONAL SCHOOL FORUMS" })
    $("a.addSchoolButton").click(AddSelectedSchool);

    $("a.search-again").click(ResetSchoolSearchForm);
    $("a.cancelSchoolsButton").click(cancelAddRemoveSchools);
    $("#AdditionalSchools a.closeModal").click(cancelAddRemoveSchools);
    $("#SchoolSearch").click(DoSchoolSearch);

    // This handler need to be re-attached since it isn't recognized for newly added elements
    $("a.addRemSchools").click(function(e) {
        $('#AdditionalSchools').jqm({ modal: true, trigger: 'a.jqModal', title: "ADDITIONAL SCHOOL FORUMS" }).jqmShow();
        return false;
    });

}

function ShowCannotFindSchool() {
    $("a#close").click(function(e) {
        return false;
    });
}

function LoadSchoolNotListedPopup(e) {
    //$("#SchoolNotListed").load("/common/CantFindSchool.aspx", ShowCannotFindSchool);
    return false;
}

function AddSelectedSchool(e) {
    var selectedSchoolId = $("#schoolsToAdd").attr("value");
    var selectedSchoolName = $("#schoolsToAdd option:selected").html();
    var currentAddedSchools = $("input.schoolsAdded").attr("value");
    var currentRemovedSchools = $("input.schoolsRemoved").attr("value");
    var addedAsArray = currentAddedSchools.split(",");
    var removedAsArray = currentRemovedSchools.split(",");

    if (IsValueInArray(selectedSchoolId, removedAsArray)) {
        $("input.schoolsRemoved").attr("value", RemoveValueFromArray(selectedSchoolId, removedAsArray).join());
    }

    if (IsValueInArray(selectedSchoolId, addedAsArray)) {
        return false;
    }

    addSchool = true;
    $("#AdditionalSchools ul li").each(function(i, n) {
        if ($(n).children('span').children('a').attr("rel") == selectedSchoolId) {
            addSchool = false;
        }
    });

    if (!addSchool) return false;

    addedAsArray.push(selectedSchoolId);

    $("input.schoolsAdded").attr("value", addedAsArray.join());

    var itemStart = "<li";
    if ($("#AdditionalSchools ul li").length % 2 == 1) {
        itemStart += " class=\"alt\"";
    }

    $("#AdditionalSchools ul").append(itemStart + "><span><a href=\"#\" rel=\"" + selectedSchoolId + "\" class=\"remSchool\">remove</a></span> " + selectedSchoolName + "</li>");
    $("a.remSchool").click(removeSchool);
    return false;
}

function ResetSchoolSearchForm(e) {
    $("#AdditionalSchoolsHead").html("Find additional school forums");
    $("#SchoolsSubText").html("Find other school forums you wish to participate in.");
    $("#SchoolSearchByZip").show();
    $("#SchoolSearchResults").hide();
    return false;
}

function IsValueInArray(val, ar) {
    for (var i = 0; i < ar.length; i++) {
        if (ar[i] == val) {
            return true;
        }
    }
    return false;
}

function RemoveValueFromArray(val, ar) {
    for (var i = 0; i < ar.length; i++) {
        if (ar[i] == val) {
            ar.splice(i, 1);
        }
    }
    return ar;
}



function removeSchool() {
    var currentAddedSchools = $("input.schoolsAdded").attr("value");
    var currentRemovedSchools = $("input.schoolsRemoved").attr("value");
    var addedAsArray = currentAddedSchools.split(",");
    var removedAsArray = currentRemovedSchools.split(",");
    var ValToRemove = $(this).attr("rel");

    if (IsValueInArray(ValToRemove, addedAsArray)) {
        $("input.schoolsAdded").attr("value", RemoveValueFromArray(ValToRemove, addedAsArray).join());
    }

    removedAsArray.push(ValToRemove);

    $("input.schoolsRemoved").attr("value", removedAsArray.join());
    
    // <li><span><a href=...
    $(this).parent().parent().remove();

    $("#AdditionalSchools ul li").each(function(i, n) {
        if (i % 2 == 0) {
            $(n).attr("class", "");
        } else {
            $(n).attr("class", "alt");
        }
        i++;
    });
    return false;
}

function cancelAddRemoveSchools() {
    $("input.schoolsAdded").attr("value", "");
    $("input.schoolsRemoved").attr("value", "");

    $("#AdditionalSchoolsHead").html("Find additional school forums");
    $("#SchoolsSubText").html("Find other school forums you wish to participate in.");
    $("#SchoolSearchByZip").show();
    $("#SchoolSearchResults").hide();

    $('#AdditionalSchools ul').html(originalSchoolList);
    $('#AdditionalSchools').jqmHide();

    return false;
}

function showUserSummaryFromSchoolUsersList(username) {
    $('#ActiveSchoolMembers').jqmHide();
    DisplayUserProfile(username);
    return false;
}

function setupUserSummaryLinks() {
    
    if ($('a.user-summary').length < 1) {
        return;
    }
    
    $('a.user-summary').click(function(e) {
        DisplayUserProfile($(this).html(), e); 
        return false; 
    });
}

function DisplayUserProfile(username) {
    
    thisScreenName = username;
    $.post("/_handlers/CommunityProfileSummary.ashx", { username: thisScreenName }, HandleProfileResponse, "json");
    return false;
}

function HandleProfileResponse(ProfileData) {

    // Remember if this is the current user
    var isCurrentUser = $("#CommunityProfile > div > input[type=hidden]").attr("value") == thisScreenName;

    // Show or hide edit button
    if (isCurrentUser) {
        $("#container-profile a.edit-profile").show();
    } else {
        $("#container-profile a.edit-profile").hide();
    }

    $(".head .bt-link").attr("rel", ProfileData.PrimarySchoolNumber);

    // Inject ProfileData reutrned into the CommunityProfile div
    // User info
    $('.profile-top-right h4').html(ProfileData.DisplayName);
    $('.profile-top-right h5:first').html(ProfileData.PrimarySchoolName);
    if (isCurrentUser) {
        $('.profile-top-right h5:first').append(" <a href=\"/common/profile/default.aspx\">edit</a>");
    }
    $('.profile-top-right p:first').html(ProfileData.Location);
    $('#profile-top .profile-top-right h5:last').html("About me");
    if (isCurrentUser) {
        $('#profile-top .profile-top-right h5:last').append(" <a href=\"/common/profile/community.aspx\">edit</a>");
    }
    $('#profile-top .profile-top-right p:last').html(ProfileData.Biography);

    // Avatar image
    if (ProfileData.AvatarUrl != null && ProfileData.AvatarUrl != "") {
        $('.profile-top-left img:first').attr('src', ProfileData.AvatarUrl);
    } else {
        $('.profile-top-left img:first').attr('src', DEFAULT_AVATAR);
    }

    $('#profile-top .profile-top-left a:last').hide();
    if (isCurrentUser) {
        $('#profile-top .profile-top-left img').hover(
            function() {
                $('#profile-top .profile-top-left a:last').show();
            },
            function() {
                $('#profile-top .profile-top-left a:last').hide();
            }
        );
    } else {
        $('#profile-top .profile-top-left img').unbind();
    }

    // Stats stuff
    $('.profile-top-left li:first').html("<span>Total posts:</span> ");
    $('.profile-top-left li:first').append(ProfileData.NumberOfPosts);


    // Recent Thread stuff
    $("#recent-posts ul li").remove();
    $("#recent-posts ul").append("<li>Loading recent posts...</li>");

    // User flags
    $('#profile-top .profile-top-left p').remove();

    for (var i = 0; i < ProfileData.RoleNames.length; i++) {
        $('#profile-top .profile-top-left').append("<p class=\"user-flags\">" + ProfileData.RoleNames[i] + "</p>");
    }

    $('#CommunityProfile').jqm({ modal: true, trigger: 'a.jqModal', title: "COMMUNITY PROFILE" }).jqmShow();

    GetUserSummaryPosts(thisScreenName);

}

function GetUserSummaryPosts(user) {

    $.post("/_handlers/CommunityProfileSummaryPosts.ashx", { username: user }, function(data) {

        // Recent Thread stuff
        $("#recent-posts ul li").remove();
        if (data.length > 0) {

            $('.profile-top-left p span').html("<a href=\"" + data[0].SubjectUrl + "\">" + data[0].Subject + "</a>");
            $('.profile-top-left p:last').html(data[0].PostDate);

            for (i = 0; i < data.length; i++) {
                $("#recent-posts ul").append("<li><h6><a href=\"" + data[i].SubjectUrl + "\">" + data[i].Subject + "</a></h6>\n<p>" + data[i].Excerpt + "...</p>\n<p>posted " + data[i].PostDate + " in <a href='" + data[i].SubForumUrl + "'>" + data[i].SubForumTitle + "</a></p></li>");
            }

        } else {
            $('#profile-bottom profile-top-left p span').html("none");
            $('.profile-top-left p:last').html("");
        }
    }, "json");
}

