﻿/* recipe blocks */
function RecipeResultsClass() {
    var _this = this;
    this._resultsContainer = null; //container of search results (including the paging containers)
    this._filtersContainer = null; //container that holds all advanced search filters
    this._pageNumber = 1;
    this._resultCount = 0;
    this._method = null;
    this._user = null;
    this._pagingContainers = null;
    this._searchQuery = "";
    this._baseUrl = "/webservice/ajax.aspx?";
    this._xhr = null;
    this._addHistory = null;
    this._initialized = false;
    this._itemsPerPage = 10;

    this.init = function(ctrl, baseQuery, addHistory, filtersContainer, itemsPerPage) {
        
        $j("div#results.results_title").hide();
        $j("div#refreshing.results_title").show();
        $j("div#results.results_title").removeClass('hide');
        if (baseQuery != "undefined")
            _this._baseUrl += baseQuery; //basequery contains the ajax method to use and any additional "static" parameters
        _this._filtersContainer = filtersContainer;
        _this._resultsContainer = ctrl;
        var query = baseQuery.replace("method=", "")
        if(query.search("&username") != -1) query = query.split("&username=");
        else query = query.split("&id=");
        _this._method = query[0];
        _this._user = query[1];

        if(typeof itemsPerPage != "undefined")
            _this._itemsPerPage = itemsPerPage;

        //_method = method;
        _this._addHistory = addHistory ? true : false;
        _this._pagingContainers = $j(_this._resultsContainer).parent().children(".pagination");
        //add sorting handlers
        _this._pagingContainers.children("select").change(function() { _this.sortSearchResults(this.value); });
        //add data container
        if($j(_this._resultsContainer).children(".recipeContainer").length == 0)
            $j(_this._resultsContainer).append("<ul class=\"recipeContainer\"></ul>");



        //add history stuff if needed, otherwise just gen results
        if (_this._addHistory) {
            $j.historyInit(_this.genRecipeTab);
        }
        else {
           _this.genRecipeTab(window.location.hash);
        }
    }

    this.setSearchParams = function(qstring) {
        _this._pageNumber = qstring.match(/pg=(\d+)/) ? qstring.match(/pg=(\d*)/)[1] : 1;
        _this._searchQuery = qstring.replace(/#?(pg=\d*&?)?/, "");
    }

    /*
    handler for paging clicks
    */
    this.genRecipeTab = function(hash) {
        
        $j("div#results.results_title").hide();
        $j("div#refreshing.results_title").show();

        if (_this._xhr)
            _this._xhr.abort();

        if (!_this._initialized && window.location.href.match("recipe-categories")) {
            _this.updatePaging(_this._resultCount, _this._pagingContainers.children(".pages"), _this._pageNumber);
            _this._initialized = true;
            shadowFix();
            return;
        }
        else {
            _this.setSearchParams(hash);
           // alert(_this._baseUrl + _this._searchQuery + "&page=" + _this._pageNumber); 
          
            _this._xhr = $j.getJSON(_this._baseUrl + _this._searchQuery + "&page=" + _this._pageNumber,
            function(data) {  
                if (data.resultCount > 0 && typeof searchCallback != "undefined")
                    searchCallback();
                $j(".recipe-result-count").text(data.resultCount);
                if (data.resultCount > 2)
                    $j(".version_sum").show();
                else
                    $j(".version_sum").hide();
                _this._resultCount = data.resultCount;
                _this.updatePaging(data.resultCount, _this._pagingContainers.children(".pages"), _this._pageNumber);
                _this.parseRecipes(data, $j(_this._resultsContainer).children(".recipeContainer"), _this._pageNumber);
               
                if (typeof requerySearch != "undefined")
                    requerySearch(data);
                
                /*$j('.recipeContainer .open-connect-login').click(function() {
					var action = $j(this).attr('action');
					openSignupLoginModal(action);
				});*/
                
                shadowFix();

                //add counts to tabs
                if (!_this._initialized && _this._resultsContainer.parent().hasClass("inner_tab_content")) {
                    $j("div.inner_tab_content").each(function(i, obj) {
                        if (obj == _this._resultsContainer.parent()[0])
                        {
                                $j("li#tab" + i + " > a").text($j("li#tab" + i + " > a").text().replace(/\(\d*\)/, ""));
                                $j("li#tab" + i + " > a").text($j("li#tab" + i + " > a").text() + " (" + data.resultCount + ")");
                           
                        }
                    });
                }
                _this._initialized = true;
            });
        }
    }

    /*
    callback method for ajax
    */
    this.parseRecipes = function(data, container, pg) {
        var re = new RegExp(_this._user,'i');
        $j(container).empty();
        if(_this._method.search(/filtersearchresults/) != -1 || _this._method.search(/getSearchResults/) != -1) {
			$j("div#results.results_title").empty();
			$j("div#results.results_title").append(_this.formatSearchResultMessage(data.resultCount, data.didYouMean));
        }
        else if (re.exec($j.cookie('Tablespoon_UserName')) != null) {
         
            if ($j(container).parent().parent().find("p.empty_txt").length > 0)
                $j(container).parent().parent().find("p.empty_txt").remove();
         
			if (_this._method.search(/getfavorites/) != -1 && data.resultCount == 0)
				$j(container).parent().parent().prepend("<p class='empty_txt'>Start filling your Recipe Box with tasty, top-rated dishes! Just find a recipe you like. Then hit the \"Save\" button at the top. Easy, huh?</p>");
			else if (_this._method.search(/getmyrecipes&drafts=1/) != -1 && data.resultCount > 0)
			{
			    $j(container).parent().parent().prepend('<p class="empty_txt">Keep track of your in-progress recipes here. Hit "Publish" to show finished recipes to other members.</p>');
			}
			else if (_this._method.search(/getmyrecipes/) != -1 && data.resultCount == 0) 
				$j(container).parent().parent().prepend("<p class='empty_txt'>Start contributing your own recipes to Tablespoon! Just <a href='/add-recipe'>Add a Recipe</a>.</p>");
		}
		
        $j.each(data.items, function(idx, val) { _this.addRecipe(idx, val, container, data.resultCount); });
        
        if (data.resultCount != 0 && (data.items.length == 0 || data.items == null))
        {
             $j(container).html("<li>We are having trouble displaying your results.  Please try your search again.</li>");
        }
        $j(".recipe_block .open-connect-login").click(function() { $j(".trigger-save-result").click(); });
       
       
        //$j(container).append("<input type=hidden value=\"" + data.resultCount + "\">");
        $j(container).find("a.list_my_recipes, a.list_drafts_delete, a.list_saved_recipes").click(function() { _this.updatePaging(--_this._resultCount, _this._pagingContainers.children(".pages"), _this._pageNumber); if (Math.min(Math.ceil(_this._resultCount / _this._itemsPerPage), _this._pageNumber) < _this._pageNumber) { _this.genRecipeTab("pg=" + Math.ceil(_this._resultCount / _this._itemsPerPage)); } });
        $j("div#results.results_title").show();
        $j("div#refreshing.results_title").hide();
        
       if (_this._method.search(/getmyrecipes/) != -1)
       {
            if ($j("a.publish-trigger").text() != "done")
            {
                $j('a.publish-trigger').simpleLightbox({
				    lightboxContentBlock:'.confirmation',
				    closeLink:'a.close-publish'
	            });
	        }
	        
	        $j("a.publish-trigger").text("done");
	        
       }
    }

    this.formatSearchResultMessage = function(count, suggestion) {
        var message = "";
        if (count == 0) {
            message = "Oops. We didn't find anything for <span id=\"search_string\">\"" + unescape(getKeyword()) + "\"</span>. Please type your term again, or enter a new one.";
            if (suggestion != null) {
                message = message + '<br/>Did you mean to search for "<a href=\'/search/' + suggestion + '\'>' + suggestion + '</a>"?';
            }
            message = message + "<br/>For fresh ideas, search our:<ul><li><a href='/top-50/'>Top 50</a></li><li><a href='/recipe-of-the-day/'>Recipe of the Day</a></li><li><a href='/top-rated-recipes/'>Top Rated</a></li></ul>";
            
			$j(_this._pagingContainers).hide();
		}
		else {
			message = count + (count == 1 ? " recipe" : " recipes") + " for <span id=\"search_string\">\"" + unescape(getKeyword()) + "\"</span>";
			$j(_this._pagingContainers).show();
		}
        return message;
    }

    //appends a recipe(data) to a container
    this.addRecipe = function(idx, data, container, currentResultCount) {
		var re = new RegExp(_this._user,'i');
		var ure = new RegExp(data.author, 'i');
		//alert(currentResultCount);
        var block = "<li class='recipe_block" + ((data.brandName == "" || typeof data.brandName == "undefined") ? " user-generated" : " brand-generated") + "' original='" + data.isOriginal + "'>";

        block += "<div class=\"smlimagebox medborder\"><div class=\"tr\"><!--ie--></div><div class=\"bl\"><!--ie--></div><div class=\"br\"><!--ie--></div><a href=\"" + data.detailUrl + "\" baynote_bnrank=\"" +  data.baynote_bnrank + "\" baynote_irrank=\"" + data.baynote_irrank + "\" onclick=\"return strandsTrackSearch('" + data.recipeId + "','" + escape(getKeyword()) + "','" + data.detailUrl + "');\">";
        if (data.smallThumbImage != "" && data.smallThumbImage != "null")
            block += "<img src=\"" + RECIPE_IMAGE_BASE_PATH + data.smallThumbImage + "\" alt=\"" + data.recipeName + "\" />";
        else
            block += "<img src=\"/assets/images/default-image-small-fpo.png\" alt=\"" + data.recipeName + "\" />";
        block += "</a>";
        block += "<div class=\"clear\"><!--ie--></div></div>";
        block += "<div class='recipe-result-body'><div class=\"brand\">";
        if (data.brandName != "" && data.brandName != null)
            block += "<a href=\"/" + getProfileURL(data.author) + "\"><img src=\"" + BRAND_IMAGE_BASE_PATH + (data.brandName.replace(/ /g, "_")) + ".png\" alt =\"" + data.brandName + "\" /><a/>";
        block += "</div>";
        block += "<a href=\"" + data.detailUrl + "\" onclick=\"javascript:eval($j(this).attr('ontrigger'));\" ontrigger=\"javascript:strandsTrackSearch('" + data.recipeId + "','" + escape(getKeyword()) + "','" + data.detailUrl + "');\" baynote_bnrank=\"" + data.baynote_bnrank + "\" baynote_irrank=\"" + data.baynote_irrank + "\" class='recipe-link'>" + truncateText(data.recipeName, 40) + "</a>";
        block += "<p>by ";

        if (data.author != "")
            block += "<a href=\"/" + getProfileURL(data.author) + "\">" + data.author + "</a>";
        else if (data.brandName != "" & data.brandName != null)
            block += "<span>" + data.brandName + "</span>";
        else
            block += "<span>Anonymous User</span>";

        block += "</p><p class='desc'>";
        if (data.description != "" && data.description != null) 
        {   
            block += truncateText(data.description, 125)
        } 
        else 
        {
            block += "&nbsp;";
        }
        block += "</p>";
        
        block += "<span class=\"rating\"><img src=\"" + getAssetRoot() + "/assets/images/";
        if (_this.getUserRecipeRating(data.mediaId) > 0) {
            block += _this.getUserRecipeRating(data.mediaId);
            block += "_Stars_yellow.gif\" alt=\"star\" /> (";
        }
        else {
            block += roundNearest(data.overallRating, 0.5).toFixed(1);
            block += "_Stars.gif\" alt=\"star\" /> (";
        }
        block += data.ratingsCount;
        block += ")</span><span class=\"comments\">Comments: <span>";
        // Retaining conditional in event we bring the link back eventually.
        if (data.commentCount < 0)
            block += "<a href=\"" + data.detailUrl + "?tab=comments\">" + data.commentCount + "</a>";
        else
            block += data.commentCount;
        block += "</span></span><span class=\"time\">Total Time: <span>";
        //block += data.totalCookingHours > 0 ? data.totalCookingHours + data.totalCookingHours > 1 ? " hours " : " hour " : "";
        //var time = data.totalCookingMinutes - (data.prepMinutes + data.prepHours*60);
        var time = (typeof data.total_time == "undefined" ? data.totalCookingMinutes : data.total_time);
       
        if (time != 0)
        {
            var hours = Math.floor(time / 60) > 0 ? Math.floor(time / 60) + (Math.floor(time / 60) > 1 ? " hrs " : " hr ") : "";
            var minutes = (time % 60) > 0 ? (time % 60) + " mins" : "";
            if (hours == "" && minutes == "")
                minutes = "0 mins";
            block += hours;
            block += minutes;
		}
		else
			block += "0 mins";
        block += "</span></span>";
        block += "<span class=\"action\">";
    
        // search results block
        //alert(_this._method);
        if (_this._method != null && (_this._method.search(/getSearchResults/) != -1 || _this._method.search(/filtersearchresults/) != -1 || _this._method.search(/getcollectionreciperesults/) != -1)) {
            // add link always displays
            var aclass = " class=\"" + ($j(".trigger-save-result").text() == "true" ? "addRecipe" : "open-connect-login");
            block += "<a action=\"Save a Recipe\" ";
            // save function if logged in
            if ($j.cookie('Tablespoon_RawUserName') != null) {
                block += " href=\"javascript:void(0);\" onclick=\"toggleSaveRemove(this); $j.getJSON('/webservice/ajax.aspx?method=markfavoriteRecipe&recipe=" + data.recipeId + "'); addMySavedRecipe('" + data.recipeId + "', this); return false;\"";
                if (isRecipeSaved(data.recipeId))
                    aclass += " hide\"";
                else
                    aclass += "\"";
            // otherwise redirect to registration
            } else {
                //block += " href=\"/registration/register.aspx?ref=save&id=" + data.recipeId + "\"";
                //aclass += "\"";
                block += " href=\"javascript:void(0)\"";
                aclass = " class='open-connect-login'";
            }
            block += aclass + ">Save</a>";

            // already saved text only displays if logged in
            if ($j.cookie('Tablespoon_RawUserName') != null) {
                var rclass = " class=\"removeRecipe disabled";
                block += "<a ";
                block += "href=\"javascript:void(0);\" onclick=\"return false;\"";
                if (!isRecipeSaved(data.recipeId))
                    rclass += " hide\"";
                else
                    rclass += "\"";
                block += rclass + ">Recipe Saved</a>";
            }
        // all other blocks on the profile page
        } else if ($j.cookie('Tablespoon_RawUserName') != null) {
            //switch (_this._method) {
			if (_this._method.search(/getfavorites/) != -1 && re.exec($j.cookie('Tablespoon_UserName')) != null) {
				block += "<a href=\"#\" class=\"";
				block += "list_saved_recipes";
				block += "\" onclick=\"";
				block += "$j.getJSON('/webservice/ajax.aspx?method=removeFavoriteRecipe&recipe=" + data.recipeId + "'); removeMySavedRecipe('" + data.recipeId + "'); removeRecipeFromList(this, '.count-saved'); updateRecipeBoxCount(-1); return false;";
				block += "\">Remove</a>";
            }
            else if (_this._method.search(/getmyrecipes&drafts=1/) != -1) {
                var publishable = (data.isPublishable != null && data.isPublishable);
                
                block += "<a href=\"javascript:void(0)\" class=\"";
				block += "list_drafts_edit";
				block += "\" onclick=\"";
				block += "javascript:self.location.href = '" + data.detailUrl.replace("recipes/", "recipes/edit/") + "';";
				block += "\" style='top: " + (publishable ? "-55px" : "-35px" ) + "'>Edit</a>";
				
				block += "<a href=\"javascript:void(0)\" class=\"";
				block += "list_drafts_delete";
				block += "\" onclick=\"";
				block += "if(confirm('Are you sure you want to delete this recipe? This cannot be undone.')){ $j.get('/webservice/ajax.aspx?method=deleteRecipe&recipe=" + data.recipeId + "'); removeMySavedRecipe('" + data.recipeId + "'); removeRecipeFromList(this);} return false;";
				block += "\" style='top: " + (publishable ? "-35px" : "-15px" ) + "'>Delete</a>";
				
				if (publishable)
				{
				    block += "<a href=\"javascript:void(0)\" class=\"";
				    block += "list_drafts_publish";
				    block += "\" onclick=\"";
				    block += "javascript:parseDraft(this); $j.get('/webservice/recipes.asmx/PublishDraft?recipeid=" + data.recipeId + "', function() { " + $j("div.recipe-tab")[1].id + "_refresh(); " + $j("div.recipe-tab")[2].id + "_refresh(); $j('a.publish-trigger').click(); });";
				    
				    block += "\">Publish</a>";
                }
			}
            else if (_this._method.search(/getmyrecipes/) != -1 && ure.exec($j.cookie('Tablespoon_UserName')) != null) {
                block += "<a href=\"#\" class=\"";
                block += "list_my_recipes";
                block += "\" onclick=\"";
                block += "if(confirm('Are you sure you want to delete this recipe? This cannot be undone.')){ $j.get('/webservice/ajax.aspx?method=deleteRecipe&recipe=" + data.recipeId + "'); removeMySavedRecipe('" + data.recipeId + "'); removeRecipeFromList(this, '.count-shared');} return false;";
                block += "\">Delete</a>";
            }
            //}
        }

        block += "</span></div>";
        block += "<div class=\"clear\"><!--ie--></div></li>";
        $j(container).append(block);
    }

    this.moveToTop = function() {
        if ($j("html, body").scrollTop() > $j(_this._resultsContainer.parent()).offset().top)
            $j("html, body").animate({ scrollTop: $j(_this._resultsContainer.parent()).offset().top - 80 }, 400);
    }
    
    /*
    Updates the paging controls with the correct page numbers.
    Adds handlers to forward/next buttons.
    */
    this.updatePaging = function(resultCount, elements, currentPage) {
       
        currentPage = currentPage - 0;
        var numpages = Math.ceil(resultCount / _this._itemsPerPage);
        var pagesLeft = Math.min(5, numpages - currentPage);

        $j.each(elements, function(i, obj) {
            $j(obj).children("a").remove();
            
            if (numpages > 1) {
               
                for (var pc = Math.max(Math.min(10, numpages), pagesLeft + currentPage); pc > (Math.max(0, currentPage - (10 - pagesLeft))); pc--) {
                    (function(idx, currpage) {
                    var url = $j(($j(obj).attr("hashLinks") == "true" ? "<a href=\"#pg=" : "<a href=\"?page=") + idx + "&" + _this._searchQuery + "\">" + idx + "</a> ").click(
                        _this._addHistory ? function(e) { e.preventDefault(); $j.historyLoad("pg=" + idx + "&" + _this._searchQuery); _this.moveToTop(); } : function(e) { e.preventDefault(); _this.genRecipeTab("pg=" + idx + "&" + _this._searchQuery); _this.moveToTop(); });
                        if (idx == currpage)
                            url = url.addClass("current");
                        $j(obj).prepend(url);
                    })(pc, currentPage);
                }
            }
        });
        (function(pn) {
        if (resultCount > _this._itemsPerPage) {
                if (_this._addHistory) {
                    $j(_this._pagingContainers).find(".imgNext").unbind("click").click(function(e) { e.preventDefault(); $j.historyLoad("pg=" + Math.min(pn + 1, Math.ceil(resultCount / _this._itemsPerPage)) + "&" + _this._searchQuery); _this.moveToTop(); }).show();
                    $j(_this._pagingContainers).find(".imgPrev").unbind("click").click(function(e) { e.preventDefault(); $j.historyLoad("pg=" + Math.max(1, pn - 1) + "&" + _this._searchQuery); _this.moveToTop(); }).show();
                }
                else {
                    $j(_this._pagingContainers).find(".imgNext").unbind("click").click(function(e) { e.preventDefault(); _this.genRecipeTab("pg=" + Math.min(pn + 1, Math.ceil(resultCount / _this._itemsPerPage)) + "&" + _this._searchQuery); _this.moveToTop(); }).show();
                    $j(_this._pagingContainers).find(".imgPrev").unbind("click").click(function(e) { e.preventDefault(); _this.genRecipeTab("pg=" + Math.max(1, pn - 1) + "&" + _this._searchQuery); _this.moveToTop(); }).show();
                }

            }
            else {
                $j(_this._pagingContainers).find(".imgNext").hide();
                $j(_this._pagingContainers).find(".imgPrev").hide();
            }
        })(currentPage - 0);
    }

    this.sortSearchResults = function(e) {
      
        if (/&sort=/.test(_this._searchQuery))
            _this._searchQuery = _this._searchQuery.replace(/&sort=(.)*&?/, "&sort=" + e + "&");
        else
            _this._searchQuery += "&sort=" + e;
        if (_this._addHistory) {
            $j.historyLoad("pg=1&" + _this._searchQuery);
        }
        else {
            _this.genRecipeTab("pg=1&" + _this._searchQuery);
        }
        _this.moveToTop();
        //$j.getJSON("/webservice/ajax.aspx?" + qs, function(data) { parseRecipes(data, $j(_this._resultsContainer).children(".recipeContainer")); });
        return false;
    }

    this.getUserRecipeRating = function(postId) {
        var ratingString = $j.cookie('Tablespoon_Ratings');

        if (ratingString != null) {
            //alert(postId + "  " + ratingString);
            var aryRatings = ratingString.split(",");
            for (var i in aryRatings) {
                if (aryRatings[i].split("=")[0] == postId) {
                    return aryRatings[i].split("=")[1];
                }
            }
        }
        return -1;
    }
}

function strandsTrackSearch(recipeId, searchString, url) 
{
    if (searchString != null && searchString != '') 
    {
        $j.get('/webservice/ajax.aspx', { method: "strandstracksearched", recipe: recipeId, searchstring: searchString }, function() { window.location.href = url; });
        return false;
    }
}

function truncateText(text, length)
{
    if (text.length > length)
        text = text.substr(0, length) + "...";
    return text;
}

function parseDraft(element)
{
    if ($j(element).parents("li.recipe_block").length > 0)
    {
        var li = $j(element).parents("li.recipe_block")[0];
        if ($j("a.view-my-recipe").length > 0 && $j(li).find("a.recipe-link").length > 0)
            $j("a.view-my-recipe")[0].href = $j(li).find("a.recipe-link")[0].href;
            
        if ($j("div.imagebox img").length > 0 && $j(li).find(".smlimagebox img").length > 0)
        {
            if ($j(li).find(".smlimagebox img")[0].src.match("thumb") == "thumb")
                $j("div.imagebox img")[0].src = $j(li).find(".smlimagebox img")[0].src.replace("_thumb", "");
        }
    }
}

var RecipeResults = new RecipeResultsClass();


