/**
 * SearchModuleFull
 * @author Jae Cho
 * Subclass of Module that handles search page. This module handles making a search
 * request and displaying result
 *
 * @dependency
 * AddFriendModule
 * StringUtil
 */
function SearchModuleFull() {

    /** module name */
    this._name = SearchModuleFull.NAME;

     /** currently selected search text */
    this._curSearchText = null;

    /** currently selected search type */
    this._curSearchType = null;

    /** search type suggestions */
    this._altSearchType = null;

    /** add friend module */
    this._addModule = null;


    var peopleTab = $("#peopleTab");
    var peopleTabDiv = $("#searchDiv-peopleTab");
    var searchWaitDiv = $("#searchWait");

    this.initialize = function()
    {
        /** add friend module */
        this._addModule = this._page.getModule(AddFriendModule.NAME);

        //set defaults for no search type
        reqParams = StringUtil.getQueryParams(window.location.search);
        if (!reqParams[SearchModuleFull.REQ_TYPE]){
           $("#option-username").attr("checked","checked");
        }

        // initialize the top search controls
        var typeName = $("#typeName");
        var typeUsername = $("#typeUsername");
        var typeEmail = $("#typeEmail");
        var typeArg = { "module": this, "typeName": typeName, "typeUsername": typeUsername, "typeEmail": typeEmail};

        var submitSearch = bindContext(this,this._submitSearch)
        var searchBtn = $("#searchBtn");
        searchBtn.click(submitSearch);
        $("#searchText").bind("keypress", this, function(e){
            if (e.which == 13){
              submitSearch()
            }
        })

    }

    /** @return list of request actions that can be handled by this module */
    this.getPageActionNames = function() {
        return [ SearchModuleFull.PAGE_ACTION_SEARCH ];
    }

    this.handlePageAction = function(actionName) {
        if (actionName == SearchModuleFull.PAGE_ACTION_SEARCH) {
            reqParams = StringUtil.getQueryParams(window.location.search);
            var text = unescape(reqParams[SearchModuleFull.REQ_TEXT]);
            var type = reqParams[SearchModuleFull.REQ_TYPE];
            $("#searchText").attr("value",text)
            this._sendSearchReq(type, text);
        }
    }

    this._submitSearch = function(e){
        if (e){e.preventDefault();}
        var searchText = $("#searchText").attr("value");
        var searchRadio = $(".search_options input:checked").attr("value")
        this._sendSearchReq(searchRadio,searchText);
    }
    /** send search request
     * @param type search type
     * @param text search term
     * @return true if
     */
    this._sendSearchReq = function(type,text)
    {
        peopleTabDiv.find(".search_results").hide();
        searchWaitDiv.show();
        this._curSearchText = text;
        var searchType = "";
        var emailRegx= /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i;

        var typeString_name =  "First &amp; Last Name";
        var altSearchTypeName =  "<strong>Username</strong> or <strong>Email Address</strong>";
        var typeString_email = "Email Address";
        var altSearchTypeEmail = "<strong>First &amp; Last Name</strong> or <strong>Username</strong>";
        var typeString_user = "Username";
        var altSearchTypeUser = "<strong>First &amp; Last Name</strong> or <strong>Email Address</strong>";

        $(".search_options input:radio").attr("checked","");

        switch(type){

        case "people":
            /** attempt to determine the people search subtype **/
            var searchTextArr = text.split(" ");
            if (searchTextArr[1]){
                $(".search_options #option-firstlast").attr("checked","checked")
                searchType = "FirstAndLastName";
                this._curSearchType = typeString_name;
                this._altSearchType = altSearchTypeName;
            }else if(emailRegx.test(searchTextArr[0])) {
                $(".search_options #option-email").attr("checked","checked")
                searchType = "UsernameOrEmail";
                 this._curSearchType = typeString_email;
                 this._altSearchType = altSearchTypeEmail;
            }else{
                $(".search_options #option-username").attr("checked","checked")
                searchType = "UsernameOrEmail";
                this._curSearchType = typeString_user;
                this._altSearchType = altSearchTypeUser;
            }
           break;
         case "firstlast":
             if (text.split(" ")[1]){ //make sure there are 2 names
                 $(".search_options #option-firstlast").attr("checked","checked")
                    searchType = "FirstAndLastName";
                    this._curSearchType = typeString_name;
                    this._altSearchType = altSearchTypeName;
             }else{
                 $(".search_options #option-firstlast").attr("checked","checked")
                 $("#searchResultTitle").html("<p style='color:#f00'><strong>You must enter both a first and last name for this search.</strong></p>")
                 searchWaitDiv.hide();
                 peopleTabDiv.find(".search_results").show();
                 peopleTabDiv.find("#searchResult").empty();
                 return;
             }
                break;
         case "email":
                 $(".search_options #option-email").attr("checked","checked");
                searchType = "UsernameOrEmail";
                this._curSearchType = typeString_email;
                this._altSearchType = altSearchTypeEmail;
                break;
         case "username":
                $(".search_options #option-username").attr("checked","checked");
                searchType = "UsernameOrEmail";
                this._curSearchType = typeString_user;
                this._altSearchType = altSearchTypeUser;
                break;
         }
        this._page.makeModuleAjaxCall(this,
            [{ "methodName": "searchUsers", "searchTerm" : text, "searchType" : searchType}]);

    };

    /** update the result set title */
    this._updateResultTitle = function(res)
    {
        var titleSpan = $("#searchResultTitle");

        var resultDesc = "";
        if (!res.profiles || res.profiles.length == 0) {
            resultDesc = "<p>We were not able to find <strong>&quot;"+this._curSearchText+"&quot;</strong> as an AddictingGames user.</p>"+
		                 "<p>You can also try searching by "+this._altSearchType+".";
        } else if (res.profiles.length == 1) {
            resultDesc = "<p>Displaying <strong>1 - 1</strong> result for <strong>&quot;"+this._curSearchText+"&quot;</strong>.</p>";
        } else {
            resultDesc = "<p>Displaying <strong>1 - "+res.profiles.length+"</strong> of <strong>"+ res.profiles.length+"</strong> results for &quot;<strong>"+this._curSearchText+"</strong>&quot;.</p>";
        }

        titleSpan.html(resultDesc);
    }

    /** handle response from the server on invitation */
    this._handleSearchRes = function(res)
    {
        // update the title
        this._updateResultTitle(res);

        var profileList = res.profiles;
        var resultDiv = $("#searchResult");
        resultDiv.empty().show();

        for (var i = 0; i < profileList.length; i++)
        {
            var profile = profileList[i];
            if (!profile.profilePath){    //innactive user check
                continue;
            }
            var profileDivContent =
                  "<div class='result float'>"+
                    "<div class='result_pic'>" +
                    "<a href='" + profile.profilePath + "'>" +
                        "<img class='profileImgSm' src='" + ProfileUtil.getImg({userId: profile.userId,userPicSet:profile.userPicSet,size:"small"}) + "' style='border:1px solid gray;'/>" +
                    "</a>"+
                  "</div>" +
                   "<div class='result_link'>"+
                    "<a href='" + profile.profilePath + "'>" + profile.userName + "</a>"+
                  "</div>"+
                  "<div class='result_add'>";

                if (profile.relationship == "stranger") {
                    profileDivContent +=
                        "<a id='addToFriendBtn_" + profile.userId + "'>Add Friend</a>"

                }else{
                    profileDivContent +=
                        "<a class='emptyLink'>&nbsp;</a>"
                }
            profileDivContent +="</div>"+
                   "</div>";

            resultDiv.append(profileDivContent);

            // bind add_to_friend
            if (profile.relationship == "stranger") {
                var moreInfo = AddFriendModule.getNeededInfo(profile);
                var args = { "module": this, "userId" : profile.userId, "userName" : profile.userName,
                    "moreInfo" : moreInfo };
                $("#addToFriendBtn_" + profile.userId).bind("click", args, function(e) {
                    var args = e.data;
                    args.module._makeFriendRequest(args.userId, args.userName, args.moreInfo,profile.userPicSet);
                });
            }

            if ((i + 1) % 7 == 0 || i + 1 == profileList.length) {
                var dividerContent = "<br class='clearFloat'/>";
                resultDiv.append(dividerContent);
            }
        }
        searchWaitDiv.hide();
        peopleTabDiv.find(".search_results").show();
    }

    /** make friend request */
    this._makeFriendRequest = function(userId, userName, moreInfo,userPicSet)
    {
        var callback = function(userId) {
           $("#addToFriendBtn_" + userId).css("background", "none").text('');
        };
        callback = bindContext(null, callback, [userId]);
        this._addModule.setCallback(callback);
        this._addModule.showAddDialog(userId, userName, moreInfo, userPicSet);
    }

    /** handle AJAX response object */
    this.handleResObjects = function(resObjects) {
        var responseReceived = false;
        for (var i = 0; i < resObjects.length; i++) {
            var res = resObjects[i];
            if (res["methodName"] == "searchUsers") {
                this._handleSearchRes(res.response);
            }
        }
    }
}

/** module name */
SearchModuleFull.NAME = "SearchModuleFull";

/*search type - name */
SearchModuleFull.TYPE_NAME = "name";

/** search type username */
SearchModuleFull.TYPE_USERNAME = "username";

/** search type email */
SearchModuleFull.TYPE_EMAIL = "email";

/** search type people  (name, username, or email)*/
SearchModuleFull.TYPE = "people";

/** page action */
SearchModuleFull.PAGE_ACTION_SEARCH = "search";

/** search type for page action */
SearchModuleFull.REQ_TYPE = "type";

/** searc text for page action */
SearchModuleFull.REQ_TEXT = "text";

SearchModuleFull.prototype = new Module();
