Exemple #1
0
        public FoldersWidget(jQueryObject parent, FolderJson[] folders, string folderPath)
        {
            string separator = Environment.ServerType == ServerType.AspNet ? "\\" : "/";
            attachedObject = Template.Get("client", "folders-table", true).AppendTo(parent).Attribute("data-path", folderPath);

            ((List<FolderJson>)(object)folders).Sort(delegate(FolderJson a, FolderJson b)
            {
                return Utility.NaturalCompare(a.name, b.name);
            });

            foreach (FolderJson folder in folders)
            {
                string subfolderPath = folderPath + separator + folder.name;
                jQueryObject row = Template.Get("client", "folders-trow", true).AppendTo(attachedObject.Children());
                jQueryObject btn = jQuery.Select(".folders-btn", row).Click(FolderButtonClick).Attribute("data-path", subfolderPath).Text(folder.count == 0 ? folder.name : String.Format("{0} ({1})", folder.name, folder.count)).Attribute("data-count", folder.count.ToString());
                jQueryObject expandBtn = jQuery.Select(".folders-expand-btn", row).Click(ExpandButtonClick);

                if (folder.subfolders != null && folder.subfolders.Length > 0)
                {
                    expandBtn.Attribute("data-path", subfolderPath).Children().AddClass("icon-plus");
                    new FoldersWidget(jQuery.Select(".folders-tcell", row), folder.subfolders, subfolderPath);
                }
            }

            if (folderPath != "")
            {
                attachedObject.Hide();
                if (Settings.UseAnimation)
                {
                    attachedObject.AddClass("fade");
                }
            }
        }
Exemple #2
0
 public static void Hide(jQueryObject element)
 {
     Script.SetTimeout(delegate()
     {
         element.Hide();
     }, 0);
 }
Exemple #3
0
        private void RejectMatch(jQueryEvent e)
        {
            jQueryObject button  = jQuery.FromElement(e.CurrentTarget);
            string       offerId = button.Siblings("input").GetValue();

            jQueryObject parentRow = button.Parents(".offer");

            parentRow.Attribute("disabled", "disabled").AddClass("ui-state-disabled");

            jQuery.Post("/services/RejectOffer?signed_request=" + Utility.GetSignedRequest(), Json.Stringify(new JsonObject("id", offerId)), (AjaxRequestCallback <object>) delegate(object data, string textStatus, jQueryXmlHttpRequest <object> request)
            {
                parentRow.Hide();

                Utility.ProcessResponse((Dictionary)data);
            });
        }
        public XrmLookupEditor(EditorArguments args) : base(args)
        {
            XrmLookupEditor self = this;

            _args      = args;
            _container = jQuery.FromHtml("<div><table class='inline-edit-container' cellspacing='0' cellpadding='0'><tr><td><INPUT type=text class='sparkle-input-inline' /></td><td class='lookup-button-td'><input type=button class='sparkle-lookup-button' /></td></tr></table></div>");
            _container.AppendTo(_args.Container);

            jQueryObject inputField   = _container.Find(".sparkle-input-inline");
            jQueryObject selectButton = _container.Find(".sparkle-lookup-button");

            _input = inputField;
            _input.Focus().Select();

            _autoComplete = inputField.Plugin <AutoCompleteObject>();

            AutoCompleteOptions options = new AutoCompleteOptions();

            options.Position  = new Dictionary <string, object>("collision", "fit");
            options.MinLength = 100000;
            options.Delay     = 0; // TODO- set to something that makes sense
            XrmLookupEditorOptions editorOptions = (XrmLookupEditorOptions)args.Column.Options;

            bool justSelected = false;

            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                if (_value == null)
                {
                    _value = new EntityReference(null, null, null);
                }

                // Note we assume that the binding has added an array of string items
                AutoCompleteItem item    = (AutoCompleteItem)uiEvent.Item;
                EntityReference  itemRef = (EntityReference)item.Value;
                if (itemRef.LogicalName == "footerlink")
                {
                    XrmLookupEditorButton button = editorOptions.footerButton;
                    button.OnClick(item);
                }
                else
                {
                    string value = item.Label;
                    _input.Value(value);
                    _value.Id          = itemRef.Id;
                    _value.Name        = itemRef.Name;
                    _value.LogicalName = ((EntityReference)item.Value).LogicalName;
                    justSelected       = true;
                }
                Script.Literal("return false;");
            };

            options.Focus = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent)
            {
                // Prevent the value being updated in the text box as we scroll through the results
                Script.Literal("return false;");
            };

            options.Open = delegate(jQueryEvent e, jQueryObject o)
            {
                self._searchOpen = true;
                if (editorOptions.showFooter && totalRecordsReturned > 0)
                {
                    WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", _input, "widget");
                    AddFooter(menu, totalRecordsReturned);
                }
            };

            options.Close = delegate(jQueryEvent e, jQueryObject o)
            {
                self._searchOpen = false;
                WidgetObject menu   = (WidgetObject)Script.Literal("{0}.autocomplete({1})", _input, "widget");
                jQueryObject footer = menu.Next();
                if (footer.Length > 0 || footer.HasClass("sparkle-menu-footer"))
                {
                    footer.Hide();
                }
            };

            // If there multiple names, add them to the columnAttributes
            string[] columns = editorOptions.nameAttribute.Split(",");

            if (columns.Length > 1)
            {
                editorOptions.columns       = columns;
                editorOptions.nameAttribute = columns[0];
            }

            // wire up source to CRM search
            Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response)
            {
                // Get the option set values
                editorOptions.queryCommand(request.Term, delegate(EntityCollection fetchResult)
                {
                    if (fetchResult.TotalRecordCount > fetchResult.Entities.Count)
                    {
                        totalRecordsReturned = fetchResult.TotalRecordCount;
                    }
                    else
                    {
                        totalRecordsReturned = fetchResult.Entities.Count;
                    }

                    int recordsFound             = fetchResult.Entities.Count;
                    bool noRecordsFound          = recordsFound == 0;
                    XrmLookupEditorButton button = editorOptions.footerButton;
                    bool footerButton            = (button != null);

                    AutoCompleteItem[] results = new AutoCompleteItem[recordsFound + (footerButton ? 1 : 0) + (noRecordsFound ? 1 :0)];

                    for (int i = 0; i < recordsFound; i++)
                    {
                        results[i]         = new AutoCompleteItem();
                        results[i].Label   = (string)fetchResult.Entities[i].GetAttributeValue(editorOptions.nameAttribute);
                        EntityReference id = new EntityReference(null, null, null);
                        id.Name            = results[i].Label;
                        id.LogicalName     = fetchResult.Entities[i].LogicalName;
                        id.Id            = (Guid)fetchResult.Entities[i].GetAttributeValue(editorOptions.idAttribute);
                        results[i].Value = id;
                        XrmLookupBinding.GetExtraColumns(editorOptions.columns, fetchResult, results, i);
                        string typeCodeName = fetchResult.Entities[i].LogicalName;

                        // Get the type code from the name to find the icon
                        if (!string.IsNullOrEmpty(editorOptions.typeCodeAttribute))
                        {
                            typeCodeName = fetchResult.Entities[i].GetAttributeValue(editorOptions.typeCodeAttribute).ToString();
                        }

                        if (editorOptions.showImage)
                        {
                            results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName);
                        }
                    }

                    int itemsCount = recordsFound;
                    if (noRecordsFound)
                    {
                        AutoCompleteItem noRecordsItem = new AutoCompleteItem();
                        noRecordsItem.Label            = SparkleResourceStrings.NoRecordsFound;
                        results[itemsCount]            = noRecordsItem;
                        itemsCount++;
                    }

                    if (footerButton)
                    {
                        // Add the add new
                        AutoCompleteItem addNewLink = new AutoCompleteItem();
                        addNewLink.Label            = button.Label;
                        addNewLink.Image            = button.Image;
                        addNewLink.ColumnValues     = null;
                        addNewLink.Value            = new Entity("footerlink");
                        results[itemsCount]         = addNewLink;
                    }
                    response(results);

                    // Disable it now so typing doesn't trigger a search
                    AutoCompleteOptions disableOption = new AutoCompleteOptions();
                    disableOption.MinLength           = 100000;
                    _autoComplete.AutoComplete(disableOption);
                });
            };

            options.Source = queryDelegate;
            inputField     = _autoComplete.AutoComplete(options);
            RenderItemDelegate autoCompleteDelegates = ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField));

            autoCompleteDelegates._renderItem = delegate(object ul, AutoCompleteItem item)
            {
                if (item.Value == item.Label)
                {
                    return((object)jQuery.Select("<li class='ui-state-disabled'>" + item.Label + "</li>").AppendTo((jQueryObject)ul));
                }

                string itemHtml = "<a class='sparkle-menu-item'>";
                // Allow for no image by passing false to 'ShowImage' on the XrmLookupEditorOptions options
                if (item.Image != null)
                {
                    itemHtml += "<span class='sparkle-menu-item-img'><img src='" + item.Image + "'/></span>";
                }
                itemHtml += "<span class='sparkle-menu-item-label'>" + item.Label + "</span><br/>";
                if (item.ColumnValues != null && item.ColumnValues.Length > 0)
                {
                    foreach (string value in item.ColumnValues)
                    {
                        itemHtml += "<span class='sparkle-menu-item-moreinfo'>" + value + "</span>";
                    }
                }
                itemHtml += "</a>";
                return((object)jQuery.Select("<li>").Append(itemHtml).AppendTo((jQueryObject)ul));
            };

            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                AutoCompleteOptions enableOption = new AutoCompleteOptions();
                enableOption.MinLength           = 0;
                _autoComplete.AutoComplete(enableOption);
                _autoComplete.AutoComplete(AutoCompleteMethod.Search, inputField.GetValue());
            });

            // Bind return to searching
            _input.Keydown(delegate(jQueryEvent e)
            {
                if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell
                {
                    if (inputField.GetValue().Length > 0)
                    {
                        selectButton.Click();
                    }
                    else
                    {
                        // Set value to null
                        _value = null;
                        return;
                    }
                }
                else if (e.Which == 13)
                {
                    return;
                }
                if (self._searchOpen)
                {
                    switch (e.Which)
                    {
                    case 9:
                    case 13:     // Return
                    case 38:     // Up - don't navigate - but use the dropdown to select search results
                    case 40:     // Down - don't navigate - but use the dropdown to select search results
                        e.PreventDefault();
                        e.StopPropagation();
                        break;
                    }
                }
                else
                {
                    switch (e.Which)
                    {
                    case 13:     // Return
                        e.PreventDefault();
                        e.StopPropagation();
                        break;
                    }
                }
                justSelected = false;
            });
        }
        public void DataBindEvents(Grid grid, DataViewBase dataView, string gridContainerDivId)
        {
            // Data Sorting
            grid.OnSort.Subscribe(delegate(EventData o, Object item)
            {
                SortColData sorting = (SortColData)item;
                dataView.Sort(sorting);
                grid.Invalidate();
                grid.Render();
            });

            // Session Grid DataBinding
            grid.OnAddNewRow.Subscribe(delegate(EventData o, Object item)
            {
                EditEventData data = (EditEventData)item;
                dataView.AddItem(data.item);


                Column column = data.column;
                grid.InvalidateRow(dataView.GetLength() - 1);

                grid.UpdateRowCount();
                grid.Render();
            });

            dataView.OnRowsChanged.Subscribe(delegate(EventData e, object a)
            {
                OnRowsChangedEventArgs args = (OnRowsChangedEventArgs)a;
                if (args != null && args.Rows != null)
                {
                    grid.InvalidateRows(args.Rows);
                    grid.Render();
                }
                else
                {
                    // Assume that a new row has been added
                    grid.InvalidateRow(dataView.GetLength());
                    grid.UpdateRowCount();
                    grid.Render();
                }
                grid.ResizeCanvas();
            });


            jQueryObject loadingIndicator = null;


            // Wire up the validation error
            jQueryObject validationIndicator = null;
            Action <EventData, object> clearValidationIndicator = delegate(EventData e, object a)
            {
                if (validationIndicator != null)
                {
                    validationIndicator.Hide();
                    validationIndicator.Remove();
                }
            };

            grid.OnCellChange.Subscribe(clearValidationIndicator);
            grid.OnActiveCellChanged.Subscribe(clearValidationIndicator);
            grid.OnBeforeCellEditorDestroy.Subscribe(clearValidationIndicator);

            grid.OnValidationError.Subscribe(delegate(EventData e, object a)
            {
                ValidationEventArgs args          = (ValidationEventArgs)a;
                ValidationResult validationResult = (ValidationResult)args.ValidationResults;
                jQueryObject activeCellNode       = (jQueryObject)args.CellNode;
                object editor       = args.Editor;
                string errorMessage = "";
                if (validationResult.Message != null)
                {
                    errorMessage = validationResult.Message;
                }
                bool valid_result = validationResult.Valid;

                // Add the message to the tooltip on the cell
                if (!valid_result)
                {
                    jQuery.FromObject(activeCellNode).Attribute("title", errorMessage);
                    clearValidationIndicator(e, a);
                    validationIndicator = jQuery.FromHtml("<div class='popup-box-container'><div width='16px' height='16px' class='sparkle-imagestrip-inlineedit_warning popup-box-icon' alt='Error' id='icon'/><div class='popup-box validation-text'/></div>").AppendTo(Document.Body);
                    validationIndicator.Find(".validation-text").Text(errorMessage);

                    string colisionPosition = ValidationPopupUseFitPosition ? "fit fit" : "none none";
                    Script.Literal(@"{0}.position({{
                                            my: 'left bottom',
                                            at: 'left top',
                                            collision: '{2}',
                                            of: {1}
                                        }})
                                        .show({{
                                        effect: 'blind'
                                        }})
                                        .delay( 500000 )
                                        .hide({{
                                            effect: 'fade',
                                            duration: 'slow', 
                                        }},
                                            function() {{
                                                $( this ).remove();
                                                
                                            }});
                                        ", validationIndicator, activeCellNode, colisionPosition);
                }
                else
                {
                    clearValidationIndicator(e, a);
                    jQuery.FromObject(activeCellNode).Attribute("title", "");
                }
            });

            // Wire up the loading spinner
            dataView.OnDataLoading.Subscribe(delegate(EventData e, object a)
            {
                loadingIndicator = ShowLoadingIndicator(loadingIndicator, gridContainerDivId);
                foreach (Column col in grid.GetColumns())
                {
                    if (col.MaxWidth != null)
                    {
                        col.MaxWidth = 400;
                    }
                }
            });

            dataView.OnDataLoaded.Subscribe(delegate(EventData e, object a)
            {
                DataLoadedNotifyEventArgs args = (DataLoadedNotifyEventArgs)a;
                if (args != null)
                {
                    if (args.ErrorMessage == null)
                    {
                        for (int i = args.From; i <= args.To; i++)
                        {
                            grid.InvalidateRow(i);
                        }
                        grid.UpdateRowCount();
                        grid.Render();
                    }
                    else
                    {
                        Script.Alert("There was a problem refreshing the grid.\nPlease contact your system administrator:\n" + args.ErrorMessage);
                    }
                }
                if (loadingIndicator != null)
                {
                    loadingIndicator.Plugin <jQueryBlockUI>().Unblock();
                }
            });

            // Wire up edit complete to property changed
            grid.OnCellChange.Subscribe(delegate(EventData e, object data)
            {
                OnCellChangedEventData eventData = (OnCellChangedEventData)data;
                dataView.RaisePropertyChanged("");
            });
        }
Exemple #6
0
        public override void Init(System.Html.Element element, Func <object> valueAccessor, Func <System.Collections.Dictionary> allBindingsAccessor, object viewModel, object context)
        {
            XrmLookupEditorButton footerButton = (XrmLookupEditorButton)allBindingsAccessor()["footerButton"];
            bool                showFooter     = (bool)allBindingsAccessor()["showFooter"];
            jQueryObject        container      = jQuery.FromElement(element);
            jQueryObject        inputField     = container.Find(".sparkle-input-lookup-part");
            jQueryObject        selectButton   = container.Find(".sparkle-input-lookup-button-part");
            EntityReference     _value         = new EntityReference(null, null, null);
            AutoCompleteOptions options        = new AutoCompleteOptions();

            options.MinLength = 100000; // Don't enable type down - use search button (or return)
            options.Delay     = 0;
            options.Position  = new Dictionary <string, object>("collision", "fit");
            bool justSelected         = false;
            int  totalRecordsReturned = 0;
            Action <AutoCompleteItem, bool> setValue = delegate(AutoCompleteItem item, bool setFocus)
            {
                if (_value == null)
                {
                    _value = new EntityReference(null, null, null);
                }
                string value = item.Label;
                inputField.Value(value);
                _value.Id          = ((Guid)item.Value);
                _value.Name        = item.Label;
                _value.LogicalName = (string)item.Data;
                justSelected       = true;
                TrySetObservable(valueAccessor, inputField, _value, setFocus);
            };

            // Set the value when selected
            options.Select = delegate(jQueryEvent e, AutoCompleteSelectEvent uiEvent)
            {
                // Note we assume that the binding has added an array of string items
                AutoCompleteItem item = (AutoCompleteItem)uiEvent.Item;
                string           data = ((string)item.Data);
                if (data == "footerlink" || data == null)
                {
                    footerButton.OnClick(item);
                    e.PreventDefault();
                    e.StopImmediatePropagation();
                    Script.Literal("return false;");
                }
                else
                {
                    setValue(item, true);
                    Script.Literal("return false;");
                }
            };

            options.Open = delegate(jQueryEvent e, jQueryObject o)
            {
                if (showFooter && totalRecordsReturned > 0)
                {
                    WidgetObject menu = (WidgetObject)Script.Literal("{0}.autocomplete({1})", inputField, "widget");
                    XrmLookupEditor.AddFooter(menu, totalRecordsReturned);
                }
            };

            options.Close = delegate(jQueryEvent e, jQueryObject o)
            {
                WidgetObject menu   = (WidgetObject)Script.Literal("{0}.autocomplete({1})", inputField, "widget");
                jQueryObject footer = menu.Next();
                if (footer.Length > 0 || footer.HasClass("sparkle-menu-footer"))
                {
                    footer.Hide();
                }
            };
            // Get the query command
            Action <string, Action <EntityCollection> > queryCommand = (Action <string, Action <EntityCollection> >)((object)allBindingsAccessor()["queryCommand"]);
            string nameAttribute     = ((string)allBindingsAccessor()["nameAttribute"]);
            string idAttribute       = ((string)allBindingsAccessor()["idAttribute"]);
            string typeCodeAttribute = ((string)allBindingsAccessor()["typeCodeAttribute"]);

            string[] columnAttributes = null;
            // If there multiple names, add them to the columnAttributes
            string[] columns = nameAttribute.Split(",");

            if (columns.Length > 1)
            {
                columnAttributes = columns;
                nameAttribute    = columnAttributes[0];
            }

            // wire up source to CRM search
            Action <AutoCompleteRequest, Action <AutoCompleteItem[]> > queryDelegate = delegate(AutoCompleteRequest request, Action <AutoCompleteItem[]> response)
            {
                Action <EntityCollection> queryCallBack = delegate(EntityCollection fetchResult)
                {
                    int  recordsFound          = fetchResult.Entities.Count;
                    bool noRecordsFound        = recordsFound == 0;
                    AutoCompleteItem[] results = new AutoCompleteItem[recordsFound + (footerButton != null ? 1 : 0) + (noRecordsFound ? 1 : 0)];

                    for (int i = 0; i < recordsFound; i++)
                    {
                        results[i]       = new AutoCompleteItem();
                        results[i].Label = (string)fetchResult.Entities[i].GetAttributeValue(nameAttribute);
                        results[i].Value = fetchResult.Entities[i].GetAttributeValue(idAttribute);
                        results[i].Data  = fetchResult.Entities[i].LogicalName;
                        GetExtraColumns(columnAttributes, fetchResult, results, i);

                        string typeCodeName = fetchResult.Entities[i].LogicalName;
                        // Get the type code from the name to find the icon
                        if (!string.IsNullOrEmpty(typeCodeAttribute))
                        {
                            typeCodeName = fetchResult.Entities[i].GetAttributeValue(typeCodeAttribute).ToString();
                        }

                        results[i].Image = MetadataCache.GetSmallIconUrl(typeCodeName);
                    }

                    if (fetchResult.TotalRecordCount > fetchResult.Entities.Count)
                    {
                        totalRecordsReturned = fetchResult.TotalRecordCount;
                    }
                    else
                    {
                        totalRecordsReturned = fetchResult.Entities.Count;
                    }
                    int itemsCount = recordsFound;
                    if (noRecordsFound)
                    {
                        AutoCompleteItem noRecordsItem = new AutoCompleteItem();
                        noRecordsItem.Label = SparkleResourceStrings.NoRecordsFound;
                        results[itemsCount] = noRecordsItem;
                        itemsCount++;
                    }
                    if (footerButton != null)
                    {
                        // Add the add new
                        AutoCompleteItem addNewLink = new AutoCompleteItem();
                        addNewLink.Label        = footerButton.Label;
                        addNewLink.Image        = footerButton.Image;
                        addNewLink.ColumnValues = null;
                        addNewLink.Data         = "footerlink";
                        results[itemsCount]     = addNewLink;
                    }
                    response(results);

                    // Disable it now so typing doesn't trigger a search
                    AutoCompleteOptions disableOption = new AutoCompleteOptions();
                    disableOption.MinLength = 100000;
                    inputField.Plugin <AutoCompleteObject>().AutoComplete(disableOption);
                };

                // Call the function with the correct 'this' context
                Script.Literal("{0}.call({1}.$parent,{2},{3})", queryCommand, context, request.Term, queryCallBack);
            };

            options.Source = queryDelegate;
            options.Focus  = delegate(jQueryEvent e, AutoCompleteFocusEvent uiEvent)
            {
                // Prevent the value being updated in the text box we scroll through the results
                Script.Literal("return false;");
            };
            inputField = inputField.Plugin <AutoCompleteObject>().AutoComplete(options);

            // Set render template
            ((RenderItemDelegate)Script.Literal("{0}.data('ui-autocomplete')", inputField))._renderItem = delegate(object ul, AutoCompleteItem item)
            {
                if (item.Data == null)
                {
                    return((object)jQuery.Select("<li class='ui-state-disabled'>" + item.Label + "</li>").AppendTo((jQueryObject)ul));
                }

                string html = "<a class='sparkle-menu-item'><span class='sparkle-menu-item-img'>";
                if (item.Image != null)
                {
                    html += @"<img src='" + item.Image + "'/>";
                }
                html += @"</span><span class='sparkle-menu-item-label'>" + item.Label + "</span><br>";

                if (item.ColumnValues != null && item.ColumnValues.Length > 0)
                {
                    foreach (string value in item.ColumnValues)
                    {
                        html += "<span class='sparkle-menu-item-moreinfo'>" + value + "</span>";
                    }
                }
                html += "</a>";
                return((object)jQuery.Select("<li>").Append(html).AppendTo((jQueryObject)ul));
            };

            // Add the click binding to show the drop down
            selectButton.Click(delegate(jQueryEvent e)
            {
                AutoCompleteOptions enableOption = new AutoCompleteOptions();
                enableOption.MinLength           = 0;
                inputField.Focus();
                inputField.Plugin <AutoCompleteObject>().AutoComplete(enableOption);
                inputField.Plugin <AutoCompleteObject>().AutoComplete(AutoCompleteMethod.Search);
            });

            // handle the field changing
            inputField.Change(delegate(jQueryEvent e)
            {
                string inputValue = inputField.GetValue();
                if (inputValue != _value.Name)
                {
                    // The name is different from the name of the lookup reference
                    // search to see if we can auto resolve it
                    TrySetObservable(valueAccessor, inputField, null, false);
                    AutoCompleteRequest lookup = new AutoCompleteRequest();
                    lookup.Term = inputValue;
                    Action <AutoCompleteItem[]> lookupResults = delegate(AutoCompleteItem[] results)
                    {
                        int selectableItems = 0;
                        // If there is only one, then auto-set
                        if (results != null)
                        {
                            foreach (AutoCompleteItem item in results)
                            {
                                if (isItemSelectable(item))
                                {
                                    selectableItems++;
                                }
                                if (selectableItems > 2)
                                {
                                    break;
                                }
                            }
                        }

                        if (selectableItems == 1)
                        {
                            // There is only a single value so set it now
                            setValue(results[0], false);
                        }
                        else
                        {
                            inputField.Value(String.Empty);
                        }
                    };

                    queryDelegate(lookup, lookupResults);
                }
            });

            Action disposeCallBack = delegate()
            {
                if ((bool)Script.Literal("$({0}).data('ui-autocomplete')!=undefined", inputField))
                {
                    Script.Literal("$({0}).autocomplete(\"destroy\")", inputField);
                }
            };

            //handle disposal (if KO removes by the template binding)
            Script.Literal("ko.utils.domNodeDisposal.addDisposeCallback({0}, {1})", element, (object)disposeCallBack);
            Knockout.BindingHandlers["validationCore"].Init(element, valueAccessor, allBindingsAccessor, null, null);

            // Bind return to searching
            inputField.Keydown(delegate(jQueryEvent e)
            {
                if (e.Which == 13 && !justSelected) // Return pressed - but we want to do a search not move to the next cell
                {
                    selectButton.Click();
                }
                else if (e.Which == 13)
                {
                    return;
                }
                switch (e.Which)
                {
                case 13:     // Return
                case 38:     // Up - don't navigate - but use the dropdown to select search results
                case 40:     // Down - don't navigate - but use the dropdown to select search results
                    e.PreventDefault();
                    e.StopPropagation();
                    break;
                }
                justSelected = false;
            });

            //Script.Literal("return { controlsDescendantBindings: true };");
        }
        private void linkFn(dynamic scope, jQueryObject element, object attrs)
        {
            scope["$watch"]("showGrid", new Action(() =>
                                                   {
                                                       if (scope.showGrid)
                                                       {
                                                           element.Show(EffectDuration.Fast);
                                                       }
                                                       else
                                                       {
                                                           element.Hide(EffectDuration.Fast);
                                                       }
                                                   }));

            scope["$watch"]("scale", new Action(() =>
                                                {
                                                    element.Empty();
                                                    var scale = (Point) scope.scale;
                                                    var n = (CanvasElement) Document.CreateElement("canvas");
                                                    var w = scale.X;
                                                    var h = scale.Y;
                                                    n.Width = (int) w + 1;
                                                    n.Height = (int) h + 1;
                                                    var context = (CanvasContext2D) n.GetContext("2d");
                                                    context.StrokeStyle = "#EEEEEE";
                                                    context.LineWidth = 1;
                                                    context.MoveTo(w, 0);
                                                    context.LineTo(w, h);
                                                    context.Stroke();
                                                    context.MoveTo(0, h);
                                                    context.LineTo(w, h);
                                                    context.Stroke();
                                                    var url = (string) ((dynamic) n).toDataURL("image/png");
                                                    element.CSS("background-image", string.Format("url({0})", url));
                                                    element.CSS("background-repeat", "repeat-x repeat-y");
                                                    element.CSS("width", "100%");
                                                    element.CSS("height", "100%");
                                                    element.CSS("margin-left", "auto");
                                                    element.CSS("margin-right", "auto");
                                                    element.CSS("margin-bottom", "auto");
                                                    element.CSS("margin-top", "auto");
                                                    element.ZIndex(-10000);
                                                }), true);
/*
            scope["$watch"]("scale", new Action(() =>
                                                {
                                                    element.Empty();
                                                    var scale = (Point) scope.scale;
                                                    var w = jQueryApi.jQuery.Window.GetWidth();
                                                    var h = jQueryApi.jQuery.Window.GetHeight();

                                                    for (int i = 0; i < (w/scale.X) + 2; i++)
                                                    {
                                                        for (int j = 0; j < (h/scale.Y) + 2; j++)
                                                        {
                                                            element.Append(
                                                                string.Format(
                                                                    "<div style='border:solid 1px black;position:absolute;left:{0}px;top:{1}px;width:{2}px;height:{3}px;'></div>",
                                                                    i*scale.X, j*scale.Y, scale.X, scale.Y));
                                                        }
                                                    }
                                                }), true);
*/
        }