//adds a recipe to the recipe box
function AddRecipe(recipeId, categoryId)
{
    //add the recipe normally
    var dataString = '{"recipeId":"' + recipeId + '", "categoryId":' + categoryId + '}';

    CallServiceMethod("/services/RecipeBoxService.asmx/AddToRecipeBox", dataString,
                      function(msg)
                      {
                        jQuery("#divAddToRecipeBox").hide();
                        jQuery("#divDelFromRecipeBox").show();
                      },
                      function(xhr, status, error)
                      {
                        var err = xhr.responseText;
                        document.write(err);
                      }); 
}

// Add a recipe note
function AddRecipeNote(recipeId)
{
    jQuery("#ctl00_cpMain_hdnRecipeId").val(recipeId);
    jQuery("#addRecipeNote").jqmShow();
    jQuery("#txtRecipeNote").empty();
}

// set up the deletion of an individual recipe
function ConfirmRecipeDelete(recipeId, categoryId)
{   
    jQuery("#recipeDeletedFromFolderText").hide();
    jQuery("#recipeDeletedText").hide();
    jQuery("#recipeDeletedContent").hide();
    jQuery("#confirmRecipeDeleteContent").show();

    // writing the html because the jQuery .attr was only working for the first recipe clicked

    //jQuery("#btnDeleteFromFolder").attr("onclick", "MoveRecipe(\"" + recipeId + "\"," + categoryId + ", 1);");
    jQuery("#btnDeleteFromFolder").html('<img src="'+ content_javascriptIMG01 + '" width="151" height="19" alt="' + javascript80 + '" title="' + javascript80 + '" onclick="MoveSingleRecipe(\'' + recipeId + '\', 1);" />');
    //jQuery("#btnDeleteRecipe").attr("onclick", "DeleteRecipeInCategory(\"" + recipeId + "\"," + categoryId + ");");
    jQuery("#btnDeleteRecipe").html('<img src="' + content_javascriptIMG02 +'" width="101" height="19" alt="Delete Recipe" title="Delete Recipe" onclick="DeleteSingleRecipe(\'' + recipeId + '\');" />');
    if(jQuery('#selectedCategoryId').val() == 1)
    {
        jQuery('#content_recipe_deleteActionCopy').html(content_recipeBox43);
        jQuery('#btnDeleteFromFolder').hide();
       
    }   
    else
    {
        jQuery('#content_recipe_deleteActionCopy').html(content_recipeBox10);
        jQuery('#btnDeleteFromFolder').show();
    }
    jQuery("#confirmRecipeDelete").jqmShow();
   
}

// shows the appropriate messages after calling to move a recipe
function MoveSingleRecipe(recipeId, newCategoryId)
{
    MoveRecipe(recipeId, newCategoryId);
    RefreshRecipeBox();    
    RefreshRecipeBoxWidget();    
	jQuery("#recipeDeletedFromFolderText").show();
    jQuery("#recipeDeletedText").hide();
    jQuery("#confirmRecipeDeleteContent").hide();
    jQuery("#recipeDeletedContent").show(); 
}

// shows the appropriate messages after calling to delete a recipe
function DeleteSingleRecipe(recipeId)
{
    DeleteRecipe(recipeId);
    RefreshRecipeBox();
    RefreshRecipeBoxWidget();
	jQuery("#recipeDeletedFromFolderText").hide();
    jQuery("#recipeDeletedText").show();
    jQuery("#confirmRecipeDeleteContent").hide();
    jQuery("#recipeDeletedContent").show(); 
}

//deletes a recipe from the recipe box
function DeleteRecipe(recipeId)
{
    var dataString = '{"recipeId":"' + recipeId + '"}';

    CallServiceMethod("/services/RecipeBoxService.asmx/DeleteFromRecipeBox", dataString,
                      function(msg)
                      {
                        //refresh the recipe box widget and recipe box
                        //RefreshRecipeBoxWidget();
                      },
                      function(xhr, status, error)
                      {
                        var err = xhr.responseText;
                        document.write(err);
                      }); 
                      
    var noteDataString = '{"recipeId":"' + recipeId + '", "recipeNote":""}';
    CallServiceMethod("/services/UserRecipe.asmx/SaveRecipeNote", noteDataString,
				      function(msg)
				      {
				      },
				      function(xhr, status, error)
				      {
					    var err = xhr.responseText;
					    document.write(err);
				      });
}

//deletes a recipe from the recipe box in a specific category
function DeleteRecipeInCategory(recipeId, categoryId)
{
    var dataString = '{"recipeId":"' + recipeId + '", "categoryId":' + categoryId + '}';

    CallServiceMethod("/services/RecipeBoxService.asmx/DeleteFromRecipeBoxInCategory", dataString,
                      function(msg)
                      {
                        //refresh the recipe box widget and recipe box
                        RefreshRecipeBoxWidget();
                        RefreshRecipeBox();
                      },
                      function(xhr, status, error)
                      {
                        var err = xhr.responseText;
                        document.write(err);
                      }); 
}

//moves a recipe from one category to another
function MoveRecipe(recipeId, newCategoryId)
{
    var dataString = '{"recipeId":"' + recipeId + '", "newCategoryId":' + newCategoryId + '}';

    CallServiceMethod("/services/RecipeBoxService.asmx/MoveRecipe", dataString,
                      function(msg)
                      {
                      },
                      function(xhr, status, error)
                      {
                        var err = xhr.responseText;
                        document.write(err);
                      }); 
}

//this code is used to refresh the categories drop down in the "add to recipe box" dialog box.
function RefreshCategoriesList()
{
    CallServiceMethod("/services/RecipeBoxService.asmx/GetCategories", '{}',
        function(msg)
        {
            //create the json array objects using the web service's return value
            var categories = eval("(" + msg.d + ")");

            //empty the folder list before refreshing it
            jQuery("#ddlRBfolder").empty();
            
            //add the items to the select
            jQuery("#ddlRBfolder").append(jQuery("<option></option>").attr("value","1").text(content_Box19));
            for (i = 0; i < categories.length; i++)
            {
                jQuery("#ddlRBfolder").append(jQuery("<option></option>").attr("value",categories[i].categoryId).text(categories[i].categoryName));	    
            }
        },
        function(xhr, status, error)
        {
            var err = xhr.responseText;
            document.write(err);
        });
}

//refreshes the recipe box widget folder list
function RefreshRecipeBoxWidget()
{
    IsUserSignedIn(
        function()
        {
            RefreshRecipeCount();
            CallServiceMethod("/services/RecipeBoxService.asmx/GetCategories", '{}',
                function(msg)
                {
                    //create the json array objects using the web service's return value
                    var categories = eval(msg.d);

                    //empty the folder list before refreshing it
                    jQuery("#ulFolderList").empty();
                    
                    // set the number of folders retrieved to hidden value 
                    jQuery("#hdnNumFolders").val(categories.length);
                    
                    if(categories.length > 0)
                    {
                        // hide the not populated callout
                        jQuery("#MyRecipeBoxNotPopulated").hide();                

                        //add the items to the select
                        for (i = 0; i < categories.length; i++)
                        {
                            jQuery("#ulFolderList").append('<li><a href="/recipeBox.aspx?cat=' + categories[i].categoryId + '">' + categories[i].categoryName + ' (' + categories[i].itemCount + ')</a></li>');
                        }                
                    }
                    else
                    {
                        // show the not populated callout
                        jQuery("#MyRecipeBoxNotPopulated").show();
                    }

                },
                function(xhr, status, error)
                {
                    var err = xhr.responseText;
                    document.write(err);
                });
            jQuery('#pnlRecipeBoxLoggedIn').show();
        },
        function()
        {
            jQuery('#pnlRecipeBoxNotLoggedIn').show();        
        }
    );
}

// sort recipes by name
function sortByName(a, b) {
	var x = a.name.toLowerCase();
	var y = b.name.toLowerCase();
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

// sort recipes by prep time
function sortByPrep(a, b) {
	var x = parseInt(a.prepTime);
	var y = parseInt(b.prepTime);
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByName(a, b)));
}

// sort recipes by servings
function sortByServings(a, b) {
	var x = parseInt(a.servings);
	var y = parseInt(b.servings);
	return ((x < y) ? -1 : ((x > y) ? 1 : sortByName(a, b)));
}

// sort recipes by notes
function sortByNotes(a, b) {
	var x = a.hasNote;
	var y = b.hasNote;
	return ((x > y) ? -1 : ((x < y) ? 1 : sortByName(a, b)));
}

// Refresh the recipes in the recipe box
function RefreshRecipeBox(sortBy)
{
//    jQuery.localise('/js/content');

    var categoryId = jQuery("#selectedCategoryId").val();
    var dataString = '{"categoryId":"' + categoryId + '"}';
    
    CallServiceMethod("/services/RecipeBoxService.asmx/GetRecipeBoxRecipes", dataString,
    function(msg)
    {
        //create the json array objects using the web service's return value
        var recipes = eval(msg.d);
        
        // sort by name by default
        if(!sortBy || sortBy == "sortByName")
        {
            recipes.sort(sortByName);
        }
        else if(sortBy == "sortByPrep")
        {
            recipes.sort(sortByPrep);
        }
        else if(sortBy == "sortByServings")
        {
            recipes.sort(sortByServings);
        }        
        else if(sortBy == "sortByNotes")
        {
            recipes.sort(sortByNotes);
        }          
        
        // empty the div before refreshing
        jQuery("#divRecipes").empty();

        // Display the number of recipes retrieved
        jQuery("#spnRecipeCount").text(recipes.length);
       
        // check how many results per page to show
        var selectedResultsPerPage = jQuery("#ddlResultsControl option:selected").val();        
        
        var pageDivName = "page";
        var currentPage = 1;
        var targetDivName = "divRecipes";
        var currentPageDivId = pageDivName + currentPage;
        
        //draw first page div
        DrawPageDiv("#" + targetDivName, currentPageDivId);
        
        for(var i=0; i < recipes.length; i++)
        {
            var noteActionHtml = "";
            if(recipes[i].hasNote == "true")
            {
                noteActionHtml = "<img class=\"notes\" src=\""+ content_javascriptIMG03 +"\" Width=\"15\" Height=\"15\" /><a  style=\"font-size:11px;\" id=\"toggleNote" + i + "\" href=\"#\" onclick=\"toggleNote(" + i + "); return false;\">" + javascript54 + "<img src=\"" + content_javascriptIMG04 + "\" id=\"RecipeNotesArrow" + i +"\" /></a>";
            }
            else
            {
                noteActionHtml = "<img class=\"notes\" src=\""+ content_javascriptIMG03 +"\" Width=\"15\" Height=\"15\" /><a href=\"#\" id=\"rbAddaRecipeNote" + i + "\" onclick=\"AddRecipeNote('" + recipes[i].recipeId + "');\">" + javascript55 + "</a>";
            }
        
            var spanId = 'spanRecipe' + i;
            var anchorId = 'aRecipe' + i;

            var recipeHtml = '<div class="span-18 last RecipeBoxDisplay" style="margin:0">' +
                '\n<div class="span-1 RecipeBoxCheck marginTop15">' +
                    '\n<input type="checkbox" id="chkRecipe' + i + '" value="' + recipes[i].recipeId + '" />' +
                '\n</div>' +
                '\n<div class="span-4 marginTop15">' +
                    '\n<a href="' + recipes[i].url + '"><img id="recipeImg' + i + '" alt="' + recipes[i].name + '" title="' + recipes[i].name + '" Width="109" Height="74" src="' + recipes[i].imagePath + '" /></a>' +
                '\n</div>' +
                '\n<div class="span-13 borderBottom last">' +
                    '\n<div class="RecipeBoxTitle marginTop15" style="margin-right:0; width:352px; float:left">' +
                        '\n<span style="font-weight:bold;" id="' + spanId + '"></span><br />' +
                        '\n<span class="RecipePrepTotalServings">' + content_Box10 + GetHoursAndMinutes(recipes[i].prepTime) + ' | ' + content_Box11 + GetHoursAndMinutes(recipes[i].totalTime) + ' | ' + content_Box12 + recipes[i].servings + '</span>' + 
                        '\n<span id="noteAction' + i + '" class="font10 marginLeft10">' + noteActionHtml + '</span>' +
						'\n<div id="recipeBoxNotes' + i + '" style="display:none" class="recipeBoxNotes">' + recipes[i].note + '<br/><a href="#" id="editRecipeBoxNote' + i + '" onclick="ShowEditNote(' + i + ');">Edit</a></div>'+
						'\n<div id="editRecipeNote' + i + '" style="display:none;"><textarea id="txtRecipeNote' + i + '" name="txtRecipeNote" onblur="" rows="1" cols="34" class="recipeBoxTextArea">' + recipes[i].note.replace(/<br \/>/g, "\n") + '</textarea><br/><a href="#" id="btnSaveNote' + i + '" onclick="SaveRecipeBoxRecipeNote(\'' + recipes[i].recipeId + '\', ' + i + ');">Save</a></div>'+
                    '\n</div>' +
                        '\n<div class="deleteBG" style="float:left; width:45px; margin-left:6px;">' +
                            '\n<img id="deleteBtn' + i + '" alt="Delete Recipe" title="Delete Recipe" src="' + content_javascriptIMG05 + '" class="btnRecipeBoxDelete hand" onclick="ConfirmRecipeDelete(\'{' + recipes[i].recipeId + '}\', ' + categoryId + ');" />' +
                        '\n</div>' +
                '\n</div>' +
            '\n</div>';

            // append the recipe to the page
            jQuery("#"+currentPageDivId).append(recipeHtml);

            //setup the promo links
            GetRecipeBoxPromotions(recipes[i].recipeId, recipes[i].name, recipes[i].url, spanId, anchorId);
            
            // check if a page break is needed
            if((i+1)%selectedResultsPerPage==0)
            {
                currentPage++;
                currentPageDivId = pageDivName + currentPage;
                DrawPageDiv("#" + targetDivName, currentPageDivId);
            }
        }                
       
        DrawPagination("paginationTop:paginationBtm", recipes.length, selectedResultsPerPage, pageDivName, false);
        
        var selectedPage = jQuery("#selectedPage").val();           
        GoToPage(pageDivName, selectedPage);
    },
    function(xhr, status, error)
    {
        var err = xhr.responseText;
        document.write(err);
    });
    
}

// Get Category Name
function RefreshCategoryBar()
{
//    jQuery.localise('/js/content');
    
    var categoryId = jQuery("#selectedCategoryId").val();
    var dataString = '{"categoryId":"' + categoryId + '"}';

    CallServiceMethod("/services/RecipeBoxService.asmx/GetCategory", dataString,
                      function(msg)
                      {
                        var folderInfo = eval('(' + msg.d + ')');
                        if(folderInfo != null && folderInfo.Name != "")
                        {
                            // set folder name in bar
                            jQuery("#rbFolderName").html(folderInfo.Name);
                            jQuery("#folderNameControls").show();
                            jQuery("#txtRbEditFolderName").attr("value", folderInfo.Name);
                            // set buttons for deleting folder
                            jQuery("#btnKeepRecipes").html('<img src="' + content_javascriptIMG06 + '" width="101" height="19" alt="Keep Recipes" title="Keep Recipes" onclick="MoveRecipesToMain(' + categoryId + ');" />');
                            jQuery("#btnDeleteAll").html('<img src="' + content_javascriptIMG07 + '" width="101" height="19" alt="Delete All" title="Delete All" onclick="DeleteFolder(' + categoryId + ');" />');
                            
                            // set description
                            jQuery("#folderDesc").html(folderInfo.Description);
                            jQuery("#txtRbEditFolderDesc").attr("value", folderInfo.Description);
                            jQuery("#defaultFolderDesc").hide();
                            jQuery("#recipeFolderDescStandard").show();
                        }
                        else
                        {
                            jQuery("#folderNameControls").hide();
                        }
                      },
                      function(xhr, status, error)
                      {
                        var err = xhr.responseText;
                        document.write(err);
                      });  
    
    // if the folder is empty, set the delete folder link to the delete empty folder dialog
    var numRecipesInFolder = jQuery("#spnRecipeCount").text();
    if(numRecipesInFolder == 0)
    {
        jQuery("#btnDeleteEmptyFolder").html('<img src="' + javascript94 + '" width="116" height="19" alt="Delete Folder" title="Delete Folder" onclick="DeleteFolder(' + categoryId + ');" />');    
        jQuery("#delFolder").html('<a href="#" id="delFolder" onclick="jQuery(\'#confirmEmptyFolderDelete\').jqmShow();">' + javascript56 + '</a>');
    }
    else
    {
        jQuery("#delFolder").html('<a href="#" id="delFolder" onclick="jQuery(\'#confirmFolderDelete\').jqmShow();">' + javascript56 + '</a>');
    }
}

// shows the text field to edit the current folder name
function ShowEditFolder()
{
    jQuery("#RecipeBoxBarStandard").hide();
    jQuery("#RecipeBoxBarEdit").show();
}

// shows the text field to edit the current folder name
function ShowEditDesc()
{
    jQuery("#recipeFolderDescStandard").hide();
    jQuery("#recipeFolderDescEdit").show();
}

//deletes a recipe folder from the recipe box
function DeleteFolder(categoryId)
{
    var dataString = '{"categoryId":' + categoryId + '}';

    CallServiceMethod("/services/RecipeBoxService.asmx/DeleteFolder", dataString,
                      function (msg) {
                          var numRecipesInFolder = jQuery("#spnRecipeCount").text();

                          // set the category to the default
                          jQuery("#selectedCategoryId").val("1");
                          //refresh the recipe box widget and recipe box
                          RefreshRecipeBoxWidget();
                          RefreshRecipeBox();
                         
                          // if the folder was empty, update the empty folder delete modal
                          if (numRecipesInFolder == 0) {
                              jQuery("#confirmEmptyFolderDeleteContent").hide();
                              jQuery("#emptyFolderDeletedContent").show();
                          }
                          else {
                              // otherwise update the other modal
                              jQuery("#confirmFolderDeleteContent").hide();
                              jQuery("#folderDeletedText").hide();
                              jQuery("#folderRecipesDeletedText").show();
                              jQuery("#folderDeletedContent").show();
                          }
                          window.location = "/RecipeBox.aspx";
                      },
                      function (xhr, status, error) {
                          var err = xhr.responseText;
                          document.write(err);
                      }); 
}

function LoadRecipeNote(recipeId, codeToExecute)
{
    var dataString = '{"recipeId":"' + recipeId + '"}';

    CallServiceMethod("/services/UserRecipe.asmx/GetRecipeNote", dataString,
        function(msg)
        {
            var details = msg.d;
            codeToExecute(details);
        },
        function(xhr, status, error)
        {
            var err = xhr.responseText;
            document.write(err);
        });  
}

// Show or hide the note div and load the note as appropriate
function PopulateRecipeNote(recipeDivNum, recipeId) 
{
    var noteDivId = "#recipeBoxNotes" + recipeDivNum;
    var noteActionId = "#noteAction" + recipeDivNum; 

    LoadRecipeNote(recipeId, function(details)
    {
        // if the recipe has a note associated
        if(details!="" && details!=null)
        {
            jQuery(noteDivId).html(details + '<br/><a href="#" id="editRecipeBoxNote' + recipeDivNum + '" onclick="ShowEditNote(' + recipeDivNum + ');">Edit</a>');
            jQuery("#txtRecipeNote" + recipeDivNum).val(details);
            var noteActionHtml = "<img ID=\"notes\" src=\"" + content_javascriptIMG09 + "\" Width=\"15\" Height=\"15\" /><a id=\"toggleNote" + recipeDivNum + "\" href=\"#\" onclick=\"toggleNote(" + recipeDivNum + "); return false;\">" + javascript54 + "<img src=\"" + content_javascriptIMG10 + "\" /></a>";
            jQuery(noteActionId).html(noteActionHtml);
        }
        else
        {
            var noteActionHtml = "<a href=\"#\" id=\"rbAddaRecipeNote\" onclick=\"AddRecipeNote('" + recipeId + "');\">" + javascript55 + "</a>";
            jQuery(noteActionId).html(noteActionHtml);
        }
    });
}

// Show or hide the note div and load the note as appropriate
function toggleNote(recipeDivNum) 
{
	var noteArrowID = "#RecipeNotesArrow" + recipeDivNum;
    var noteDivId = "#recipeBoxNotes" + recipeDivNum;

    if(!jQuery(noteDivId).is(':visible'))
    {
        jQuery(noteDivId).show("normal");
        jQuery(noteArrowID).attr('src', content_javascriptIMG11);
    }
    else
    {
        jQuery(noteDivId).hide("normal");        
        jQuery(noteArrowID).attr('src', content_javascriptIMG10);
    }
}

// Check what is selected in the dropdown and execute
function DoRecipeBoxAction()
{
//    jQuery.localise('/js/content');

    var selectedAction = jQuery("#ddlAction option:selected").val();
    if(selectedAction=="Move")
    {
	    var ctr = 0;
	    jQuery("input[id^='chkRecipe']").each(function(){
            if(this.checked)
            {
                ctr++;
            }
	    });
	    if(ctr > 0)
	    {    
            var oldCategoryId = jQuery("#selectedCategoryId").val();
            var newCategoryId = jQuery("#ddlActionModifier").val();
            MoveSelectedRecipes(newCategoryId);
	    }
	    else
	    {
            ShowMessageModal(content_recipeBox40, content_recipeBox41);
	    }
    }
    if(selectedAction=="Delete")
    {
	    var ctr = 0;
	    jQuery("input[id^='chkRecipe']").each(function(){
            if(this.checked)
            {
                ctr++;
            }
	    });
	    if(ctr > 0)
	    {
            jQuery("#recipeDeletedFromFolderText").hide();
            jQuery("#recipeDeletedText").hide();
            jQuery("#recipeDeletedContent").hide();
            jQuery("#confirmRecipeDeleteContent").show();    
        
            // set up the confirmation buttons
            var oldCategoryId = jQuery("#selectedCategoryId").val();
            //jQuery("#btnDeleteFromFolder").attr("onclick", "MoveSelectedRecipes(" + oldCategoryId + ", 1);");
            //jQuery("#btnDeleteRecipe").attr("onclick", "DeleteSelectedRecipes();");

            jQuery("#btnDeleteFromFolder").html('<img src="' + content_javascriptIMG01 + '" width="151" height="19" alt="' + javascript80 + '" title="' + javascript80 + '" onclick="MoveSelectedRecipes(1);" />');
            jQuery("#btnDeleteRecipe").html('<img src="' + content_javascriptIMG02 + '" width="101" height="19" alt="Delete Recipe" title="Delete Recipe" onclick="DeleteSelectedRecipes();" />');
            jQuery("#confirmRecipeDelete").jqmShow();	    
	    }
	    else
	    {
            ShowMessageModal("", content_Box15);
	    }
    }
    if(selectedAction=="ViewNotes")
    {
        ShowAllNotes();
    }
    if(selectedAction=="Sort")
    {
        var sortBy = jQuery("#ddlActionModifier option:selected").val();
        RefreshRecipeBox(sortBy);
    }    
}

function ShowAllNotes()
{
    // IF THIS IS TO ONLY APPLY TO CHECKED RECIPES....
    
//	jQuery("input[id^='chkRecipe']").each(function(){
//        if(this.checked)
//        {
//            //get div num by looking at the id, getting substr after 'chkRecipe'
//            var recipeDivNum = this.id.substr(9);
//            var noteDivId = "#recipeBoxNotes" + recipeDivNum;
//            jQuery(noteDivId).show("normal"); 
//        }
//	});

    // Note: Functionality removed from dropdown per experience design
    var selectedPage = jQuery("#selectedPage").val();
    var pageDivId = "page" + selectedPage;

	jQuery("#" + pageDivId + ", [id^='toggleNote']").each(function(){
        //get div num by looking at the id, getting substr after 'toggleNote'
        var recipeDivNum = this.id.substr(10);
        var noteDivId = "#recipeBoxNotes" + recipeDivNum;
        jQuery(noteDivId).show("normal"); 
	});
}

// Deletes the selected recipes in the recipe box
function DeleteSelectedRecipes()
{
	jQuery("input[id^='chkRecipe']").each(function(){
        if(this.checked)
        {
            //DeleteRecipeInCategory(this.value, jQuery("#selectedCategoryId").val());
            DeleteRecipe(this.value);
        }
	});
    RefreshRecipeBox();	
    RefreshRecipeBoxWidget();
    jQuery("#confirmRecipeDeleteContent").hide();
    jQuery("#recipeDeletedFromFolderText").hide();
    jQuery("#recipeDeletedText").show();
    jQuery("#recipeDeletedContent").show();
    
}

// Moves the selected recipes in the recipe box
function MoveSelectedRecipes(newCategoryId)
{
	jQuery("input[id^='chkRecipe']").each(function(){
        if(this.checked)
        {
            MoveRecipe(this.value, newCategoryId);
        }
	});
    RefreshRecipeBox();
    RefreshRecipeBoxWidget();	
    jQuery("#confirmRecipeDeleteContent").hide();
    jQuery("#recipeDeletedFromFolderText").show();
    jQuery("#recipeDeletedText").hide();
    jQuery("#recipeDeletedContent").show();	
}

// Moves the selected recipes in the recipe box
function MoveRecipesToMain(oldCategoryId)
{
	jQuery("input[id^='chkRecipe']").each(function(){
        MoveRecipe(this.value, 1);        
	});
	RefreshRecipeBox();
	RefreshRecipeBoxWidget();
	DeleteFolder(oldCategoryId);
	jQuery("#confirmFolderDeleteContent").hide();
	jQuery("#folderDeletedText").show();
	jQuery("#folderRecipesDeletedText").hide();
	jQuery("#folderDeletedContent").show();
}

function clearCheckboxes()
{
    jQuery("#pnlRecipeBox :checkbox").each(function(){
        this.checked = false;
    });
}

function RefreshRecipeCount()
{
    var dataString = '{}';

    CallServiceMethod("/services/RecipeBoxService.asmx/GetItemCount", dataString,
        function(msg)
        {
            var recipeCount = msg.d;
            jQuery("#recipeCount").text("(" + recipeCount + ")");
            // if there aren't any recipes, show the no recipes content
            if (recipeCount == 0)
            {
                jQuery("#pnlRecipeBox").hide();
                if (document.location.toString().indexOf("RecipeBox.aspx") >= 0)
                {
                    GetRandomRecipeLinks();
                }
                jQuery("#pnlNoRecipes").show();
            }
            else
            {
                jQuery("#pnlRecipeBox").show();
                jQuery("#pnlNoRecipes").hide();
            }
        },
        function(xhr, status, error)
        {
            var err = xhr.responseText;
            document.write(err);
        });  
}

//updates a recipe folder name
function UpdateFolder()
{
    var dataString = '{"categoryId":"' + jQuery("#selectedCategoryId").val() + '", "categoryName": "' + jQuery("#txtRbEditFolderName").val() + '", "parentCategoryId": "0", "categoryDescription": "' + jQuery("#txtRbEditFolderDesc").val()  + '"}';
    var checkFolderName = jQuery("#aspnetForm").validate().element("#txtRbEditFolderName");
    var checkDesc = jQuery("#aspnetForm").validate().element("#txtRbEditFolderDesc");

    // for some reason the validation on the description isn't working if the field is empty, so also allowing null below
    if((checkFolderName && checkDesc) || (checkFolderName && checkDesc == null))
    {
        CallServiceMethod("/services/RecipeBoxService.asmx/UpdateFolder", dataString,
                          function(msg)
                          {
                            //refresh the recipe box widget and recipe box
                            RefreshRecipeBoxWidget();
                            RefreshRecipeBox();
                            jQuery("#RecipeBoxBarEdit").hide();
                            jQuery("#RecipeBoxBarStandard").show();
                            jQuery("#recipeFolderDescEdit").hide();
                            jQuery("#recipeFolderDescStandard").show();                        
                            RefreshCategoryBar();
                          },
                          function(xhr, status, error)
                          {
                            var err = xhr.responseText;
                            document.write(err);
                          }); 
    }                          
}

// shows the text field to edit the note for the recipe
function ShowEditNote(recipeDivNum)
{
    var noteDivId = "#recipeBoxNotes" + recipeDivNum;
    var noteEditDivId = "#editRecipeNote" + recipeDivNum;
    jQuery(noteDivId).hide();
    jQuery(noteEditDivId).show();
}

function SaveRecipeBoxRecipeNote(recipeId, recipeDivNum)
{
    // validation for editing recipe folder name and description
    jQuery("#aspnetForm").validate().element("#txtRecipeNote" + recipeDivNum);
    jQuery("#txtRecipeNote" + recipeDivNum).rules(
                                            "add", {
						                    maxlength: 500,
                                            messages: {
                                            maxlength: javascript64
                                            }
                                        });
    var validNote = jQuery("#aspnetForm").validate().element("#txtRecipeNote" + recipeDivNum);

    if(validNote)
    {
        var recipeNote = jQuery("#txtRecipeNote" + recipeDivNum).val();
        var noteDivId = "#recipeBoxNotes" + recipeDivNum;
        var noteEditDivId = "#editRecipeNote" + recipeDivNum;
        
        var dataString = '{"recipeId":"' + recipeId + '", "recipeNote":"' + JSONEncode(recipeNote) + '"}';
        CallServiceMethod("/services/UserRecipe.asmx/SaveRecipeNote", dataString,
				          function(msg)
				          {
					        //refresh the note and show it
                            PopulateRecipeNote(recipeDivNum, recipeId);
                            jQuery(noteEditDivId).hide();
                            jQuery(noteDivId).show();

				          },
				          function(xhr, status, error)
				          {
					        var err = xhr.responseText;
					        document.write(err);
				          });    
    }

    // remove the rules so they don't conflict with profile, or others
    jQuery("#txtRecipeNote" + recipeDivNum).rules("remove");
}

function IsRecipeInRecipeBox(InBox, NotInBox)
{
    var recipeId = jQuery("#ctl00_cpMain_hdnRecipeId").val();
    var dataString = '{"recipeId":"' + recipeId + '"}';    
    
    CallServiceMethod("/services/RecipeBoxService.asmx/IsRecipeInRecipeBox", dataString,
                      function(msg)
                      {
                        if(msg.d)
                        {
                            InBox();
                        }
                        else
                        {
                            NotInBox();
                        }
                      },
                      function(xhr, status, error)
                      {
                        var err = xhr.responseText;
                        document.write(err);
                      });    
}

function RBoxWidgetCreateFolder()
{
    ClearValidationErrors();
    var numFolders = jQuery("#hdnNumFolders").val();
    if(numFolders < 12)
    {
        jQuery("#txtCreateFolderName").val("");
        jQuery("#txtCreateFolderDescription").val("");
        jQuery("#recipeBoxCreateFolder").jqmShow();
    }
    else
    {
        jQuery("#mdlMaxFolder").jqmShow();
    }
}	

function GetHoursAndMinutes(totalMinutes)
{
//    jQuery.localise('/js/content');

    var hoursAndMins = "";
    var hours = Math.floor(totalMinutes / 60);
    var minutes = totalMinutes % 60;

    if (hours == 1)
        hoursAndMins += hours + javascript57;
    else if (hours > 1)
        hoursAndMins += hours + javascript58;
    if (minutes == 1)
        hoursAndMins += minutes + javascript59;
    else if (minutes > 1)
        hoursAndMins += minutes + javascript60;

    return hoursAndMins;
}

function GetRandomRecipeLinks()
{
    var dataString = '{}';
    CallServiceMethod("/services/RecipeBoxService.asmx/GetRandomRecipes", dataString,
				      function(msg)
				      {
				        var recipes = eval('(' + msg.d + ')');
				        var otherRecipesHtml = "";
                        for(var i=0; i < recipes.length; i++)
                        {				        
                            otherRecipesHtml += '<a href="' + recipes[i].url + '">' + recipes[i].name + '</a>'; 
                            if(i < recipes.length-1) { otherRecipesHtml += ', '; } 
                        }
                        jQuery("#whatOthersAdded").html(otherRecipesHtml);
				      },
				      function(xhr, status, error)
				      {
					    var err = xhr.responseText;
					    document.write(err);
				      });     
}

