void SelectClause(ClauseRadio rb1)
        {
            //Find the right panels
            StackPanel spRb = (StackPanel)rb1.Parent;
            StackPanel spCl = (StackPanel)spRb.Parent;
            int els = spCl.Children.IndexOf(spRb);
            StackPanel spEl = (StackPanel)spCl.Children[els + 1];

            //Hide the others
            foreach (Object o in spCl.Children)
            {
                StackPanel sp = (StackPanel)o;
                if ((string)sp.Tag == "elementsp")
                {
                    if (spCl.Children.IndexOf(sp) == els + 1)
                    {
                        sp.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        sp.Visibility = System.Windows.Visibility.Collapsed;
                    }
                }
            }

        }
        public void BuildSideBar(string TemplateId, string TemplateName, string TemplatePlaybookLink)
        {

            Globals.ThisAddIn.ProcessingStart("Build Side Bar");

            try
            {
                Data d = Globals.ThisAddIn.getData();

                _templateid = TemplateId;
                _templateplaybooklink = TemplatePlaybookLink;
                tbTemplateName.Text = TemplateName;

                if (_templateplaybooklink != "")
                {
                    ToolTip tt = new System.Windows.Controls.ToolTip();
                    tt.Content = "Open the Template Playbook link: " + TemplatePlaybookLink;
                    btnTemplatePlaybook.ToolTip = tt;
                }
                else
                {
                    // mark with no link
                    btnTemplatePlaybook.Foreground = new SolidColorBrush(Color.FromRgb(176, 196, 222));
                }


                // if this is an attached doc then to get the order we step through the document
                // and get the controls in order
                // if this is an unattached document then we get the template and get the order from that

                _doc = Globals.ThisAddIn.Application.ActiveDocument;

                Word.Document orderdoc = null;
                Word.Range orderrng = null;

                if (_attachedmode)
                {
                    orderdoc = Globals.ThisAddIn.Application.ActiveDocument;
                    object start = orderdoc.Content.Start;
                    object end = orderdoc.Content.End;
                    orderrng = orderdoc.Range(ref start, ref end);
                }
                else
                {
                    string filename = Utility.SaveTempFile(TemplateId);
                    Globals.ThisAddIn.ProcessingUpdate("Download Template File From SForce");
                    DataReturn orderdr = Utility.HandleData(d.GetTemplateFile(TemplateId, filename));
                    if (!orderdr.success) return;
                    filename = orderdr.strRtn;
                    orderdoc = Globals.ThisAddIn.Application.Documents.Open(filename, Visible: false);
                    object start = orderdoc.Content.Start;
                    object end = orderdoc.Content.End;
                    orderrng = orderdoc.Range(ref start, ref end);
                }

                _clauses = new Dictionary<string, FrameworkElement>();
                _elements = new Dictionary<string, FrameworkElement>();
                //Clear any old ones
                Questions.Children.Clear();

                lbApprovals.Visibility = System.Windows.Visibility.Hidden;
                btnApprovals.Visibility = System.Windows.Visibility.Hidden;
                this.rdTopPanel.Height = new GridLength(85);
                Globals.Ribbons.Ribbon1.Approval(false);

                //Make the default the first one for now
                int num = 0;

                //Get all the clauses and get all the elements at the start
                DataReturn dr = Utility.HandleData(_d.GetTemplateClauses(TemplateId, ""));
                if (!dr.success) return;
                DataTable allclauses = dr.dt;

                //Generate a list of the ClauseIds so we can get all the elemets at one
                //short term solution to cut down on the API calls     
                List<string> clauseids = new List<string>();
                foreach (DataRow r in allclauses.Rows)
                {
                    if (!clauseids.Contains(r["Clause__r_Id"].ToString())) clauseids.Add(r["Clause__r_Id"].ToString());
                }
                string clausefilter = "";
                foreach (string c in clauseids)
                {
                    if (clausefilter == "")
                    {
                        clausefilter = "('" + c + "'";
                    }
                    else
                    {
                        clausefilter += ",'" + c + "'";
                    }
                }
                if (clausefilter != "") clausefilter += ")";

                dr = Utility.HandleData(_d.GetMultipleClauseElements(clausefilter));
                if (!dr.success) return;
                DataTable allelements = dr.dt;


                //Now step through all the Contact Controls and update the XML so we get the newest clauses
                Globals.ThisAddIn.ProcessingUpdate("Step Through Clauses");
                foreach (Word.ContentControl cc in orderrng.ContentControls)
                {
                    if (cc.Tag != null)
                    {
                        string tag = cc.Tag;
                        string[] taga = cc.Tag.Split('|');
                        if (taga[0] == "Concept")
                        {

                            DataRow[] clauses = allclauses.Select("Clause__r_Concept__r_Id='" + Convert.ToString(taga[1]) + "'", "Order__c,Clause__r_Name");

                            string conceptid = "";
                            string conceptname = "";

                            string pbInfo = "";
                            string pbClient = "";

                            if (clauses.Length > 0)
                            {
                                conceptid = Convert.ToString(clauses[0]["Clause__r_Concept__r_Id"]);
                                conceptname = clauses[0]["Clause__r_Concept__r_Name"].ToString();
                                pbInfo = clauses[0]["Clause__r_Concept__r_PlayBookInfo__c"].ToString();
                                pbClient = clauses[0]["Clause__r_Concept__r_PlayBookClient__c"].ToString();
                            }

                            //Add in the Concept Expander


                            Grid gExp = new Grid();
                            Expander newExp = new Expander();
                            newExp.Header = conceptname;
                            newExp.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                            newExp.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xEC, 0xED, 0xED));
                            newExp.Name = "exp" + conceptid;
                            newExp.Tag = conceptid;
                            newExp.IsExpanded = true;

                            int paddingforlockbutton = 30;
                            if (!_attachedmode)
                            {
                                paddingforlockbutton = 6;
                            }

                            Button lExp1 = new Button();
                            Style style = this.FindResource("LinkButton") as Style;
                            lExp1.Style = style;
                            if (pbInfo == "") lExp1.Foreground = new SolidColorBrush(Color.FromRgb(176, 196, 222));
                            lExp1.Margin = new Thickness(0, 8, paddingforlockbutton, 0);
                            lExp1.ToolTip = ConvertHTMLToToolTip(pbInfo);
                            lExp1.Content = "Info";
                            lExp1.Height = 28;

                            PlaybookTag pb = new PlaybookTag();
                            pb.id = conceptid;
                            pb.html = pbInfo;
                            pb.type = "Info";

                            lExp1.Tag = pb;
                            lExp1.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                            lExp1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                            lExp1.Click += new RoutedEventHandler(lExp1_Click);

                            Button lExp2 = new Button();
                            lExp2.Style = style;
                            if (pbClient == "") lExp2.Foreground = new SolidColorBrush(Color.FromRgb(176, 196, 222));
                            lExp2.Margin = new Thickness(0, 8, paddingforlockbutton + 30, 0);
                            lExp2.ToolTip = ConvertHTMLToToolTip(pbClient);
                            lExp2.Content = "Client";

                            pb = new PlaybookTag();
                            pb.id = conceptid;
                            pb.html = pbClient;
                            pb.type = "Client";

                            lExp2.Tag = pb;
                            lExp2.Height = 28;
                            lExp2.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                            lExp2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                            lExp2.Click += new RoutedEventHandler(lExp2_Click);

                            Button unlock = new Button();
                            unlock.Margin = new Thickness(0, 2, 2, 0);
                            unlock.ToolTip = "Unlock Clause";

                            Image icon = new Image();
                            icon.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/AxiomIRISRibbon;component/Resources/locksmall.png", UriKind.Relative));
                            unlock.Content = icon;
                            unlock.Name = "unlock" + conceptid;
                            unlock.Tag = conceptid;
                            unlock.Height = 22;
                            unlock.Width = 22;
                            unlock.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                            unlock.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                            unlock.Click += new RoutedEventHandler(unlock_Click);

                            gExp.Children.Add(newExp);
                            gExp.Children.Add(lExp1);
                            gExp.Children.Add(lExp2);
                            gExp.Children.Add(unlock);

                            // if we are unattached then hide the lock cause it doesn't make that much sense
                            if (!_attachedmode) unlock.Visibility = System.Windows.Visibility.Hidden;


                            StackPanel spCl = new StackPanel();


                            foreach (DataRow r in clauses)
                            {

                                StackPanel spEl = new StackPanel();
                                spEl.Tag = "elementsp";
                                spEl.Margin = new Thickness(35, 5, 5, 5);
                                StackPanel spRb = new StackPanel();
                                spRb.Tag = "rbsp";

                                //Get the XML for this clause                                
                                string xml = "";
                                string clauseid = Convert.ToString(r["Clause__r_Id"]);
                                string lastmodified = Convert.ToString(r["Clause__r_LastModifiedDate"]);
                                lastmodified = lastmodified.Substring(0, 16);

                                // ----- If the Clause is the one in the template/contract then get it from the control if timestamp matches
                                // ----- if the cause is unlocked then it will be set to "Unlocked" and we need to load
                                // ----- otherwise load the clause
                                if (_attachedmode)
                                {
                                    bool selectedclause = false;
                                    if (taga.Length > 3)
                                    {
                                        // clause matches and timestamp or if timestap is set to 0000 which indicates its been loaded
                                        if (taga[2] == clauseid && (lastmodified == taga[3] || taga[3] == "0000"))
                                        {
                                            selectedclause = true;
                                        }
                                    }

                                    if (selectedclause)
                                    {
                                        Globals.ThisAddIn.ProcessingUpdate("Take XML from Doc");
                                        // get the xml from the doc
                                        xml = Globals.ThisAddIn.GetContractClauseXML(_doc, conceptid);
                                    }

                                    if (xml == "")
                                    {

                                        Globals.ThisAddIn.ProcessingUpdate("Get the Clause Template File from SF for:" + r["Clause__r_Name"].ToString());
                                        string filename = Utility.SaveTempFile(clauseid);
                                        filename = Utility.HandleData(_d.GetClauseFile(clauseid, filename)).strRtn;
                                        if (filename == "")
                                        {
                                            xml = "Sorry can't find clause";
                                        }
                                        else
                                        {
                                            //This is the bit that causes the flash - have to open and close the file
                                            Globals.ThisAddIn.Application.ScreenUpdating = false;
                                            Word.Document doc1 = Globals.ThisAddIn.Application.Documents.Open(filename, Visible: false);
                                            xml = doc1.WordOpenXML;
                                            var docclose = (Microsoft.Office.Interop.Word._Document)doc1;
                                            docclose.Close();
                                            Globals.ThisAddIn.Application.ScreenUpdating = true;
                                        }
                                    }
                                }

                                //Approvals - work if we have an approver
                                string desc = r["Clause__r_Description__c"].ToString();
                                string approver = "";
                                if (desc.Contains("Approver:"))
                                {
                                    int i1 = desc.IndexOf("Approver:") + "Approver:".Length;
                                    int i2 = desc.IndexOf("\n", i1);
                                    if (i2 == -1) i2 = desc.Length;
                                    approver = desc.Substring(i1, i2 - i1);
                                }

                                string unlockapprover = "";
                                if (desc.Contains("ApproverFreeText:"))
                                {
                                    int i1 = desc.IndexOf("ApproverFreeText:") + "ApproverFreeText:".Length;
                                    int i2 = desc.IndexOf("\n", i1);
                                    if (i2 == -1) i2 = desc.Length;
                                    unlockapprover = desc.Substring(i1, i2 - i1);
                                }

                                if (unlockapprover == "") unlockapprover = approver;

                                //Approval over ---

                                //Add in the radio button header

                                ClauseRadio rb1 = new ClauseRadio(Convert.ToString(r["Clause__r_Id"]), r["Clause__r_Name"].ToString(), conceptid, conceptname, num, r, xml, lastmodified, approver, false, unlockapprover, desc);
                                rb1.GroupName = conceptname;
                                rb1.Checked += new RoutedEventHandler(rb1_Checked);
                                rb1.GotFocus += new RoutedEventHandler(rb1_GotFocus);
                                spRb.Margin = new Thickness(5, 5, 5, 5);

                                spRb.Children.Add(rb1);



                                //Approvals put in the button ---------------------------------------------------
                                Button ApprovalButton = new Button();
                                ApprovalButton.Margin = new Thickness(2, 2, 2, 0);
                                // ApprovalButton.ToolTip = ConvertHTMLToToolTip(pbInfo);
                                ApprovalButton.Content = "Get Approval";
                                ApprovalButton.Tag = conceptid + "|" + conceptname + "|" + approver;
                                ApprovalButton.Height = 22;
                                ApprovalButton.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                                ApprovalButton.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                                ApprovalButton.Click += new RoutedEventHandler(ApprovalButton_Click);

                                System.Windows.Controls.Label lbl = new System.Windows.Controls.Label();
                                lbl.Content = "This Clause Requires Approval from: " + approver;
                                lbl.Margin = new Thickness(4, 4 + (num * 27), 10, 0);
                                lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                                //lbl.Width = 120;

                                Grid gApproval = new Grid();
                                gApproval.Height = 32;
                                gApproval.Children.Add(lbl);
                                gApproval.Children.Add(ApprovalButton);

                                spEl.Children.Add(gApproval);

                                if (approver == "")
                                {
                                    gApproval.Visibility = System.Windows.Visibility.Collapsed;
                                }
                                //Approvals ---------------------------------------------------


                                //Add in the elements for this clause
                                //dr = _d.GetElements(Convert.ToString(r["Clause__r_Id"]));
                                //if (!dr.success) return;
                                //DataTable elements = dr.dt;

                                DataRow[] elements = allelements.Select("Clause__r_Id='" + Convert.ToString(r["Clause__r_Id"]) + "'");

                                if (elements.Length > 0)
                                {
                                    Globals.ThisAddIn.ProcessingUpdate("Add In Elements");

                                    foreach (DataRow er in elements)
                                    {
                                        //Add in the element control
                                        lbl = new System.Windows.Controls.Label();

                                        string lblstr = er["Element__r_Label__c"].ToString();
                                        if (lblstr == "") lblstr = er["Element__r_Name"].ToString();


                                        /* OLD TEXT BOX ONLY code
                                        TextBox tb = new TextBox();
                                        tb.Height = 23;
                                        tb.Margin = new Thickness(90, 4 + (num * 27), 10, 0);
                                        tb.Name = "tb" + er["Element__r_Name"].ToString();
                                        tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;

                                        string dflt = er["Element__r_DefaultValue__c"].ToString();
                                        if (dflt != "")
                                        {

                                            if (dflt == "=Now")
                                            {
                                                DateTime now = DateTime.Now;
                                                if (er["Element__r_Format__c"].ToString() != "")
                                                {
                                                    tb.Text = now.ToString(er["Element__r_Format__c"].ToString());
                                                }
                                                else
                                                {
                                                    tb.Text = now.ToString("d MMMM yyyy");
                                                }

                                            }
                                            else
                                            {
                                                tb.Text = er["Element__r_DefaultValue__c"].ToString();
                                            }
                                        }
                                        Element e = new Element();
                                        e.docelementid = "";
                                        e.templateelementid = er["Element__r_Id"].ToString();
                                        e.conceptid = Convert.ToString(r["Clause__r_Id"]); //hold the clause so we know what to open if they click
                                        e.templateclauseelementid = Convert.ToString(er["Id"]); //hold this so we don't update the same field when
                                        e.templateelementname = er["Element__r_Name"].ToString();
                                        tb.Tag = e;

                                        tb.TextChanged += new TextChangedEventHandler(element_TextChanged);
                                        tb.GotFocus += new RoutedEventHandler(tb_GotFocus);
                                        Grid g2 = new Grid();
                                        //StackPanel sp2 = new StackPanel();
                                        //g2.Orientation = Orientation.Horizontal;
                                        g2.Height = 32;
                                        g2.Children.Add(lbl);
                                        g2.Children.Add(tb);

                                        spEl.Children.Add(g2);
                                         * */

                                        //------------------- PULL THIS OUT SO IT IS MORE MODULAR! make it easier to add diferent types
                                        lbl.Content = lblstr + ":";
                                        lbl.Margin = new Thickness(4, 4 + (num * 27), 10, 0);
                                        lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                                        lbl.Width = 120;

                                        Grid g2 = new Grid();
                                        g2.Height = 32;

                                        if (er["Element__r_Type__c"].ToString() == "Picklist")
                                        {
                                            ComboBox cb = new ComboBox();
                                            //cb.Width = 200;
                                            cb.Height = 23;

                                            cb.IsEditable = true;
                                            cb.IsTextSearchEnabled = true;

                                            cb.Name = "cb" + er["Element__r_Name"].ToString().Replace(" ", ""); ;
                                            cb.Margin = new Thickness(120, 4 + (num * 27), 10, 0);
                                            cb.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;

                                            string options = er["Element__r_Options__c"].ToString().Replace("\r", "");
                                            string[] entries = options.Split('\n');

                                            cb.ItemsSource = entries;
                                            cb.SelectedValuePath = "Content";
                                            //cb.Tag = er["ID"].ToString() + "|" + er["ClauseElementId"].ToString() + "|" + conceptid + "|";

                                            string dflt = er["Element__r_DefaultValue__c"].ToString();
                                            // if (dflt != "") cb.SelectedItem = dflt;

                                            Element e = new Element();
                                            e.docelementid = "";
                                            e.type = er["Element__r_Type__c"].ToString();
                                            e.controltype = "ComboBox";
                                            e.format = er["Element__r_Format__c"].ToString();
                                            e.templateelementid = er["Element__r_Id"].ToString();
                                            e.conceptid = conceptid; //hold the clause so we know what to open if they click
                                            e.templateclauseelementid = Convert.ToString(er["Id"]); //hold this so we don't update the same field when
                                            e.templateelementname = er["Element__r_Name"].ToString();
                                            e.options = entries;
                                            e.defaultvalue = dflt;
                                            cb.Tag = e;

                                            cb.GotFocus += new RoutedEventHandler(cb_GotFocus);
                                            cb.SelectionChanged += new SelectionChangedEventHandler(cb_SelectionChanged);
                                            cb.LostFocus += new RoutedEventHandler(cb_LostFocus);

                                            _elements.Add(e.templateclauseelementid, cb);

                                            g2.Children.Add(lbl);
                                            g2.Children.Add(cb);


                                        }
                                        else if (er["Element__r_Type__c"].ToString() == "Checkbox")
                                        {
                                            CheckBox cbox = new CheckBox();
                                            //cb.Width = 200;
                                            cbox.Height = 23;

                                            cbox.Name = "cbox" + er["Element__r_Name"].ToString().Replace(" ", "");
                                            cbox.Margin = new Thickness(10, 4 + (num * 27), 10, 0);
                                            cbox.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                                            cbox.Content = lblstr;

                                            string options = er["Element__r_Options__c"].ToString().Replace("\r", "");
                                            string[] entries = options.Split('\n');
                                            string opt1 = "", opt2 = "";
                                            if (entries.Length >= 1) opt1 = entries[0];
                                            if (entries.Length >= 2) opt2 = entries[1];

                                            string dflt = er["Element__r_DefaultValue__c"].ToString().ToLower();
                                            // if (dflt != "")
                                            // {
                                            //     if (dflt == "y" || dflt == "yes" || dflt == "true" || dflt == "t" || dflt == opt1.ToLower())
                                            //     {
                                            //         cbox.IsChecked = true;
                                            //     }
                                            // }



                                            //cbox.Tag = er["ID"].ToString() + "|" + er["ClauseElementId"].ToString() + "|" + conceptid + "|" + opt1 + "|" + opt2 ;                                    
                                            Element e = new Element();
                                            e.docelementid = "";
                                            e.templateelementid = er["Element__r_Id"].ToString();
                                            e.type = er["Element__r_Type__c"].ToString();
                                            e.controltype = "CheckBox";
                                            e.format = er["Element__r_Format__c"].ToString();
                                            e.conceptid = conceptid; //hold the clause so we know what to open if they click
                                            e.templateclauseelementid = Convert.ToString(er["Id"]); //hold this so we don't update the same field when
                                            e.templateelementname = er["Element__r_Name"].ToString();
                                            e.options = entries;
                                            e.option1 = opt1;
                                            e.option2 = opt2;
                                            e.defaultvalue = dflt;
                                            cbox.Tag = e;

                                            cbox.GotFocus += new RoutedEventHandler(cbox_GotFocus);
                                            cbox.Checked += new RoutedEventHandler(cbox_Checked);
                                            cbox.Unchecked += new RoutedEventHandler(cbox_Unchecked);

                                            _elements.Add(e.templateclauseelementid, cbox);

                                            g2.Children.Add(cbox);


                                        }
                                        else if (er["Element__r_Type__c"].ToString() == "Date")
                                        {
                                            DatePicker dp = new DatePicker();
                                            //cb.Width = 200;
                                            dp.Height = 23;

                                            dp.Name = "cb" + er["Element__r_Name"].ToString().Replace(" ", "");
                                            dp.Margin = new Thickness(120, 4 + (num * 27), 10, 0);
                                            dp.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;

                                            string dflt = er["Element__r_DefaultValue__c"].ToString();


                                            Element e = new Element();
                                            e.docelementid = "";
                                            e.type = er["Element__r_Type__c"].ToString();
                                            e.controltype = "DatePicker";
                                            e.format = er["Element__r_Format__c"].ToString();
                                            e.templateelementid = er["Element__r_Id"].ToString();
                                            e.conceptid = conceptid; //hold the clause so we know what to open if they click
                                            e.templateclauseelementid = Convert.ToString(er["Id"]); //hold this so we don't update the same field when
                                            e.templateelementname = er["Element__r_Name"].ToString();
                                            e.defaultvalue = dflt;
                                            dp.Tag = e;

                                            dp.GotFocus += new RoutedEventHandler(dp_GotFocus);
                                            dp.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dp_SelectedDateChanged);
                                            dp.LostFocus += new RoutedEventHandler(dp_LostFocus);

                                            dp.SelectedDateFormat = DatePickerFormat.Long;

                                            _elements.Add(e.templateclauseelementid, dp);

                                            g2.Children.Add(lbl);
                                            g2.Children.Add(dp);


                                        }
                                        else
                                        {
                                            TextBox tb = new TextBox();
                                            //tb.Width = 200;
                                            tb.Height = 23;
                                            tb.Name = "tb" + er["Element__r_Name"].ToString().Replace(" ", "");
                                            tb.Margin = new Thickness(120, 4 + (num * 27), 10, 0);
                                            tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;

                                            string dflt = er["Element__r_DefaultValue__c"].ToString();

                                            //For now the tag is the ElementId|ClauseElementId|ConceptId|Format - fix this when we have proper objects
                                            //tb.Tag = er["ID"].ToString() + "|" + er["ClauseElementId"].ToString() + "|" + conceptid + "|" + er["Format"].ToString();

                                            if (!_elements.ContainsKey(er["Element__r_Id"].ToString()))
                                            {
                                                Element e = new Element();
                                                e.docelementid = "";
                                                e.type = er["Element__r_Type__c"].ToString();
                                                e.controltype = "TextBox";
                                                e.format = er["Element__r_Format__c"].ToString();
                                                e.templateelementid = er["Element__r_Id"].ToString();
                                                e.conceptid = conceptid; //hold the clause so we know what to open if they click
                                                e.templateclauseelementid = Convert.ToString(er["Id"]); //hold this so we don't update the same field when
                                                e.templateelementname = er["Element__r_Name"].ToString();
                                                e.defaultvalue = dflt;

                                                tb.Tag = e;

                                                if (er["Element__r_Type__c"].ToString() == "Number" || er["Element__r_Type__c"].ToString() == "Currency")
                                                {
                                                    if (er["Element__r_Type__c"].ToString() == "Number") tb.PreviewTextInput += new TextCompositionEventHandler(tb_PreviewTextInput);
                                                    tb.TextAlignment = TextAlignment.Right;

                                                }

                                                // tb.Text = FormatElement(e, dflt);

                                                tb.TextChanged += new TextChangedEventHandler(element_TextChanged);
                                                tb.GotFocus += new RoutedEventHandler(tb_GotFocus);
                                                tb.LostFocus += new RoutedEventHandler(tb_LostFocus);



                                                _elements.Add(e.templateclauseelementid, tb);

                                                g2.Children.Add(lbl);
                                                g2.Children.Add(tb);
                                            }


                                        }

                                        spEl.Children.Add(g2);

                                    }

                                }

                                //Push radio button and its elements
                                spCl.Children.Add(spRb);
                                spCl.Children.Add(spEl);

                                if (Convert.ToString(r["Clause__r_Concept__r_Id"]) != conceptid)
                                {
                                    //Push the last concept
                                    newExp.Content = spCl;
                                    Questions.Children.Add(gExp);

                                    //Create the new expando for this object
                                    conceptid = Convert.ToString(r["Clause__r_Concept__r_Id"]);
                                    conceptname = r["Clause__r_Concept__r_Name"].ToString();

                                    lExp1 = new Button();
                                    lExp1.Style = style;
                                    if (pbInfo == "") lExp1.Foreground = new SolidColorBrush(Color.FromRgb(176, 196, 222));
                                    lExp1.Margin = new Thickness(0, 8, 10, 0);
                                    lExp1.ToolTip = ConvertHTMLToToolTip(pbInfo);
                                    lExp1.Content = "Info";
                                    lExp1.Height = 28;

                                    pb = new PlaybookTag();
                                    pb.id = conceptid;
                                    pb.html = pbInfo;
                                    pb.type = "Info";

                                    lExp1.Tag = pb;
                                    lExp1.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                                    lExp1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                                    lExp1.Click += new RoutedEventHandler(lExp1_Click);

                                    lExp2 = new Button();
                                    lExp2.Style = style;
                                    if (pbClient == "") lExp2.Foreground = new SolidColorBrush(Color.FromRgb(176, 196, 222));
                                    lExp2.Margin = new Thickness(0, 8, 40, 0);
                                    lExp2.ToolTip = ConvertHTMLToToolTip(pbClient);
                                    lExp2.Content = "Client";

                                    pb = new PlaybookTag();
                                    pb.id = conceptid;
                                    pb.html = pbClient;
                                    pb.type = "Client";
                                    lExp2.Tag = pb;
                                    lExp2.Height = 28;
                                    lExp2.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                                    lExp2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                                    lExp2.Click += new RoutedEventHandler(lExp2_Click);

                                }

                            }

                            // if Allow None is true then add a "None" selection
                            if (Convert.ToBoolean(clauses[0]["Clause__r_Concept__r_AllowNone__c"]))
                            {
                                StackPanel spElNone = new StackPanel();
                                spElNone.Tag = "elementsp";
                                spElNone.Margin = new Thickness(35, 5, 5, 5);
                                StackPanel spRbNone = new StackPanel();
                                spRbNone.Tag = "rbsp";
                                ClauseRadio rb1 = new ClauseRadio("", "None", conceptid, conceptname, num, null, "", "", "", false, "", "");
                                rb1.GroupName = conceptname;
                                rb1.Checked += new RoutedEventHandler(rb1_Checked);
                                rb1.GotFocus += new RoutedEventHandler(rb1_GotFocus);
                                spRbNone.Margin = new Thickness(5, 5, 5, 5);
                                spRbNone.Children.Add(rb1);
                                //Push radio button and its elements
                                spCl.Children.Add(spRbNone);
                                spCl.Children.Add(spElNone);

                                // put in the approval button even though it'll never get triggered for None
                                // Approvals put in the button ---------------------------------------------------
                                Button ApprovalButton = new Button();
                                ApprovalButton.Margin = new Thickness(2, 2, 2, 0);
                                // ApprovalButton.ToolTip = ConvertHTMLToToolTip(pbInfo);
                                ApprovalButton.Content = "Get Approval";
                                ApprovalButton.Tag = conceptid + "|" + conceptname + "|" + "";
                                ApprovalButton.Height = 22;
                                ApprovalButton.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                                ApprovalButton.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                                ApprovalButton.Click += new RoutedEventHandler(ApprovalButton_Click);

                                System.Windows.Controls.Label lbl = new System.Windows.Controls.Label();
                                lbl.Content = "This Clause Requires Approval from: " + "";
                                lbl.Margin = new Thickness(4, 4 + (num * 27), 10, 0);
                                lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                                //lbl.Width = 120;

                                Grid gApproval = new Grid();
                                gApproval.Height = 32;
                                gApproval.Children.Add(lbl);
                                gApproval.Children.Add(ApprovalButton);

                                spElNone.Children.Add(gApproval);

                                // just hide
                                gApproval.Visibility = System.Windows.Visibility.Collapsed;

                                //Approvals ---------------------------------------------------


                            }

                            //push the last one
                            newExp.Content = spCl;
                            Questions.Children.Add(gExp);
                        }

                    }
                }

                if (!_attachedmode)
                {
                    // Close the template
                    var docclosetemplate = (Microsoft.Office.Interop.Word._Document)orderdoc;
                    docclosetemplate.Close(false);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(docclosetemplate);
                }

                // scroll to the top
                this._doc.Characters.First.Select();
            }
            catch (Exception e)
            {
                string message = "Sorry there has been an error - " + e.Message;
                if (e.InnerException != null) message += " " + e.InnerException.Message;
                MessageBox.Show(message);
                // Globals.ThisAddIn.ProcessingStop("Finished");
            }
        }