private void editRow(int recordId)
    {
        var obj = new PigeonCms.Shop.ProductItem();
        LblOk.Text = RenderSuccess("");
        LblErr.Text = RenderError("");

        if (!PgnUserCurrent.IsAuthenticated)
            throw new Exception("user not authenticated");

        clearForm();
        clearQuickForm();
        CurrentId = recordId;
        if (CurrentId == 0)
        {
            loadDropCategories(PRODUCT_SECTION); //TODO with settings.
            obj.ItemDate = DateTime.Now;
            obj.ValidFrom = DateTime.Now;
            obj.ValidTo = DateTime.MinValue;
            int defaultCategoryId = 0;
            int.TryParse(DropCategoriesFilter.SelectedValue, out defaultCategoryId);
            obj.CategoryId = defaultCategoryId;
            obj.AttributeSet = 0;
            obj2form(obj);
            LitItemType.Text = obj.ItemTypeName;
            obj.IsDraft = true;
            var currentProd = new ProductItemsManager().Insert(obj);
            this.CurrentId = currentProd.Id;
        }
        else
        {
            obj = new ProductItemsManager(true, true).GetByKey(CurrentId);
            loadDropCategories(obj.SectionId);

            // QUI nascondere le dropdown in più
            hideAttributes(obj.AttributeSet);
            hideAttributes(obj.AttributeSet, true);

            obj2form(obj);
        }
        GridRelated.DataBind();
        GridViewSimple.DataBind();
        MultiView1.ActiveViewIndex = VIEW_INSERT;
    }
    private List<ItemAttributeValue> form2obj(ProductItem obj)
    {
        obj.Id = CurrentId;
        obj.Enabled = ChkEnabled.Checked;
        obj.TitleTranslations.Clear();
        obj.DescriptionTranslations.Clear();
        obj.CategoryId = int.Parse(DropCategories.SelectedValue);
        obj.Alias = TxtAlias.Text;
        obj.CssClass = TxtCssClass.Text;
        obj.ItemDate = this.ItemDate;
        obj.ValidFrom = this.ValidFrom;
        obj.ValidTo = this.ValidTo;

        // product fields

        // Product Type
        int type = 0;
        int.TryParse(DropNew.SelectedValue, out type);
        if (type > 0)
        {
            obj.ProductType = (ProductItem.ProductTypeEnum)type;
        }
        // Attribute Set
        int attributeSetId = 0;
        int.TryParse(DropSets.SelectedValue, out attributeSetId);

        obj.AttributeSet = attributeSetId;

        // Draft
        obj.IsDraft = false;
        // SKU
        obj.SKU = TxtSKU.Text;
        // Regular Price
        decimal regPrice = 0m;
        decimal.TryParse(TxtRegularPrice.Text, out regPrice);
        if (regPrice > 0)
            obj.RegularPrice = regPrice;
        // Sale Price
        decimal salePrice = 0m;
        decimal.TryParse(TxtSalePrice.Text, out salePrice);
        if(salePrice > 0)
            obj.SalePrice = salePrice;
        // Weight
        decimal weight = 0m;
        decimal.TryParse(TxtWeight.Text, out weight);
        if(weight > 0)
            obj.Weight = weight;
        // Qty
        int qty = 0;
        int.TryParse(TxtQty.Text, out qty);
        if (weight > 0)
            obj.Availability = qty;
        // Stock
        int inStock = 0;
        int.TryParse(DropStock.SelectedValue, out inStock);
        if (inStock > 0)
            obj.InStock = (inStock == 1) ? true : false;

        if (CurrentId == 0)
            obj.ItemTypeName = LitItemType.Text;

        foreach (KeyValuePair<string, string> item in Config.CultureList)
        {
            TextBox t1 = new TextBox();
            t1 = (TextBox)PanelTitle.FindControl("TxtTitle" + item.Value);
            obj.TitleTranslations.Add(item.Key, t1.Text);

            var txt2 = new Controls_ContentEditorControl();
            txt2 = Utility.FindControlRecursive<Controls_ContentEditorControl>(this, "TxtDescription" + item.Value);
            obj.DescriptionTranslations.Add(item.Key, txt2.Text);
        }

        foreach(GridViewRow r in GridViewSimple.Rows)
        {
            CheckBox cb = (CheckBox)r.FindControl("chkRow");
            string IdString = r.Cells[5].Text;

            int Id = 0;
            int.TryParse(IdString, out Id);
            var p = new ProductItemsManager().GetByKey(Id);

            if (cb.Checked)
            {
                p.ThreadId = CurrentId;
            }
            else
            {
                if (p.ThreadId == CurrentId )
                    p.ThreadId = p.Id;
            }

            try
            {
                new ProductItemsManager().Update(p);
            }
            catch (Exception e1)
            {
                LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString());
            }

        }

        foreach (GridViewRow r in GridRelated.Rows)
        {
            CheckBox cb = (CheckBox)r.FindControl("chkRow");
            string IdString = r.Cells[5].Text;
            int Id = 0;
            int.TryParse(IdString, out Id);
            var p = new ProductItemsManager().GetByKey(Id);

            if (cb.Checked)
            {
                try
                {
                    new ProductItemsManager().SetRelated(CurrentId, p.Id);
                }
                catch (Exception e1)
                {
                    LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString());
                }
            }
            else
            {
                try
                {
                    new ProductItemsManager().DeleteRelated(CurrentId, p.Id);
                }
                catch (Exception e1)
                {
                    LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString());
                }
            }

        }

        var atts = new List<ItemAttributeValue>();

        // Store ItemAttributeValues

        var set = sman.GetByKey(attributeSetId);

        attributes.Clear();

        foreach (var attributeId in set.AttributesList)
        {
            var attribute = aman.GetByKey(attributeId);
            attributes.Add(attribute);
        }

        foreach (var attribute in attributes)
        {
            if (!attribute.AllowCustomValue)
            {
                DropDownList d1 = new DropDownList();
                d1 = (DropDownList)PanelAttributes.FindControl("DropAttributeValues" + attribute.Name);
                int attributeValueId = 0;
                int.TryParse(d1.SelectedValue, out attributeValueId);
                var record = new ItemAttributeValue();
                record.AttributeId = attribute.Id;
                record.AttributeValueId = attributeValueId;
                record.ItemId = CurrentId;
                atts.Add(record);
            }
            else
            {
                TextBox t1 = new TextBox();
                t1 = (TextBox)QuickAttributes.FindControl("TxtCustomField" + attribute.Name);

                var record = new ItemAttributeValue();
                record.AttributeId = attribute.Id;
                record.AttributeValueId = 0;
                record.CustomValueString = t1.Text;
                record.ItemId = CurrentId;
                atts.Add(record);

            }
        }

        obj.ItemParams = FormBuilder.GetParamsString(obj.ItemType.Params, ItemParams1);
        string fieldsString = FormBuilder.GetParamsString(obj.ItemType.Fields, ItemFields1);
        obj.LoadCustomFieldsFromString(fieldsString);
        PermissionsControl1.Form2obj(obj);

        return atts;
    }
    private bool checkForm()
    {
        LblErr.Text = RenderError("");
        LblOk.Text = RenderSuccess("");
        bool res = true;
        string err = "";

        if (!string.IsNullOrEmpty(TxtAlias.Text))
        {
            var filter = new ProductItemFilter();
            var list = new List<PigeonCms.Shop.ProductItem>();

            filter.Alias = TxtAlias.Text;
            list = new ProductItemsManager().GetByFilter(filter, "");
            if (list.Count > 0)
            {
                if (this.CurrentId == 0)
                {
                    res = false;
                    err += "alias in use<br />";
                }
                else
                {
                    if (list[0].Id != this.CurrentId && this.CurrentId == list[0].Id)
                    {
                        res = false;
                        err += "alias in use<br />";
                    }
                }
            }
        }
        LblErr.Text = RenderError(err);
        return res;
    }
    private bool checkQuickAdd()
    {
        LblErr.Text = RenderError("");
        LblOk.Text = RenderSuccess("");
        bool res = true;
        string err = "";
        var pfilter = new ProductItemFilter();
        var filter = new ItemAttributeValueFilter();
        pfilter.ThreadId = CurrentId;
        pfilter.ShowOnlyRootItems = false;
        var pChilds = new ProductItemsManager(true, true).GetByFilter(pfilter, "");
        foreach (var pChild in pChilds)
        {
            int pId = pChild.Id;
            filter.ItemId = pId;
            var values = man.GetByFilter(filter, "");
            int foundIn = 0,
                presentAttributes = 0;

            // QUI salvo gli attributi quick edit

            foreach (var attribute in attributes)
            {
                if (!attribute.AllowCustomValue)
                {
                    DropDownList d1 = new DropDownList();
                    d1 = (DropDownList)PanelAttributes.FindControl("DropAttributeValuesQuick" + attribute.Name);
                    int attributeValueId = 0;
                    int.TryParse(d1.SelectedValue, out attributeValueId);
                    if (attributeValueId > 0)
                    {
                        presentAttributes++;
                        var exist = values.Exists(x => x.AttributeId == attribute.Id && x.AttributeValueId == attributeValueId);
                        if (exist)
                        {
                            foundIn++;
                        }
                    }
                }
            }
            if (foundIn == presentAttributes)
            {
                res = false;
                err += "Existing variant<br />";
            }
        }
        LblErr.Text = RenderError(err);
        return res;
    }
 protected void ObjDs3_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
 {
     var typename = new ProductItemsManager();
     e.ObjectInstance = typename;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        LblOk.Text = RenderSuccess("");
        LblErr.Text = RenderError("");

        if (this.BaseModule.DirectEditMode)
        {
            if (base.CurrItem.Id == 0)
                throw new ArgumentException();
            if (new ProductItemsManager(true, true).GetByKey(base.CurrItem.Id).Id == 0)
                throw new ArgumentException();
        }

        QuickTxtWeight.Attributes.Add("onclick", "autosuggest(" + TxtWeight.ClientID + ", this )");
        QuickTxtRegularPrice.Attributes.Add("onclick", "autosuggest(" + TxtRegularPrice.ClientID + ", this )");
        QuickTxtSalePrice.Attributes.Add("onclick", "autosuggest(" + TxtSalePrice.ClientID + ", this )");
        QuickTxtQty.Attributes.Add("onclick", "autosuggest(" + TxtQty.ClientID + ", this )");

        if (!Page.IsPostBack)
        {
            loadDropEnabledFilter();
            loadDropCategoriesFilter(PRODUCT_SECTION); // TOTO with settings
            loadDropsItemTypes();
            loadDropSets();
            loadDropProductType();
        }
        else
        {
            string eventArg = HttpContext.Current.Request["__EVENTARGUMENT"];
            if (eventArg == "items")
                Grid1.DataBind();

            //reload params on every postback, because cannot manage dinamically fields
            var currentItem = new ProductItem();
            if (CurrentId > 0)
            {
                currentItem = new ProductItemsManager(true, true).GetByKey(CurrentId);
                ItemParams1.LoadParams(currentItem);
                ItemFields1.LoadFields(currentItem);
            }
            else
            {
                //manually set ItemType
                try
                {
                    currentItem.ItemTypeName = LitItemType.Text;
                    ItemParams1.LoadParams(currentItem);
                    ItemFields1.LoadFields(currentItem);
                }
                catch { }
            }
        }
        if (this.BaseModule.DirectEditMode)
        {
            DropNew.Visible = false;
            BtnNew.Visible = false;
            BtnCancel.OnClientClick = "closePopup();";

            editRow(base.CurrItem.Id);
        }
    }
    protected void ObjDs2_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        //see http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx
        //for use generics with ObjDs TypeName
        var filter = new ProductItemFilter();

        filter.Enabled = Utility.TristateBool.NotSet;
        switch (DropEnabledFilter.SelectedValue)
        {
            case "1":
                filter.Enabled = Utility.TristateBool.True;
                break;
            case "0":
                filter.Enabled = Utility.TristateBool.False;
                break;
            default:
                filter.Enabled = Utility.TristateBool.NotSet;
                break;
        }

        filter.ShowOnlyRootItems = false;

        var main = new ProductItemsManager(true, true).GetByKey(base.CurrentId);
        int setDrop = 0;
        int.TryParse(DropSets.SelectedValue, out setDrop);
        int setId = (main.AttributeSet > 0) ? main.AttributeSet : setDrop;

        filter.ProductType = (int)ProductItem.ProductTypeEnum.Simple;
        filter.AttributeSet = setId;

        e.InputParameters["filter"] = filter;
        e.InputParameters["sort"] = "";
    }
    protected void GridRelated_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var item = new ProductItem();
            item = (ProductItem)e.Row.DataItem;

            if (item.IsThreadRoot)
                lastRowDataboundRoot = e.Row;
            else
            {
                if (lastRowDataboundRoot != null)
                    e.Row.RowState = lastRowDataboundRoot.RowState; //keeps same style of thread root
            }

            if (item.Id == base.CurrentId)
            {
                e.Row.Visible = false;
            }

            var pman = new ProductItemsManager();
            var relatedIds = pman.GetRelatedItems(CurrentId).Select(x => x.Id);

            CheckBox chkRow = (CheckBox)e.Row.FindControl("chkRow");
            if (relatedIds.Contains(item.Id))
            {
                chkRow.Checked = true;
            }

        }
    }
    private void setFlag(int recordId, bool value, string flagName)
    {
        try
        {
            if (!PgnUserCurrent.IsAuthenticated)
                throw new Exception("user not authenticated");

            var o1 = new ProductItemsManager().GetByKey(recordId);
            switch (flagName.ToLower())
            {
                case "enabled":
                    o1.Enabled = value;
                    break;
                default:
                    break;
            }
            new ProductItemsManager().Update(o1);
            removeFromCache();
        }
        catch (Exception e1)
        {
            LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString());
        }
        finally { }
    }
    private bool saveQuickAdd()
    {
        bool res = false;
        LblErr.Text = RenderError("");
        LblOk.Text = RenderSuccess("");
        try
        {
            var o1 = new ProductItem();  //precarico i campi esistenti e nn gestiti dal form
            var a1 = quickform2obj(o1);

            var prod = new ProductItemsManager().Insert(o1);

            // cancello tutti i record con questo itemID
            man.DeleteByItemId(prod.Id);

            foreach (var a in a1)
            {
                a.ItemId = prod.Id;
                man.Insert(a);
            }
            removeFromCache();

            Grid1.DataBind();
            GridViewSimple.DataBind();
            clearQuickForm();
            LblOk.Text = RenderSuccess(Utility.GetLabel("RECORD_SAVED_MSG"));
            res = true;
        }
        catch (CustomException e1)
        {
            if (e1.CustomMessage == ProductItemsManager.MaxItemsException)
                LblErr.Text = RenderError(base.GetLabel("LblMaxItemsReached", "you have reached the maximum number of elements"));
            else
                LblErr.Text = RenderError(e1.CustomMessage);
        }
        catch (Exception e1)
        {
            LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString());
        }
        finally
        {
        }
        return res;
    }
    private bool saveForm()
    {
        bool res = false;
        LblErr.Text = RenderError("");
        LblOk.Text = RenderSuccess("");

        try
        {
            var o1 = new ProductItemsManager().GetByKey(CurrentId);  //precarico i campi esistenti e nn gestiti dal form
            List<ItemAttributeValue> a1 = null;

            a1 = form2obj(o1);
            new ProductItemsManager().Update(o1);

            man.DeleteByItemId(CurrentId);

            foreach (var a in a1)
            {
                man.Insert(a);
            }

            removeFromCache();

            Grid1.DataBind();
            GridViewSimple.DataBind();
            GridRelated.DataBind();
            LblOk.Text = RenderSuccess(Utility.GetLabel("RECORD_SAVED_MSG"));
            res = true;
        }
        catch (CustomException e1)
        {
            if (e1.CustomMessage == ProductItemsManager.MaxItemsException)
                LblErr.Text = RenderError(base.GetLabel("LblMaxItemsReached", "you have reached the maximum number of elements"));
            else
                LblErr.Text = RenderError(e1.CustomMessage);
        }
        catch (Exception e1)
        {
            LblErr.Text = RenderError(Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString());
        }
        finally
        {
        }
        return res;
    }