﻿
var PLUCKSearch = PLUCKSearch ? PLUCKSearch : function() {
    var private = {
        title: "PLUCK Search Implementation",
        serverUrl: serverUrl,
        UID: "uid",
        currentPage: 1,
        debug: function(str) {
            if (debug)
                console.log(str);
            //alert(str);
        },
        debugobj: function(obj) {
            if (debug)
                console.dir(obj);
        },
        searchUser: function(searchString, page) {
            private.debug("searchUser: getting stuff from pluck");
            private.currentPage = page;
            var requestBatch = new RequestBatch();
            var searchPage = new SearchAction("CommunityGroup", searchString, 10, private.currentPage);
            requestBatch.AddToRequest(searchPage);
            requestBatch.BeginRequest(private.serverUrl, private.renderUserSearch);
        },
        renderUserSearch: function(responseBatch) {
            private.debug("renderUserSearch");
            private.debugobj(responseBatch);
            if (responseBatch.Messages[0].Message === 'ok') {
                // success from pluck, lets process the data
                for (var i = 0; i < responseBatch.Responses.length; i++) {
                    var response = responseBatch.Responses[i];
                    if (response.SearchResult != null) {
                        if (private.searchResultPageHandler != null) {
                            private.searchResultPageHandler(response.SearchResult, response.SearchResult.SearchString);
                        }
                        else {
                            private.debug("No SearchResultPageHandler defined and response " + i + " is a SearchResult");
                        }
                    }
                }
            }
        },
        searchResultPageHandler: function(searchPage, SearchString) {
            private.debug('searchResult');
            private.debugobj(searchPage);
            public.showResults(searchPage.SearchResults, searchPage.NumberOfSearchResults, SearchString);
        },
        addFriend: function(friendKey) {
            private.debug('adding Friend ' + friendKey);
            var requestBatch = new RequestBatch();
            var addFriend = new AddFriendAction(new UserKey(friendKey));
            requestBatch.AddToRequest(addFriend);
            requestBatch.BeginRequest(private.serverUrl, private.renderFriends);  // reusing renderFriends since it'll redraw the friend list.
        },
        renderFriends: function(responseBatch) {
            private.debug("renderFriends");
            private.debugobj(responseBatch);
        }
    };


    var public = {
        getTitle: function() {
            return private.title;
        },
        firstRun: function(InitialLocationSearchString) {
            private.searchUser(InitialLocationSearchString, 1);
        },
        getItStarted: function(joinedQuery, page) {
            private.searchUser(joinedQuery, page);
        },
        getItStartedOriginal: function() {
            var el = document.getElementById("quickSearch");
            private.searchUser(el.value, 1);
        },
        userDetails: function(user) {
            var detailsHtml = "";
            var MAX_DUMP_DEPTH = 10;

            function dumpObj(obj, name, indent, depth) {
                if (depth > MAX_DUMP_DEPTH) {
                    return indent + name + ": Maximum Depth Reached<br />";
                }
                if (typeof obj == "object") {
                    var child = null;
                    var output = indent + name + "<br />";
                    indent += "&nbsp;&nbsp;";
                    for (var item in obj) {
                        try {
                            child = obj[item];
                        } catch (e) {
                            child = "<Unable to Evaluate>";
                        }
                        if (typeof child == "object") {
                            output += dumpObj(child, item, indent, depth + 1);
                        } else {
                            output += indent + item + ": " + child + "<br />";
                        }
                    }
                    return output;
                } else {
                    return obj;
                }
            }
            detailsHtml += "User :" + dumpObj(user, "User", "", 0) + " <br />";

            return detailsHtml;
        },
        showResults: function(groupArray, totalItems, SearchString) {
            private.debug("showResults");
            var friendHtml = "";
            for (var i = 0; i < groupArray.length; i++) {
                var group = groupArray[i];
                var detailsView = public.userDetails(group).replace(/'/g, "\\'");
                //var location = group.Categories.split("|");

                if (group.Section == "clinic") {
                    ProfileLink = "ClinicProfile";
                }
                else if (group.Section == "races") {
                    ProfileLink = "RaceProfile";
                }
                else if (group.Section == "events") {
                    ProfileLink = "EventProfile";
                }
                else {
                    ProfileLink = "GroupProfile";
                }

                if (group.Section == "clinic") {
                    if (group.Categories.indexOf('|') != -1) {
                        CategoriesSplit = group.Categories.split("|");
                        locationSplit = CategoriesSplit[1].split(",");
                        groupDetail = locationSplit[3] + " weeks";
                    }
                    else {
                        groupDetail = "duration not specified";
                    }
                }
                else {
                    if (group.Categories.indexOf('|') != -1) {
                        CategoriesSplit = group.Categories.split("|");
                        locationSplit = CategoriesSplit[1].split(",");
                        groupDetail = locationSplit[1] + ", " + locationSplit[2];
                    }
                    else {
                        groupDetail = "location not provided";
                    }
                }

                
                friendHtml += "<div class='MyGroupItem'>";
                friendHtml += " <div id='icon'><img class='friendPhoto' src='" + group.AvatarImageUrl + "' /></a></div>";
                friendHtml += " <div class='info'>";
                friendHtml += "      <span class='user'><a href='" + ProfileLink + ".aspx?groupid=" + group.CommunityGroupKey.Key + "'>" + group.Title + "</a></span>";
                friendHtml += "      <span class='friendLocation'> (" + groupDetail + ")</span><br>";
                var description = group.Description;
                if (description.length > 255) {
                    description = description.substr(0, 255) + "...";
                }
                friendHtml += "<span class='status'>" + description + "</span><br>";
                friendHtml += "<span class='status'><strong>" + readCustomEventDataForRaceIndex(group.CommunityGroupKey.Key) + "</strong></span>";
                friendHtml += "</div>";
                friendHtml += "</div>";
                
            }
            var elUser = document.getElementById("MyGroupList");
            elUser.innerHTML = friendHtml;
            //var elUser = document.getElementById("SearchCount");
            //elUser.innerHTML = totalItems;

            var detailsView = public.userDetails(groupArray, 0);
            var userHtml = "";
            userHtml += "<div id='userReturn'>";
            userHtml += detailsView;
            userHtml += "</div>";
            //var elUser = document.getElementById("SearchResults");
            //elUser.innerHTML = elUser.innerHTML + userHtml;

            var numberOfPages = Math.ceil(totalItems / 10);
            //alert(totalItems);
            //alert(numberOfPages);
            var pagerHTML = "";

            for (p = 1; p <= numberOfPages; p++) {
                pagerHTML += '<a href="javascript:void(0);" onclick="PLUCKSearch.getItStarted(\'' + SearchString + '\',\'' + p + '\')">' + p + '</a> | ';
            }

            document.getElementById("pagination").innerHTML = pagerHTML;


        },
        addFriend: function() {
            private.debug("addFriendQuick");
            var el = document.getElementById("quickAdd");
            private.addFriend(el.value);
        },
        reportAbuse: function(index) {
            // report abuse
        }
    }
    private.debug("Doing Something : " + public.getTitle());
    return public;
} ();


    var requestBatch = new RequestBatch();
    var userKey = new UserKey(currentProfileID);
    requestBatch.AddToRequest(userKey);

    requestBatch.BeginRequest(serverUrl, myCallbackMethod);

    function myCallbackMethod(responseBatch) {
        //console.dir(responseBatch);
        var User = responseBatch.Responses[0].User;
        LocationSplit = User.Location.split(",");
        // USING CITE FOR NOW
        UserProvince = LocationSplit[1];
        //alert("||"+UserProvince+"||");
        if (UserProvince == " AB") {
            UserProvinceDisplay = "Alberta";
        }
        if (UserProvince == " BC") {
            UserProvinceDisplay = "British Columbia";
        }
        if (UserProvince == " MB") {
            UserProvinceDisplay = "Manitoba";
        }
        if (UserProvince == " NB") {
            UserProvinceDisplay = "New Brunswick";
        }
        if (UserProvince == " NL") {
            UserProvinceDisplay = "Newfoundland and Labrador";
        }
        if (UserProvince == " NT") {
            UserProvinceDisplay = "Northwest Territories";
        }
        if (UserProvince == " NS") {
            UserProvinceDisplay = "Nova Scotia";
        }
        if (UserProvince == " NU") {
            UserProvinceDisplay = "Nunavut";
        }
        if (UserProvince == " ON") {
            UserProvinceDisplay = "Ontario";
        }
        if (UserProvince == " PE") {
            UserProvinceDisplay = "Prince Edward Island";
        }
        if (UserProvince == " QC") {
            UserProvinceDisplay = "Quebec";
        }
        if (UserProvince == " SK") {
            UserProvinceDisplay = "Saskatchewan";
        }
        if (UserProvince == " YK") {
            UserProvinceDisplay = "Yukon";
        }
        
        //alert("_"+UserProvince+"_");
        UserCity = LocationSplit[0];
        //var InitialLocationSearchString = "Section:events AND Categories:isapproved AND Categories:" + UserCity;
        var InitialLocationSearchString = "Section:events AND Categories:isapproved";
        //document.getElementById("ProvinceResult").innerHTML = UserProvinceDisplay;
        PLUCKSearch.firstRun(InitialLocationSearchString);
    }
    

    function quickGroupSearch() {
        var requestBatch = new RequestBatch();
        var userKey = new UserKey(currentProfileID);
        requestBatch.AddToRequest(userKey);

        requestBatch.BeginRequest(serverUrl, myCallbackMethod);

        function myCallbackMethod(responseBatch) {
            //var User = responseBatch.Responses[0].User;
            //LocationSplit = User.Location.split(",");
            //UserCity = LocationSplit[0];
 
            //var InitialLocationSearchString = "Location:" + UserCity;
            function andMaker() {
                if (joinedQuery == "") {
                    and = "";
                }
                else {
                    and = " AND ";
                }
            }
            
            var joinedQuery = "Categories:isapproved";
            if (document.getElementById("runnerName").value != "") {
                andMaker();
                joinedQuery += and + "Title:" + document.getElementById("runnerName").value;
            }
            if (document.getElementById("runnerProvince").value != "") {
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerProvince").value;
            }
            if (document.getElementById("runnerCity").value != "") {
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerCity").value;
            }
            if (document.getElementById("runnerDistance").value != "") {
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerDistance").value;
            }
            if (document.getElementById("runnerRunsOn").value != "") {
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerRunsOn").value;
            }
            if (document.getElementById("runnerKeywords").value != "") {
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerKeywords").value;
            }
            joinedQuery += " AND Section:Events";
            //document.getElementById("ProvinceResult").innerHTML = joinedQuery;
            PLUCKSearch.getItStarted(joinedQuery,'1');
        }
    }
