private void UpdateTemplate()
    {
        long template_id = System.Convert.ToInt64(Request.QueryString["id"]);
        SetTitleBarToMessage("lbl update template");
        criteria.AddFilter(Ektron.Cms.Device.CmsDeviceConfigurationProperty.Id, CriteriaFilterOperator.GreaterThanOrEqualTo, "0");
        dList = cDevice.GetList(criteria);

        if (Request.Form["updateTemplate"] == null)
        {
            TemplateData templateData = m_refContentApi.EkContentRef.GetTemplateInfoByID(template_id);
            string templateName = templateData.FileName;
            sitePathValue.Text = "<td class=\"nowrap\">" + m_refContentApi.SitePath + "</td><td class=\"fullWidth\"><input type=\"text\" id=\"updateTemplate\"  maxlength=\"180\" class=\"fullWidth\" name=\"updateTemplate\" value=\"" + templateName + "\"/></td>";
            ltrTemplateDetails.Text = "<tr><td>" + m_refMsg.GetMessage("lbl template name") + ":</td><td></td><td><input id=\"updatetemplateName\" title=\"" + m_refMsg.GetMessage("lbl template name") + "\" maxlength=\"50\" name=\"updatetemplateName\" type=\"text\" value=\"" + templateData.TemplateName + "\"/></td></tr>" +
                "<tr><td>" + m_refMsg.GetMessage("lbl template description") + ":</td><td></td><td><input id=\"updatetemplateDescription\" title=\"" + m_refMsg.GetMessage("lbl template description") + "\" maxlength=\"200\" name=\"updatetemplateDescription\" type=\"text\" value=\"" + templateData.Description + "\"/></td></tr>";
            browsebuttontd.Visible = true;
            cbPageBuilderTemplate.Enabled = true;

            pnlPageBuilder.Visible = true;
            Ektron.Cms.Widget.WidgetTypeModel model = new Ektron.Cms.Widget.WidgetTypeModel();
            Ektron.Cms.Widget.WidgetTypeData[] widgetTypes = model.FindAll();
            repWidgetTypes.DataSource = widgetTypes;
            repWidgetTypes.DataBind();

            Ektron.Cms.PageBuilder.WireframeModel wireframeModel = new Ektron.Cms.PageBuilder.WireframeModel();
            Ektron.Cms.PageBuilder.WireframeData wireframe = wireframeModel.FindByTemplateID(template_id);

            if (wireframe != null)
            {
                Ektron.Cms.Widget.WidgetTypeData[] selectedWidgets = wireframeModel.GetAssociatedWidgetTypes(wireframe.ID);
                //lblThumbnailFileName.Text = wireframe.ThumbnailFile
                List<string> widgetIds = new List<string>();
                foreach (Ektron.Cms.Widget.WidgetTypeData widget in selectedWidgets)
                {
                    widgetIds.Add(widget.ID.ToString());
                }

                ClientScript.RegisterClientScriptBlock(this.GetType(), "pageBuilderSelectedIds", "Ektron.ready(function(){SelectWidgets([" + string.Join(", ", widgetIds.ToArray()) + "]);});", true);

                cbPageBuilderTemplate.Checked = true;
                if (wireframe.Template.SubType == Ektron.Cms.Common.EkEnumeration.TemplateSubType.MasterLayout)
                {
                    browsebuttontd.Visible = false;
                    sitePathValue.Text = "<td class=\"nowrap\">" + templateName + "</td><td class=\"fullWidth\"><input type=\"text\" id=\"updateTemplate\" class=\"masterlayout\" style=\"display:none\" name=\"updateTemplate\" value=\"" + templateName + "\"/></td>";
                    cbPageBuilderTemplate.Enabled = false;
                }
            }

            //Code to show device types
            string valDeviceInputs = "";
            if (m_refContentApi.RequestInformationRef.IsDeviceDetectionEnabled)
            {
                List<DeviceTemplateData> templateDevices = m_refContentApi.EkContentRef.GetTemplateDevicesByID(template_id);
                StringBuilder sb = new StringBuilder();
                if ((dList.Count > 0))
                {
                    Int32 i = 0;
                    sb.Append("<tr>").Append(Environment.NewLine);
                    sb.Append("     <td >").Append(Environment.NewLine);
                    sb.Append("         <br/><label class=\"deviceheader\" for=\"lblDeviceConfiguration\">").Append(m_refMsg.GetMessage("device configuration")).Append("</label>").Append(Environment.NewLine);
                    sb.Append("     </td>").Append(Environment.NewLine);
                    sb.Append("</tr>").Append(Environment.NewLine);
                    foreach (CmsDeviceConfigurationData dItem in dList)
                    {
                        if (dItem.Name != "Generic")
                        {
                            chkID = dItem.Id;
                            DeviceTemplateData deviceMatch = templateDevices.Find(GetDeviceItem);
                            sb.Append("<tr>").Append(Environment.NewLine);
                            sb.Append("     <td class=\"devicelabel\">").Append(Environment.NewLine);
                            if ((deviceMatch != null) && deviceMatch.IsEnabled == true)
                            {
                                sb.Append("     <input type=\"checkbox\" class=\"pageBuilderCheckbox clearfix\" checked=\"checked\" name=\"cbDeviceTemplate_").Append(dItem.Id).Append("\" id=\"cbDeviceTemplate_").Append(dItem.Id).Append("\" />").Append(Environment.NewLine);
                            }
                            else
                            {
                                sb.Append("     <input type=\"checkbox\" class=\"pageBuilderCheckbox clearfix\" name=\"cbDeviceTemplate_").Append(dItem.Id).Append("\" id=\"cbDeviceTemplate_").Append(dItem.Id).Append("\" />").Append(Environment.NewLine);
                            }
                            sb.Append("         <label for=\"addTemplateDevice_").Append(dItem.Id).Append("\">").Append(dItem.Name).Append("</label>").Append(Environment.NewLine);
                            sb.Append("     </td>").Append(Environment.NewLine);
                            sb.Append("     <td class=\"nowrap\">").Append(Environment.NewLine);
                            sb.Append(m_refContentApi.SitePath).Append(Environment.NewLine);
                            sb.Append("     </td>").Append(Environment.NewLine);
                            sb.Append("     <td>").Append(Environment.NewLine);
                            if ((deviceMatch != null))
                            {
                                sb.Append("          <input type=\"text\" id=\"updateDeviceTemplate_").Append(dItem.Id).Append("\"  maxlength=\"180\" class=\"masterlayout\" name=\"updateDeviceTemplate_").Append(dItem.Id).Append("\" value=\"").Append(deviceMatch.FileName).Append("\" />");
                            }
                            else
                            {
                                sb.Append("          <input type=\"text\" id=\"updateDeviceTemplate_").Append(dItem.Id).Append("\"  maxlength=\"180\" class=\"masterlayout\" name=\"updateDeviceTemplate_").Append(dItem.Id).Append("\" value=\"\" />");
                            }
                            sb.Append("     </td>").Append(Environment.NewLine);
                            sb.Append("     <td class=\"value\">").Append(Environment.NewLine);
                            sb.Append("         <input type=\"button\" id=\"btnDeviceTemplate_").Append(dItem.Id).Append("\" value=\"...\" class=\"ektronModal browseButton\" onclick=\"SetBtnClicked(").Append(dItem.Id).Append(");OnBrowseButtonClicked()\" />").Append(Environment.NewLine);
                            sb.Append("     </td>").Append(Environment.NewLine);
                            sb.Append("<tr>").Append(Environment.NewLine);
                            if (i > 0)
                            {
                                valDeviceInputs += "," + dItem.Id;
                            }
                            else
                            {
                                valDeviceInputs += dItem.Id;
                            }
                            i = i + 1;
                        }
                    }
                    ltrDeviceConfigurations.Text = sb.ToString();
                }
            }
            AddBackButton("template_config.aspx?view=list");
            AddButton(m_refContentApi.AppPath + "images/UI/Icons/save.png", "javascript:ConfirmNotEmpty('updateTemplate','" + valDeviceInputs + "');", m_refMsg.GetMessage("lbl update template"), m_refMsg.GetMessage("lbl update template"), "", StyleHelper.SaveButtonCssClass, true);
            AddHelpButton("template_update");
        }
        else
        {
            Ektron.Cms.PageBuilder.WireframeModel wireframeModel = new Ektron.Cms.PageBuilder.WireframeModel();
            Ektron.Cms.PageBuilder.WireframeData wireframe = wireframeModel.FindByTemplateID(template_id);

            if (wireframe != null)
            {
                if (cbPageBuilderTemplate.Checked == true)
                {
                    wireframe.Path = Request.Form["updateTemplate"];
                    wireframe.Template.FileName = wireframe.Path;
                    wireframe.Template.Description = AntiXss.HtmlEncode(Request.Form["updatetemplateDescription"]);
                    wireframe.Template.TemplateName = AntiXss.HtmlEncode(Request.Form["updatetemplateName"]);

                    if (wireframe.Template.SubType == Ektron.Cms.Common.EkEnumeration.TemplateSubType.MasterLayout)
                    {
                        wireframe.Template.Thumbnail = m_templateModel.GenerateThumbnail(wireframe.Template.MasterLayoutID);
                    }
                    else
                    {
                        string tempLocation = string.Empty;
                        if (wireframe.Path.IndexOf("?") != -1)
                        {
                            tempLocation = wireframe.Path.Substring(0, wireframe.Path.IndexOf("?")).ToString();
                        }
                        else
                        {
                            tempLocation = wireframe.Path;
                        }
                        wireframe.Template.Thumbnail = m_templateModel.GenerateThumbnail(tempLocation);
                    }

                    wireframeModel.Update(wireframe);
                    wireframeModel.RemoveAllWidgetTypeAssociations(wireframe.ID);

                    foreach (string Key in Request.Form.AllKeys)
                    {
                        if (Key.StartsWith("widget"))
                        {
                            try
                            {
                                wireframeModel.AddWidgetTypeAssociation(wireframe.ID, long.Parse(Key.Substring(6)));
                            }
                            catch (Exception ex)
                            {
                                EkException.ThrowException(ex);
                            }
                        }
                    }
                }
                else
                {
                    wireframeModel.Remove(wireframe.ID);
                }
            }
            else if (cbPageBuilderTemplate.Checked)
            {
                string strThumbnail = (string)(m_templateModel.GenerateThumbnail(Request.Form["updateTemplate"].ToString()));
                wireframe = wireframeModel.Create(Request.Form["updateTemplate"], template_id, System.IO.Path.GetFileName(strThumbnail), AntiXss.HtmlEncode(Request.Form["updatetemplateDescription"].ToString()), AntiXss.HtmlEncode(Request.Form["updatetemplateName"].ToString()));
                foreach (string Key in Request.Form.AllKeys)
                {
                    if (Key.StartsWith("widget"))
                    {
                        try
                        {
                            wireframeModel.AddWidgetTypeAssociation(wireframe.ID, long.Parse(Key.Substring(6)));
                        }
                        catch (Exception ex)
                        {
                            EkException.ThrowException(ex);
                        }
                    }
                }
            }
            else
            {
                Collection newtemplatedata = new Collection();
                TemplateData updateTemplateData = new TemplateData();
                updateTemplateData.Id = template_id;
                updateTemplateData.FileName = Request.Form["updateTemplate"].ToString();
                updateTemplateData.Description = AntiXss.HtmlEncode(Request.Form["updatetemplateDescription"].ToString());
                updateTemplateData.TemplateName = AntiXss.HtmlEncode(Request.Form["updatetemplateName"].ToString());
                m_refContentApi.EkContentRef.UpdateTemplatev2_0(updateTemplateData);
            }
            if (m_refContentApi.RequestInformationRef.IsDeviceDetectionEnabled)
            {
                SaveDeviceTemplates(dList, template_id, "update");
            }

            Response.Redirect("template_config.aspx?view=list", false);
        }
    }
    private void AddTemplate()
    {
        SetTitleBarToMessage("lbl add new template");

        criteria.AddFilter(Ektron.Cms.Device.CmsDeviceConfigurationProperty.Id, CriteriaFilterOperator.GreaterThanOrEqualTo, "0");
        dList = cDevice.GetList(criteria);

        if (Request.Form["addTemplate"] == null)
        {

            sitePathValue.Text = "<td class=\"nowrap\">" + m_refContentApi.SitePath + "</td><td><input type=\"text\" id=\"addTemplate\" maxlength=\"180\" onkeypress=\"return disableEnterKey(event)\" class=\"ektronInputTextMedium\" name=\"addTemplate\" value=\"\"/></td>";
            ltrTemplateDetails.Text = "<tr><td>" + m_refMsg.GetMessage("lbl template name") + ":</td><td></td><td><input id=\"templateName\" title=\"" + m_refMsg.GetMessage("lbl template name") + "\" maxlength=\"50\" name=\"templateName\" type=\"text\" value=\"\"/></td></tr>" +
                "<tr><td>" + m_refMsg.GetMessage("lbl template description") + ":</td><td></td><td><input id=\"templateDescription\" title=\"" + m_refMsg.GetMessage("lbl template description") + "\" maxlength=\"200\" name=\"templateDescription\" type=\"text\" value=\"\"/></td></tr>";

            pnlPageBuilder.Visible = true;

            Ektron.Cms.Widget.WidgetTypeController.SyncWidgetsDirectory(m_refContentApi.RequestInformationRef.WidgetsPath);

            Ektron.Cms.Widget.WidgetTypeModel model = new Ektron.Cms.Widget.WidgetTypeModel();
            Ektron.Cms.Widget.WidgetTypeData[] widgetTypes = model.FindAll();
            repWidgetTypes.DataSource = widgetTypes;
            repWidgetTypes.DataBind();

            string valDeviceInputs = "";
            if ((m_refContentApi.RequestInformationRef.IsDeviceDetectionEnabled))
            {
                StringBuilder sb = new StringBuilder();
                if ((dList.Count > 0))
                {
                    Int32 i = 0;
                    sb.Append("<tr>").Append(Environment.NewLine);
                    sb.Append("     <td >").Append(Environment.NewLine);
                    sb.Append("         <br/><label class=\"deviceheader\" for=\"lblDeviceConfiguration\">").Append("Device Configurations").Append("</label>").Append(Environment.NewLine);
                    sb.Append("     </td>").Append(Environment.NewLine);
                    sb.Append("</tr>").Append(Environment.NewLine);

                    foreach (CmsDeviceConfigurationData dItem in dList)
                    {
                        if (dItem.Name != "Generic")
                        {
                            sb.Append("<tr>").Append(Environment.NewLine);
                            sb.Append("     <td class=\"devicelabel\" >").Append(Environment.NewLine);
                            sb.Append("         <input type=\"checkbox\" class=\"pageBuilderCheckbox clearfix\" name=\"cbDeviceTemplate_").Append(dItem.Id).Append("\" id=\"cbDeviceTemplate_").Append(dItem.Id).Append("\" />").Append(Environment.NewLine);
                            sb.Append("         <label for=\"addTemplateDevice_").Append(dItem.Id).Append("\">").Append(dItem.Name).Append("</label>").Append(Environment.NewLine);
                            sb.Append("     </td>").Append(Environment.NewLine);
                            sb.Append("     <td class=\"nowrap\">").Append(Environment.NewLine);
                            sb.Append(m_refContentApi.SitePath).Append(Environment.NewLine);
                            sb.Append("     </td> ").Append(Environment.NewLine);
                            sb.Append("     <td> ").Append(Environment.NewLine);
                            sb.Append("          <input  type=\"text\" id=\"updateDeviceTemplate_").Append(dItem.Id).Append("\"  maxlength=\"180\" class=\"ektronInputTextMedium\" name=\"updateDeviceTemplate_").Append(dItem.Id).Append("\" value=\"\" />");
                            sb.Append("     </td>").Append(Environment.NewLine);
                            sb.Append("     <td class=\"value\">").Append(Environment.NewLine);
                            sb.Append("         <input type=\"button\" id=\"btnDeviceTemplate_").Append(dItem.Id).Append("\" value=\"...\" class=\"ektronModal browseButton\" onclick=\"SetBtnClicked(").Append(dItem.Id).Append(");OnBrowseButtonClicked()\" />").Append(Environment.NewLine);
                            sb.Append("     </td>").Append(Environment.NewLine);
                            sb.Append("</tr>").Append(Environment.NewLine);
                            if (i > 0)
                            {
                                valDeviceInputs += "," + dItem.Id;
                            }
                            else
                            {
                                valDeviceInputs += dItem.Id;
                            }
                            i = i + 1;
                        }
                    }
                    ltrDeviceConfigurations.Text = sb.ToString();
                }
            }
            AddButton(m_refContentApi.AppPath + "images/UI/Icons/cancel.png", "javascript:CancelAddTemplate();", m_refMsg.GetMessage("btn cancel"), m_refMsg.GetMessage("btn cancel"), "", StyleHelper.CancelButtonCssClass, true);
            AddButton(m_refContentApi.AppPath + "images/UI/Icons/save.png", "javascript:ConfirmNotEmpty('addTemplate','" + valDeviceInputs + "');", m_refMsg.GetMessage("lbl Add New Template to System"), m_refMsg.GetMessage("lbl Add New Template to System"), "", StyleHelper.SaveButtonCssClass, true);
            AddHelpButton("template_add");

        }
        else
        {
            long template_id = 0;
            string strThumbnail = "";
            string strLocation = "";
            if (Request.Form["addtemplate"].IndexOf("?") != -1)
            {
                strLocation = (string)(Request.Form["addTemplate"].Substring(0, System.Convert.ToInt32(Request.Form["addtemplate"].IndexOf("?"))).ToString());
            }
            else
            {
                strLocation = (string)(Request.Form["addTemplate"].ToString());
            }
            strThumbnail = (string)(m_templateModel.GenerateThumbnail(strLocation));

            if (cbPageBuilderTemplate.Checked)
            {
                Ektron.Cms.PageBuilder.WireframeModel model = new Ektron.Cms.PageBuilder.WireframeModel();
                Ektron.Cms.PageBuilder.WireframeData wireframe = model.Create(Request.Form["addTemplate"].ToString(), System.IO.Path.GetFileName(strThumbnail), AntiXss.HtmlEncode(Request.Form["templateDescription"].ToString()), AntiXss.HtmlEncode(Request.Form["templateName"].ToString()));
                if (wireframe.ID == 0)
                {
                    Utilities.ShowError((string)(m_refMsg.GetMessage("msg template aleady exists")));
                    return;
                }
                foreach (string Key in Request.Form.AllKeys)
                {
                    if (Key.StartsWith("widget"))
                    {
                        try
                        {
                            model.AddWidgetTypeAssociation(wireframe.ID, long.Parse(Key.Substring(6)));
                        }
                        catch (Exception ex)
                        {
                            EkException.ThrowException(ex);
                        }
                    }
                }

                template_id = wireframe.Template.Id;
            }
            else
            {
                Collection newtemplatedata = new Collection();
                newtemplatedata.Add(Request.Form["addTemplate"].ToString(), "TemplateFileName", null, null);
                newtemplatedata.Add(AntiXss.HtmlEncode(Request.Form["templateName"].ToString()), "TemplateName", null, null);
                newtemplatedata.Add(AntiXss.HtmlEncode(Request.Form["templateDescription"].ToString()), "Description", null, null);
                template_id = m_refContentApi.EkContentRef.AddTemplatev2_0(newtemplatedata);
                if (template_id == 0)
                {
                    Utilities.ShowError((string)(m_refMsg.GetMessage("msg template aleady exists")));
                    return;
                }
            }
            if (m_refContentApi.RequestInformationRef.IsDeviceDetectionEnabled)
            {
                SaveDeviceTemplates(dList, template_id, "add");
            }
            ClientScript.RegisterClientScriptBlock(this.GetType(), "windowCloseScript", "AddTemplateEntry(" + template_id + ", \'" + (cbPageBuilderTemplate.Checked ? Request.Form["addTemplate"].ToString().Replace("\'", "\\\'") + " (Wireframe Template)" : Request.Form["addTemplate"].ToString().Replace("\'", "\\\'")) + "\');", true);
            //ClientScript.RegisterClientScriptBlock(this.GetType(), "windowCloseScript", "AddTemplateEntry(" + template_id + ", \'" + Request.Form["addTemplate"].ToString().Replace("\'", "\\\'") + "\');", true);
        }
    }