debug = false;
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 = "";
            len = groupArray.length - 1;
            for (var i = len; i >= 0; 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";
                }

                //alert(group.Categories + " is there a | = "+group.Categories.indexOf('|'));

                if (group.Section == "clinic") {
                    if (group.Categories.indexOf('|') != -1) {
                        CategoriesSplit = group.Categories.split("|");
                        locationSplit = CategoriesSplit[1].split(",");
                        //alert(locationSplit[3]);
                        groupDetail = locationSplit[3] + " weeks";
                    }
                    else {
                        groupDetail = "duration not specified";
                    }
                }
                else {
                    if (group.Categories.indexOf('|') != -1) {
                        CategoriesSplit = group.Categories.split("|");
                        locationSplit = CategoriesSplit[1].split(",");
                        if (locationSplit[0] != "") {
                            neighbourhood = locationSplit[0];
                            if (neighbourhood.length > 30) {
                                neighbourhood = neighbourhood.substr(0, 30) + "...";
                            }
                            groupDetail = neighbourhood + ", " + locationSplit[1] + ", " + locationSplit[2];
                        }
                        else {
                            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'>";
                if (group.CommunityGroupVisibility == "Public" || group.Owner == currentProfileID) {
                    friendHtml += "      <span class='user'><a href='" + ProfileLink + ".aspx?groupid=" + group.CommunityGroupKey.Key + "'>" + group.Title + "</a></span>";
                }
                else {
                    friendHtml += "      <span class='user'><img src='images/icons/small/private.gif' title='This is a private group.'> " + group.Title + "</span>";
                    friendHtml += "      <span id='privateGroupLink" + i + "' class='privateGroupLink'><a href='javascript:void(0);' onClick='RequestMembershipInPrivateGroup(\"" + group.CommunityGroupKey.Key + "\",\"" + i + "\",\"" + group.Owner + "\")'><img src='images/icons/small/JoinClinic.gif' alt='Request Membership' title='Request membership in this group'></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>";
                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;
            
            //set links for nav tabs
            /*document.getElementById("allResultsTab").onclick = "alert('"+SearchString+"')";
            document.getElementById("groupsTab").onclick = "PLUCKSearch.getItStarted('" + SearchString + "','1')";
            document.getElementById("clinicsTab").onclick = "PLUCKSearch.getItStarted('" + SearchString + "','1')";*/
            
            if (!document.all) {
                allResultsTab = document.getElementById("allResultsTab");
                groupsTab = document.getElementById("groupsTab");
                clinicsTab = document.getElementById("clinicsTab");
            }
            
            //$('#allResultsTab').click = function() {alert(SearchString+'111');return false;}
            tabLocation = SearchString.split(" ");
            groupsTabSearchString = tabLocation[0] + " AND Section:Standard";
            clinicsTabSearchString = tabLocation[0] + " AND Section:Clinic";
            
            allResultsTab.onclick = function() {PLUCKSearch.getItStarted(SearchString,"1");return false;}
            groupsTab.onclick = function() {PLUCKSearch.getItStarted(groupsTabSearchString,"1");return false;}
            clinicsTab.onclick = function() {PLUCKSearch.getItStarted(clinicsTabSearchString,"1");return false;}
            //allResultsTab.onclick = function() {alert(groupsTabSearchString);return false;}
            
            /*allResultsTab.setAttribute("onclick","alert('"+SearchString+"1111')");
            groupsTab.setAttribute("onclick","alert('"+SearchString+"2222')");
            clinicsTab.setAttribute("onclick","alert('"+SearchString+"3333')");*/
            
            var numberOfPages = Math.ceil(totalItems / 10);
            //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 qString = gSiteLife.GetParameter('qstring');
        //alert(qString);
        //alert(qString);
        if (qString == null) {
            var User = responseBatch.Responses[0].User;
            LocationSplit = User.Location.split(",");
            UserCity = LocationSplit[0];
            //alert(UserCity);
            var InitialLocationSearchString = "Categories:" + UserCity;
            InitialLocationSearchString += " AND Section:Standard OR Section:Clinic";
            //document.getElementById("SearchParameterUsed").innerHTML = InitialLocationSearchString;
            
        }
        else {
            qString = qString.replace(/%20/g,' ');
            var InitialLocationSearchString = qString;
        }
        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 = "";
            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("groupType").value != "") {
                andMaker();
                joinedQuery += and + "Section:" + document.getElementById("groupType").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("runnerRunsDuring").value != "") {
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerRunsDuring").value;
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerRunsDuring").value;
            }
            if (document.getElementById("runnerKeywords").value != "") {
                andMaker();
                joinedQuery += and + "Categories:" + document.getElementById("runnerKeywords").value;
            }
            joinedQuery+= " NOT Section:Events NOT Section:Races";
            //document.getElementById("SearchParameterUsed").innerHTML = joinedQuery;
            PLUCKSearch.getItStarted(joinedQuery,'1');
            if (!document.all) {
                allResultsTab = document.getElementById("allResultsTab");
                groupsTab = document.getElementById("groupsTab");
                clinicsTab = document.getElementById("clinicsTab");
            }
            
            //$('#allResultsTab').click = function() {alert(SearchString+'111');return false;}
            tabLocation = SearchString.split(" ");
            groupsTabSearchString = tabLocation[0] + " AND Section:Standard";
            clinicsTabSearchString = tabLocation[0] + " AND Section:Clinic";
        }
    }
    
