private static GridPanel GetCategoryPanel(RelationInfo link)
 {
   CategoryItem categoryItem = new CategoryItem(Client.ContentDatabase.GetItem(link.Category));
   GridPanel categoryPanel = new GridPanel();
   string categoryFullName = categoryItem.CategoryName;
   string categoryName = categoryItem.DisplayName;
   categoryPanel.Controls.Add(new Literal(string.Format("{0} ({1:F0}%)", categoryName, link.Weight))
                                {Class = "categoryName"});
   categoryPanel.Controls.Add(
     new Literal(string.Format("{0}",
                               categoryFullName.Substring(0, categoryFullName.Length - categoryName.Length - 1)))
       {Class = "categoryPath"});
   categoryPanel.Attributes["class"] = "categoryPanel";
   return categoryPanel;
 }
        private string RenderToHtml(RenderFieldArgs args) 
        {

          Database db = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
          
          
          CategoryItem categoryItem; 
          
          string rowValue = string.Empty;
          string htmlValue = string.Empty;
          string tagId = string.Empty;
          string tagWeight = string.Empty;
          List<String> listId = new List<String>();
          if(!String.IsNullOrEmpty(args.FieldValue))
          {
            rowValue = args.FieldValue;
            args.RawParameters = rowValue;
            listId.AddRange(rowValue.Split("|".ToCharArray()));
            foreach (string tId in listId)
            {
              string span;
              tagId = StringUtil.GetPrefix(tId, ':');
              tagWeight = StringUtil.GetPostfix(tId, ':');
              if ((tagId != "Null") && (tagId != ID.Null.ToString()))
              {
                categoryItem = new CategoryItem(db.GetItem(new ID(tagId)));
                span = "<span class='tagSet' tagId='" + tagId + "' weightId='" + tagWeight + "' onclick='tag_select(event);' ondblclick='showAlert(\"" + tagId + "\")'>" + categoryItem.CategoryName + "<wbr /></span>;";
              }
              else
              {
                  span = "<span class='tagNotFound' tagId='" + tagId + "'>" + tagWeight + "<wbr /></span>;";
              }
              htmlValue += span; 
            }
             
          }
          return htmlValue;
        }
 protected void SelectTag(ClientPipelineArgs args)
 {
   string tagNotFound = args.Parameters["tagNotFound"];
   if (args.IsPostBack)
   {
     string oldValue = "|" + GetValue() + "|";
     string newValue = oldValue;
     if (!string.IsNullOrEmpty(tagNotFound))
     {
       newValue = newValue.Replace(string.Format("|{0}:{1}|", Sitecore.Data.ID.Null, tagNotFound), "|");
       SetValue(newValue.Trim("|".ToCharArray()));
       SheerResponse.Eval("{0}RemoveTagNotFound('{1}');", scriptBase, tagNotFound);
     }
     if (args.HasResult && args.Result != "undefined")
     {
       Database db = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
       CategoryItem categoryItem = new CategoryItem(db.GetItem(new ID(args.Result)));
       string tagId = categoryItem.ID.ToString();
       string tagValue = categoryItem.CategoryName;
       newValue += string.Format("{0}:{1}|", tagId, "{C1453A1D-9ED2-428A-8BB3-50B4A877BEA7}");
       SetValue(newValue.Trim("|".ToCharArray()));
       SetModified();
       SheerResponse.Eval("{0}SetTag('{1}','{2}');", scriptBase, tagValue, tagId);
     }
     CheckTags();
   }
   else
   {
     UrlString url =
       new UrlString(
         ControlManager.GetControlUrl(new ControlName("Sitecore.Shell.Applications.Taxonomy.Dialogs.TagBrowser")));
     UrlHandle handle = new UrlHandle();
     if (!string.IsNullOrEmpty(tagNotFound))
     {
       handle["tagNotFound"] = tagNotFound;
     }
     handle["categoriesRootId"] = CategoriesRootId;
     handle["value"] = GetValue() ?? string.Empty;
     handle.Add(url);
     SheerResponse.ShowModalDialog(url.ToString(), "650px", "600px", string.Empty, true);
     args.WaitForPostBack();
   }
 }
    public static Dictionary<ID, RelationInfo> GetAllCategories([NotNull] Item item, [NotNull] string value)
    {
      Assert.ArgumentNotNull(item, "item");
      Assert.ArgumentNotNull(value, "value");

      Dictionary<ID, RelationInfo> result;
      if (string.IsNullOrEmpty(value))
      {
        result = GetRecommendedCategories(item).ToDictionary(
          pair => pair.Key, pair => new RelationInfo
          {
              Category = pair.Key,
              RelatedCategory = new List<ID> { ID.Null },
              Calculated = true,
              Weight = Convert.ToSingle(item.Database.GetItem(pair.Value)["Weight"]),
              ConflictCategory = GetConflictIDs(item.Database.GetItem(pair.Value)["ConflictTags"]).ToList()
          });
      }
      else
      {
        result = ClassificationField.Parse(value).ToDictionary(
          pair => pair.Key,
          pair =>
            {
                return new RelationInfo
                  {
                      Category = pair.Key,
                      RelatedCategory = new List<ID> { ID.Null },
                      Calculated = false,
                      Weight = Convert.ToSingle(item.Database.GetItem(pair.Value)["Weight"]),
                      ConflictCategory = GetConflictIDs(item.Database.GetItem(pair.Value)["ConflictTags"]).ToList()
                  };
            });
      }
      var queue = new Queue<RelationInfo>(result.Values);
      while (queue.Count > 0)
      {
        RelationInfo info = queue.Dequeue();
        var innerItem = item.Database.GetItem(info.Category);
        if (innerItem == null)
        {
          continue;
        }

        var category = new CategoryItem(innerItem);
        var parentCategory = category.Parent;
        if (parentCategory == null)
        {
          continue;
        }
        RelationInfo parentInfo;
        if (result.TryGetValue(parentCategory.ID, out parentInfo))
        {

            int entry = parentInfo.RelatedCategory.Count;

            float nWeight = (float)Math.Sqrt(parentCategory.RelatedWithChildren * category.RelatedToParent) *
                                 info.Weight;

            parentInfo.Weight = (float)Math.Pow(parentInfo.Weight, entry);
            parentInfo.Weight = (float)Math.Pow(parentInfo.Weight * nWeight, 1.0 / (entry + 1));

            parentInfo.RelatedCategory.Add(category.ID);

        }
        else
        {
          parentInfo = new RelationInfo
                         {
                           Category = parentCategory.ID,
                           RelatedCategory = new List<ID>{category.ID},
                           Calculated = true,
                           Weight =
                             (float) Math.Sqrt(parentCategory.RelatedWithChildren*category.RelatedToParent)*info.Weight
                         };
          result[parentInfo.Category] = parentInfo;
        }
        queue.Enqueue(parentInfo);
      }
      return result;
    }
    protected override void OK_Click()
    {
      string selected = WebUtil.GetFormValue("categoryTreeview_Selected");
      selected = ShortID.Decode(StringUtil.Mid(selected, 1));
      if (string.IsNullOrEmpty(selected))
      {
        SheerResponse.Alert("Please select a category.");
        return;
      }

      if (Sitecore.Data.ID.IsID(selected))
      {
        UrlHandle handle = UrlHandle.Get();
        Database db = Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database;
        Item selectedItem = db.GetItem(new ID(selected));
        Item rootItem = db.GetItem(new ID(handle["categoriesRootId"]));

        if (selectedItem.TemplateID.ToString() != "{A69C0097-5CE1-435B-99E9-FA2B998D1C70}")
        {      
          string taxValue = handle["value"];
          if (taxValue.Contains(selectedItem.ID.ToString()))
          {
            SheerResponse.Alert("Selected category is already assigned.\nPlease select another category.");
            return;
          }

          if (!string.IsNullOrEmpty(taxValue))
          {
            List<string> conflictCategoryNames = new List<string>();

            List<ID> tagConflicts = TaxonomyEngine.GetConflictTags(selectedItem.ID).ToList();
            if (tagConflicts.Count > 0)
            {
              foreach (ID itemTagId in StringUtil.Split(taxValue, '|', true).Select(id => new ID(StringUtil.GetPrefix(id, ':'))))
              {
                if (tagConflicts.Contains(itemTagId))
                {
                  CategoryItem categoryItem = new CategoryItem(Client.ContentDatabase.GetItem(itemTagId));
                  conflictCategoryNames.Add(categoryItem.CategoryName);
                }
              }
            }

            if (conflictCategoryNames.Count > 0)
            {
              CategoryItem categoryItem = new CategoryItem(selectedItem);

              if (conflictCategoryNames.Count > 3)
              {
                SheerResponse.Alert(
                  string.Format(
                    Messages.CategoryConflictsWithAlreadyAssignedMoreThanThree,
                    categoryItem.CategoryName,
                    StringUtil.Join(conflictCategoryNames.Take(3).Select(categoryName => "  -" + categoryName + "\n"), string.Empty),
                    conflictCategoryNames.Count - 3));
              }
              else
              {
                SheerResponse.Alert(
                string.Format(
                  Messages.CategoryConflictsWithAlreadyAssigned,
                  categoryItem.CategoryName,
                  StringUtil.Join(conflictCategoryNames.Select(categoryName => "  -" + categoryName + "\n"), string.Empty)));
              }
              return;
            }
          }
          SheerResponse.SetDialogValue(selected);
          base.OK_Click();
        }
        else
        {
          SheerResponse.Alert("Please select a category.");
        }
      }
    }
        public static Dictionary <ID, RelationInfo> GetAllCategories([NotNull] Item item, [NotNull] string value)
        {
            Assert.ArgumentNotNull(item, "item");
            Assert.ArgumentNotNull(value, "value");

            Dictionary <ID, RelationInfo> result;

            if (string.IsNullOrEmpty(value))
            {
                result = GetRecommendedCategories(item).ToDictionary(
                    pair => pair.Key, pair => new RelationInfo
                {
                    Category        = pair.Key,
                    RelatedCategory = new List <ID> {
                        ID.Null
                    },
                    Calculated       = true,
                    Weight           = Convert.ToSingle(item.Database.GetItem(pair.Value)["Weight"]),
                    ConflictCategory = GetConflictIDs(item.Database.GetItem(pair.Value)["ConflictTags"]).ToList()
                });
            }
            else
            {
                result = ClassificationField.Parse(value).ToDictionary(
                    pair => pair.Key,
                    pair =>
                {
                    return(new RelationInfo
                    {
                        Category = pair.Key,
                        RelatedCategory = new List <ID> {
                            ID.Null
                        },
                        Calculated = false,
                        Weight = Convert.ToSingle(item.Database.GetItem(pair.Value)["Weight"]),
                        ConflictCategory = GetConflictIDs(item.Database.GetItem(pair.Value)["ConflictTags"]).ToList()
                    });
                });
            }
            var queue = new Queue <RelationInfo>(result.Values);

            while (queue.Count > 0)
            {
                RelationInfo info      = queue.Dequeue();
                var          innerItem = item.Database.GetItem(info.Category);
                if (innerItem == null)
                {
                    continue;
                }

                var category       = new CategoryItem(innerItem);
                var parentCategory = category.Parent;
                if (parentCategory == null)
                {
                    continue;
                }
                RelationInfo parentInfo;
                if (result.TryGetValue(parentCategory.ID, out parentInfo))
                {
                    int entry = parentInfo.RelatedCategory.Count;

                    float nWeight = (float)Math.Sqrt(parentCategory.RelatedWithChildren * category.RelatedToParent) *
                                    info.Weight;

                    parentInfo.Weight = (float)Math.Pow(parentInfo.Weight, entry);
                    parentInfo.Weight = (float)Math.Pow(parentInfo.Weight * nWeight, 1.0 / (entry + 1));

                    parentInfo.RelatedCategory.Add(category.ID);
                }
                else
                {
                    parentInfo = new RelationInfo
                    {
                        Category        = parentCategory.ID,
                        RelatedCategory = new List <ID> {
                            category.ID
                        },
                        Calculated = true,
                        Weight     =
                            (float)Math.Sqrt(parentCategory.RelatedWithChildren * category.RelatedToParent) * info.Weight
                    };
                    result[parentInfo.Category] = parentInfo;
                }
                queue.Enqueue(parentInfo);
            }
            return(result);
        }