Subversion Repositories SmartDukaan

Rev

Rev 18453 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.catalog.dashboard.client;

import in.shop2020.catalog.dashboard.shared.Item;
import in.shop2020.catalog.dashboard.shared.ItemInventory;
import in.shop2020.catalog.dashboard.shared.ItemWarehouse;
import in.shop2020.catalog.dashboard.shared.SourcePricings;
import in.shop2020.catalog.dashboard.shared.Utils;
import in.shop2020.catalog.dashboard.shared.VendorItemMapping;
import in.shop2020.catalog.dashboard.shared.VendorPricings;
import in.shop2020.catalog.dashboard.shared.VoucherItemMapping;
import in.shop2020.catalog.dashboard.shared.BulkItemPricing;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ResizeComposite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;

/**
 * Panel contains fields for item details. Some of these fields are editable.
 * It also contains vendor item pricings, vendor item keys, and item availability in tabular format.
 * Item availability is made invisible for time being 
 */
public class ItemDetails extends ResizeComposite implements ComingSoon {

        private final int TABLE_INDEX_MAPPING_VENDOR_DESC = 0, 
        TABLE_INDEX_MAPPING_ITEM_KEY = 1,
        TABLE_INDEX_MAPPING_BUTTON = 2,
        TABLE_INDEX_MAPPING_VENDORID = 3, 
        TABLE_INDEX_MAPPING_ITEM_KEY_OLD = 4;

        private final int TABLE_INDEX_PRICING_VENDOR_DESC = 0, 
        TABLE_INDEX_PRICING_MOP = 1,
        TABLE_INDEX_PRICING_DP = 2,
        TABLE_INDEX_PRICING_TP = 3,
        TABLE_INDEX_PRICING_NLC = 4,
        TABLE_INDEX_PRICING_BUTTON = 5,
        TABLE_INDEX_PRICING_VENDORID = 6;

        private final int TABLE_INDEX_SOURCE_PRICING_SOURCE_DESC = 0, 
        TABLE_INDEX_SOURCE_PRICING_MRP = 1,
        TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE = 2,
        TABLE_INDEX_SOURCE_PRICING_BUTTON = 3,
        TABLE_INDEX_SOURCE_PRICING_SOURCE_ID = 4;

        private final int TABLE_INDEX_WAREHOUSE_ID = 0,
        TABLE_INDEX_WAREHOUSE_DESC = 1,
        TABLE_INDEX_WAREHOUSE_INVA = 2,
        TABLE_INDEX_WAREHOUSE_INVR = 3,
        TABLE_INDEX_WAREHOUSE_HELD = 4,
        TABLE_INDEX_WAREHOUSE_EBAY_HELD = 5,
        TABLE_INDEX_WAREHOUSE_SNAPDEAL_HELD = 6,
        TABLE_INDEX_WAREHOUSE_FLIPKART_HELD = 7,
        TABLE_INDEX_WAREHOUSE_HOMESHOP18_HELD = 8,
        TABLE_INDEX_WAREHOUSE_GET_BUTTON = 9,
        TABLE_INDEX_WAREHOUSE_UPDATE_BUTTON = 10;

        private final int TABLE_INDEX_WAREHOUSE_NAME = 0,
        TABLE_INDEX_WAREHOUSE_ADD_DEL_BUTTON = 1;

        private final int TABLE_INDEX_STATE_NAME = 0,
        TABLE_INDEX_STATE_TAX_PERCENTAGE = 1;


        private final int TABLE_INDEX_SIMILAR_ITEMS_CATALOG_ITEM_ID = 0,
        TABLE_INDEX_SIMILAR_ITEMS_PRODUCT_GROUP = 1,
        TABLE_INDEX_SIMILAR_ITEMS_BRAND = 2,
        TABLE_INDEX_SIMILAR_ITEMS_MODEL_NUMBER = 3,
        TABLE_INDEX_SIMILAR_ITEMS_MODEL_NAME = 4,
        TABLE_INDEX_SIMILAR_ITEMS_CATEGORY = 5,
        TABLE_INDEX_SIMILAR_ITEMS_BUTTON = 6;

        private final int TABLE_INDEX_VOUCHERS_TYPE = 0,
        TABLE_INDEX_VOUCHERS_AMOUNT = 1,
        TABLE_INDEX_VOUCHERS_ADD_EDIT_BUTTON = 2,
        TABLE_INDEX_VOUCHERS_DEL_BUTTON = 3;

        private final int TABLE_INDEX_BULK_PRICING_ID=0, 
        TABLE_INDEX_QUANTITY = 1,
        TABLE_INDEX_PRICE = 2,
        TABLE_INDEX_BULK_PRICING_BUTTON =3,
        TABLE_INDEX_BULK_PRICING_REMOVE_BUTTON = 4;

        private final String MANDATORY_MRP = "MRP",
        MANDATORY_WEIGHT = "Weight",
        MANDATORY_BEST_DEAL_TEXT = "Best Deal Text",
        MANDATORY_BEST_DEAL_DETAIL_TEXT = "Best Deal Detail Text",
        MANDATORY_BEST_DEAL_DETAIL_LINK = "Best Deal Detail Link",
        MANDATORY_BRAND = "Brand",
        MANDATORY_MODEL_NO = "Model Number",
        MANDATORY_MODEL_NAME = "Model Name";


        private final String OPTIONAL_SELLING_PRICE = "Selling Price",  
        OPTIONAL_VENDOR_PRICING = "Vendor Pricing",
        OPTIONAL_PREFERRED_VENDOR = "Preferred Vendor",
        OPTIONAL_PREFERRED_INSURER = "Preferred Insurer",
        OPTIONAL_SOURCE_PRICING = "Source Pricing",
        OPTIONAL_FREEBIE_ITEM_ID = "Freebie Item Id",
        OPTIONAL_PACK_QUANTITY = "Pack Quantity",
        OPTIONAL_QUANTITY_STEP="Quantity Step",
        OPTIONAL_MINIMUM_BUY_QTY="Minimum Buy Qty",
        OPTIONAL_MAXIMUM_BUY_QTY = "Maximum Buy Qty";

        private final String PRICE_WIDTH = "100px", VENDOR_DESC_WIDTH = "130px",
        VENDOR_ID_WIDTH = "100px", ITEM_KEY_WIDTH = "200px",
        BUTTON_WIDTH = "50px";

        private Map<String, String> ConfigMap;
        interface ItemDetailsUiBinder extends UiBinder<Widget, ItemDetails> {}
        private static ItemDetailsUiBinder uiBinder = GWT.create(ItemDetailsUiBinder.class);
        private final CatalogServiceAsync catalogService = GWT.create(CatalogService.class);
        Map<String, Object> mandatoryChangedValMap;
        Map<String, Object> optionalChangedValMap;


        interface ItemDetailStyle extends CssResource{
                String greenLabel();
                String fieldChanged();
        }

        private Item item, newItem;
        private CatalogDashboard catalogDashboardPanel;

        @UiField ItemDetailStyle style;
        @UiField Label itemId;
        @UiField TextBox brand, modelNumber, modelName, color;
        @UiField Label contentCategory, catalogItemId, productGroup;
        @UiField TextBox statusDesc, comments, dealText;
        @UiField TextBox sellingPrice, mrp, weight;
        @UiField Label addedOn, retireDate, updatedOn;
        @UiField Label itemStatus;
        @UiField TextBox bestDealsText, bestDealsValue ,bestDealsDetailsText,bestDealsDetailsLink; 
        @UiField FlexTable headerAvailability, availabilityTable;
        @UiField FlexTable headerVendorItemKey, tableVendorItemKey;
        @UiField FlexTable headerVendorPrices, tableVendorPrices;
        @UiField FlexTable headerSourcePrices, tableSourcePrices;
        @UiField FlexTable headerBulkPricing, tableBulkPricing;
        @UiField TextBox bestSellingRank,dealRank;
        @UiField TextBox expectedDelay;
        @UiField CheckBox defaultForEntity, risky, warehouseStickiness, itemType, hasItemNo, showSellingPrice, holdOverride,isCodOnDeal,isDealActive;
        @UiField DateBox startDate, expectedArrivalDate, comingSoonStartDate,dealStartDate,dealEndDate;
        @UiField FlexTable headerSimilarItems, tableSimilarItems;
        @UiField ListBox preferredVendor,preferredInsurer,dealTextOption,dealFreebieOption;
        @UiField Button comingSoonButton;
        @UiField FlexTable headerVouchers, tableVouchers;
        @UiField FlexTable headerIgnoredWarehouse,tableIgnoredWarehouse;
        @UiField FlexTable headerVatDetails,tableVatDetails;
        @UiField TextBox minStockLevel, numOfDaysStock;
        @UiField TextBox lastNdaySale, websiteLastNdaySale, amazonLastNdaySale, ebayLastNdaySale, snapdealLastNdaySale, flipkartLastNdaySale, homeshop18LastNdaySale;
        @UiField TextBox freebieItemId;
        @UiField TextBox asin;
        @UiField TextBox holdInventory;
        @UiField TextBox defaultInventory;
        @UiField TextBox dealFreebieItemId;
        @UiField TextBox dealPrice;
        @UiField TextBox packQuantity, quantityStep, minimumBuyQuantity, maximumBuyQuantity;

        public ItemDetails(Item item){
                this();
                setItemDetails(item);
        }

        public ItemDetails() {
                initWidget(uiBinder.createAndBindUi(this));
                initAvailabilityHeader();
                initBulkPricingHeader();
                initVendorKeysHeader();
                initVendorPricingHeader();
                initSourcePricingHeader();
                initSimilarItemList();
                initVoucherHeader();
                initIgnoredWarehouseHeader();
                preferredVendor.addItem("null");
                preferredInsurer.addItem("null");
                getConfigdataforPriceCompare();
        }

        public void getConfigdataforPriceCompare(){
                catalogService.getConfigdataforPriceCompare(new AsyncCallback<Map<String,String>>() {
                        @Override
                        public void onSuccess(Map<String, String> result) {
                                ConfigMap = result;
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                        }
                });
        }

        /**
         * Sets the UI fields with item object attributes
         * Also populates tables for vendor prices, keys and item availability
         * @param item
         */
        public void setItemDetails(Item item){
                this.item = item;
                itemId.setText(item.getId()+"");
                productGroup.setText(item.getProductGroup());
                brand.setText(item.getBrand());
                modelNumber.setText(item.getModelNumber());
                modelName.setText(item.getModelName());
                color.setText(item.getColor());

                statusDesc.setText(item.getItemStatusDesc());
                contentCategory.setText(item.getContentCategory()+"");
                comments.setText(item.getComments());
                catalogItemId.setText(item.getCatalogItemId() + "");
                dealTextOption.clear();
                dealTextOption.addItem("None","0");
                dealTextOption.addItem("Existing Best Deals Text","1");
                dealTextOption.addItem("Other","2");
                dealTextOption.setSelectedIndex(item.getPrivateDeal().getDealTextOption().intValue());
                if(!item.getPrivateDeal().getDealText().equals("")){
                        dealText.setText(item.getPrivateDeal().getDealText()+"");
                }
                else{
                        dealText.setText("");   
                }
                if(dealTextOption.getSelectedIndex()!=2){
                        dealText.setEnabled(false);
                }
                dealFreebieOption.clear();
                dealFreebieOption.addItem("None","0");
                dealFreebieOption.addItem("Existing Freebie","1");
                dealFreebieOption.addItem("Other","2");
                dealFreebieOption.setSelectedIndex(item.getPrivateDeal().getDealFreebieOption().intValue());
                if(dealFreebieOption.getSelectedIndex()!=2){
                        dealFreebieItemId.setEnabled(false);
                }
                dealFreebieItemId.setText(item.getPrivateDeal().getDealFreebieItemId()+"");
                preferredInsurer.clear();
                preferredVendor.clear();
                int index = -1;
                if (item.getPreferredVendor() == null) {
                        index++;
                        preferredVendor.addItem("select");
                }

                if((item.getVendorPricesMap() == null || item.getVendorPricesMap().isEmpty())) {
                        if(item.getPreferredVendor() != null) {
                                index++;
                                preferredVendor.addItem(Utils.getVendorDesc(item.getPreferredVendor()));
                        }
                }
                else {
                        for(VendorPricings vendorDetail : item.getVendorPricesMap().values()){
                                index++;
                                preferredVendor.addItem(Utils.getVendorDesc(vendorDetail.getVendorId()));
                                if(item.getPreferredVendor() != null && item.getPreferredVendor() == vendorDetail.getVendorId()) {
                                        preferredVendor.setSelectedIndex(index);
                                }
                        }

                        if(item.getPreferredVendor() != null && !item.getVendorPricesMap().containsKey(item.getPreferredVendor())){
                                index++;
                                preferredVendor.addItem(Utils.getVendorDesc(item.getPreferredVendor()));
                                preferredVendor.setSelectedIndex(index);
                        }
                }
                index=0;
                preferredInsurer.addItem("select","0");
                preferredInsurer.setSelectedIndex(0);
                for (Map.Entry<Long, String> entry : Utils.getAllInsurers().entrySet()){
                        index++;
                        preferredInsurer.addItem(entry.getValue(),entry.getKey().toString());
                        if(item.getPreferredInsurer()==entry.getKey()){
                                preferredInsurer.setSelectedIndex(index);  
                        }
                }
                mrp.setText(item.getMrp() != null ? item.getMrp()+"" : "");
                sellingPrice.setText(item.getSellingPrice() != null ? item.getSellingPrice()+"" : "");
                weight.setText(item.getWeight() != null ? item.getWeight()+"" : "");
                expectedDelay.setValue(item.getExpectedDelay()+"");
                warehouseStickiness.setValue(item.isWarehouseStickiness());

                hasItemNo.setValue(item.isHasItemNo());
                itemType.setValue(item.isItemType());
                showSellingPrice.setValue(item.isShowSellingPrice());
                holdOverride.setValue(item.isHoldOverride());

                startDate.setValue(new Date(item.getStartDate()));
                if(item.getComingSoonStartDate() != null){
                        comingSoonStartDate.setValue(new Date(item.getComingSoonStartDate()));
                }else {
                        comingSoonStartDate.setValue(null);
                }

                if(item.getExpectedArrivalDate() != null){
                        expectedArrivalDate.setValue(new Date(item.getExpectedArrivalDate()));
                }else {
                        expectedArrivalDate.setValue(null);
                }
                addedOn.setText(Utils.getDisplayableDate(item.getAddedOn()));
                retireDate.setText(Utils.getDisplayableDate(item.getRetireDate()));
                updatedOn.setText(Utils.getDisplayableDate(item.getUpdatedOn()));

                bestDealsText.setText(item.getBestDealsText());
                bestDealsDetailsText.setText(item.getBestDealsDetailsText());
                bestDealsDetailsLink.setText(item.getBestDealsDetailsLink());
                bestDealsValue.setText(item.getBestDealsValue() != null ? item.getBestDealsValue()+"" : "");
                bestSellingRank.setText(item.getBestSellingRank() != null ? item.getBestSellingRank()+"" : "");
                minStockLevel.setText(item.getMinStockLevel() != null ? item.getMinStockLevel()+"" : "");
                lastNdaySale.setText(item.getSaleHistory().get(0L));
                websiteLastNdaySale.setText(item.getSaleHistory().get(1L));
                amazonLastNdaySale.setText(item.getSaleHistory().get(3L));
                ebayLastNdaySale.setText(item.getSaleHistory().get(6L));
                snapdealLastNdaySale.setText(item.getSaleHistory().get(7L));
                flipkartLastNdaySale.setText(item.getSaleHistory().get(8L));
                homeshop18LastNdaySale.setText(item.getSaleHistory().get(4L));
                numOfDaysStock.setText(item.getNumOfDaysStock() != null ? item.getNumOfDaysStock()+"" : "");
                defaultForEntity.setValue(item.isDefaultForEntity());
                risky.setValue(item.isRisky());

                itemStatus.setText(item.getItemStatus());
                freebieItemId.setText(item.getFreebieItemId().toString());
                asin.setText(item.getAsin());
                holdInventory.setText(Long.toString(item.getHoldInventory()));
                defaultInventory.setText(Long.toString(item.getDefaultInventory()));
                dealPrice.setText(item.getPrivateDeal().getDealPrice() != 0 ? item.getPrivateDeal().getDealPrice()+"" : "");
                if(item.getPrivateDeal().isActive()){
                        isDealActive.setValue(true);
                }
                else{
                        isDealActive.setValue(false);
                }
                if(item.getPrivateDeal().getStartDate()!=null){
                        dealStartDate.setValue(new Date(item.getPrivateDeal().getStartDate()));
                }
                else{
                        dealStartDate.setValue(null);
                }
                if(item.getPrivateDeal().getEndDate()!=null){
                        dealEndDate.setValue(new Date(item.getPrivateDeal().getEndDate()));
                }
                else{
                        dealEndDate.setValue(null);
                }
                bestSellingRank.setText(item.getBestSellingRank() != null ? item.getBestSellingRank()+"" : "");
                dealRank.setText(item.getPrivateDeal().getRank()!= 10000L? item.getPrivateDeal().getRank()+"" : "");
                if(item.getPrivateDeal().isCod()){
                        isCodOnDeal.setValue(true);
                }
                else{
                        isCodOnDeal.setValue(false);
                }
                dealText.setText(item.getPrivateDeal().getDealText());
                packQuantity.setText(item.getPackQuantity().toString());
                quantityStep.setText(item.getQuantityStep().toString());
                minimumBuyQuantity.setText(item.getMinimumBuyQuantity().toString());
                maximumBuyQuantity.setText(item.getMaximumBuyQuantity().toString());
                initVatDetailsHeader();
                updateVatDetailsTable(item.getStateNameVatPercentageMap());
                updateAvailabilityTable(item.getItemInventory());
                updateVendorKeysTable(item.getVendorKeysMap());
                updateVendorPricingTable(item.getVendorPricesMap());
                updateSourcePricingTable(item.getSourcePricesMap());
                updateSimilarItemsTable(item.getSimilarItems());
                updateVoucherTable(item.getVouchersMap());
                updateTableIgnoredWarehouse();
                getBulkPricingForItem(item.getId());
                dealTextOption.addChangeHandler(new ChangeHandler(){
                        @Override
                        public void onChange(ChangeEvent event) {
                                if(dealTextOption.getSelectedIndex()!=2){
                                        dealText.setEnabled(false);
                                }
                                else{
                                        dealText.setEnabled(true);
                                }
                                if(dealTextOption.getSelectedIndex()==1){
                                        dealText.setText(bestDealsText.getText());
                                }
                                if(dealTextOption.getSelectedIndex()==0){
                                        dealText.setText("");
                                }

                        }}
                );
                dealFreebieOption.addChangeHandler(new ChangeHandler(){
                        @Override
                        public void onChange(ChangeEvent event) {
                                if(dealFreebieOption.getSelectedIndex()!=2){
                                        dealFreebieItemId.setEnabled(false);
                                }
                                else{
                                        dealFreebieItemId.setEnabled(true);
                                }
                                if(dealFreebieOption.getSelectedIndex()==1){
                                        dealFreebieItemId.setText(freebieItemId.getText());
                                }
                                if(dealFreebieOption.getSelectedIndex()==0){
                                        dealFreebieItemId.setText("");
                                }

                        }}
                );
        }

        /**
         * initialise item availability table header.
         */
        private void initAvailabilityHeader(){
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_ID, "100px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_DESC, "250px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_INVA, "100px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_INVR, "100px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_HELD, "100px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_EBAY_HELD, "80px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_SNAPDEAL_HELD, "80px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_FLIPKART_HELD, "80px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_HOMESHOP18_HELD, "80px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_GET_BUTTON, "100px");
                headerAvailability.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_UPDATE_BUTTON, "100px");

                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_ID, "Warehouse Id");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_DESC, "Warehouse Desc");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_INVA, "Availability");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_INVR, "Reserved");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_HELD, "Held");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_EBAY_HELD, "Ebay Held");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_SNAPDEAL_HELD, "Snapdeal Held");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_FLIPKART_HELD, "Flipkart Held");
                headerAvailability.setText(0, TABLE_INDEX_WAREHOUSE_HOMESHOP18_HELD, "Homeshop18 Held");

                Button getLiveDataButton = new Button("Get Live Data");
                headerAvailability.setWidget(0, TABLE_INDEX_WAREHOUSE_GET_BUTTON, getLiveDataButton);
                getLiveDataButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                catalogService.getProdItemInventory(item.getId(), new AsyncCallback<Map<Long, ItemInventory>>() {
                                        @Override
                                        public void onSuccess(Map<Long, ItemInventory> itemInventoryMap) {
                                                if(itemInventoryMap != null) {
                                                        GWT.log("Inventory Data fetched");
                                                        item.setItemInventory(itemInventoryMap);
                                                        updateAvailabilityTable(item.getItemInventory());
                                                }
                                                else {
                                                        GWT.log("Error fetching Inventory Data");
                                                        Window.alert("Error fetching Inventory Data");
                                                }
                                        }
                                        @Override
                                        public void onFailure(Throwable caught) {
                                                caught.printStackTrace();
                                                Window.alert("Error fetching Inventory Data");
                                        }
                                });
                        }
                });

                Button updateLiveDataButton = new Button("Update Live Data");
                headerAvailability.setWidget(0, TABLE_INDEX_WAREHOUSE_UPDATE_BUTTON, updateLiveDataButton);
                /* code to be rewritten later
        updateLiveDataButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                catalogService.getProdItemInventory(item.getId(), new AsyncCallback<Map<Long, ItemInventory>>() {
                    @Override
                    public void onSuccess(Map<Long, ItemInventory> itemInventoryMap) {
                        if(itemInventoryMap != null) {
                            GWT.log("Inventory Data fetched");
                            item.setItemInventory(itemInventoryMap);
                            updateAvailabilityTable(item.getItemInventory());
                        }
                        else {
                            GWT.log("Error fetching Inventory Data");
                            Window.alert("Error fetching Inventory Data");
                        }
                    }
                    @Override
                    public void onFailure(Throwable caught) {
                        caught.printStackTrace();
                        Window.alert("Error fetching Inventory Data");
                    }
                });
            }
        });
                 */
                headerAvailability.getCellFormatter().setVisible(0, TABLE_INDEX_WAREHOUSE_UPDATE_BUTTON, false);

        }

        /**
         * initialises vendor item key table header. Creates an Add button and
         * adds click event listener to it to create and pop up a dialog for adding 
         * a new vendor item key. 
         */
        private void initVendorKeysHeader(){
                headerVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_VENDORID, VENDOR_ID_WIDTH);
                headerVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_VENDOR_DESC, VENDOR_DESC_WIDTH);
                headerVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_ITEM_KEY, ITEM_KEY_WIDTH);
                headerVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_ITEM_KEY_OLD, ITEM_KEY_WIDTH);
                headerVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_BUTTON, BUTTON_WIDTH);

                headerVendorItemKey.setText(0, TABLE_INDEX_MAPPING_VENDORID, "Vendor Id");
                headerVendorItemKey.setText(0, TABLE_INDEX_MAPPING_VENDOR_DESC, "Vendor");
                headerVendorItemKey.setText(0, TABLE_INDEX_MAPPING_ITEM_KEY, "Item Key");
                headerVendorItemKey.setText(0, TABLE_INDEX_MAPPING_ITEM_KEY_OLD, "Prev Item Key");

                headerVendorItemKey.getCellFormatter().setVisible(0, TABLE_INDEX_MAPPING_VENDORID, false);
                headerVendorItemKey.getCellFormatter().setVisible(0, TABLE_INDEX_MAPPING_ITEM_KEY_OLD, false);

                Button addButton = new Button("Add");
                headerVendorItemKey.setWidget(0, TABLE_INDEX_MAPPING_BUTTON, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                VendorMappingDialog vendorMappingDialog = new VendorMappingDialog(productGroup.getText().trim(), brand.getText().trim(), 
                                                modelNumber.getText().trim(), color.getText().trim());
                                vendorMappingDialog.updateButton.setText("Add");
                                vendorMappingDialog.setVendorMappingUpdateListener(new VendorMappingDialog.VendorMappingUpdateListener() {
                                        @Override
                                        public boolean onUpdate(String key, long vendorId) {
                                                int row = tableVendorItemKey.getRowCount();
                                                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_VENDORID, VENDOR_ID_WIDTH);
                                                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_VENDOR_DESC, VENDOR_DESC_WIDTH);
                                                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_ITEM_KEY, ITEM_KEY_WIDTH);
                                                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_ITEM_KEY_OLD, ITEM_KEY_WIDTH);

                                                tableVendorItemKey.setText(row, TABLE_INDEX_MAPPING_VENDORID, vendorId + "");
                                                tableVendorItemKey.setText(row, TABLE_INDEX_MAPPING_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                                                tableVendorItemKey.setText(row, TABLE_INDEX_MAPPING_ITEM_KEY, key);
                                                tableVendorItemKey.setText(row, TABLE_INDEX_MAPPING_ITEM_KEY_OLD, key);

                                                tableVendorItemKey.getCellFormatter().setVisible(row, TABLE_INDEX_MAPPING_VENDORID, false);
                                                tableVendorItemKey.getCellFormatter().setVisible(row, TABLE_INDEX_MAPPING_ITEM_KEY_OLD, false);
                                                return true;
                                        }
                                });
                                vendorMappingDialog.show();
                        }
                });
        }

        private void initBulkPricingHeader(){
                headerBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_BULK_PRICING_ID, "5px");
                headerBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_QUANTITY, "5px");
                headerBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_PRICE, "5px");
                headerBulkPricing.setText(0, TABLE_INDEX_BULK_PRICING_ID, "Bulk Pricing Id");
                headerBulkPricing.setText(0, TABLE_INDEX_QUANTITY, "Quantity");
                headerBulkPricing.setText(0, TABLE_INDEX_PRICE, "Price");
                headerBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_BULK_PRICING_BUTTON, BUTTON_WIDTH);
                headerBulkPricing.getCellFormatter().setVisible(0, TABLE_INDEX_BULK_PRICING_ID, false);
                Button addButton = new Button("Add");
                headerBulkPricing.setWidget(0, TABLE_INDEX_BULK_PRICING_BUTTON, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                if (item==null){
                                        Window.alert("Please select item first");
                                        return;
                                }
                                BulkPricingDialog bulkPricesDialog = new BulkPricingDialog();
                                bulkPricesDialog.updateButton.setText("Add");
                                bulkPricesDialog.setBulkPricingUpdateListener(new BulkPricingDialog.BulkPricingUpdateListener() {

                                        @Override
                                        public boolean onUpdate(long quantity, double price) {
                                                if(!checkBulkPricing(quantity)){
                                                        Window.alert("Quantity already present.");
                                                        return false;
                                                }
                                                final int row = tableBulkPricing.getRowCount();
                                                BulkItemPricing bulkItemPricing = new BulkItemPricing();
                                                bulkItemPricing.setItem_id(item.getId());
                                                bulkItemPricing.setPrice(price);
                                                bulkItemPricing.setQuantity(quantity);
                                                catalogService.addBulkPricingForItem(bulkItemPricing, new AsyncCallback<BulkItemPricing>() {
                                                        @Override
                                                        public void onSuccess(BulkItemPricing result) {
                                                                if (result==null){
                                                                        Window.alert("Unable to add bulk pricing");
                                                                        return;
                                                                }
                                                                tableBulkPricing.setText(row, TABLE_INDEX_BULK_PRICING_ID, result.getId()+"");
                                                                tableBulkPricing.setText(row, TABLE_INDEX_QUANTITY, result.getQuantity()+"");
                                                                tableBulkPricing.setText(row, TABLE_INDEX_PRICE, result.getPrice()+"");
                                                                tableBulkPricing.getCellFormatter().setVisible(row, TABLE_INDEX_BULK_PRICING_ID, false);
                                                                Button deleteButton = new Button("Delete");
                                                                tableBulkPricing.setWidget(row, TABLE_INDEX_BULK_PRICING_BUTTON, deleteButton);
                                                                deleteButton.addClickHandler(new ClickHandler() {
                                                                        @Override
                                                                        public void onClick(ClickEvent event) {
                                                                                Cell cell = tableBulkPricing.getCellForEvent(event);
                                                                                int row = cell.getRowIndex();
                                                                                deleteBulkPricingForId(Long.valueOf(tableBulkPricing.getText(row, TABLE_INDEX_BULK_PRICING_ID)), item.getId());
                                                                        }

                                                                });
                                                        }
                                                        @Override
                                                        public void onFailure(Throwable caught) {
                                                                caught.printStackTrace();
                                                                Window.alert("Unable to add bulk pricing.");
                                                        }
                                                });
                                                return true;
                                        }
                                });
                                bulkPricesDialog.show();
                        }
                });
                
                Button removeButton = new Button("Delete All");
                headerBulkPricing.setWidget(0, TABLE_INDEX_BULK_PRICING_REMOVE_BUTTON, removeButton);
                removeButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                if (item==null){
                                        Window.alert("Please select item first");
                                        return;
                                }
                                if(tableBulkPricing.getRowCount()==0){
                                        Window.alert("Nothing to delete");
                                        return;
                                }
                                String removeAllMessage = "Delete all bulk pricing for item id "+item.getId();
                                if (!Window.confirm(removeAllMessage)){
                                        return;
                                }
                                deleteBulkPricingForItemId(item.getId());
                        }
                });
        }
        
        public void deleteBulkPricingForItemId(final long item_id){
                catalogService.deleteBulkPricingForItem(item_id, new AsyncCallback<Boolean>() {
                        @Override
                        public void onSuccess(Boolean result) {
                                if (result){
                                        Window.alert("All Bulk Pricing deleted");
                                        getBulkPricingForItem(item_id);
                                }
                                else{
                                        Window.alert("Unable to delete bulk pricing.");
                                }
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Unable to delete bulk pricing.");
                        }
                });
        }
        
        public void deleteBulkPricingForId(long id, final long item_id){
                String deleteMessage = "Delete bulk pricing for item id " +item_id;
                if (!Window.confirm(deleteMessage)){
                        return;
                }
                catalogService.deleteBulkPricingForItemById(id, new AsyncCallback<Boolean>() {
                        @Override
                        public void onSuccess(Boolean result) {
                                if (result){
                                        Window.alert("Bulk Pricing deleted");
                                        getBulkPricingForItem(item_id);
                                }
                                else{
                                        Window.alert("Unable to delete bulk pricing.");
                                }
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Unable to delete bulk pricing.");
                        }
                });
        }


        /**
         * initialises vendor prices table header. Creates an Add button and
         * adds click event listener to it to create and pop up a dialog for adding 
         * a prices for a new vendor 
         */
        private void initVendorPricingHeader(){
                headerVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_VENDORID, VENDOR_ID_WIDTH);
                headerVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_VENDOR_DESC, VENDOR_DESC_WIDTH);
                headerVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_MOP, PRICE_WIDTH);
                headerVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_DP, PRICE_WIDTH);
                headerVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_TP, PRICE_WIDTH);
                headerVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_NLC, PRICE_WIDTH);
                headerVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_BUTTON, BUTTON_WIDTH);

                headerVendorPrices.setText(0, TABLE_INDEX_PRICING_VENDORID, "Vendor Id");
                headerVendorPrices.setText(0, TABLE_INDEX_PRICING_VENDOR_DESC, "Vendor");
                headerVendorPrices.setText(0, TABLE_INDEX_PRICING_MOP, "MOP");
                headerVendorPrices.setText(0, TABLE_INDEX_PRICING_DP, "Dealer Price");
                headerVendorPrices.setText(0, TABLE_INDEX_PRICING_TP, "Transfer Price");
                headerVendorPrices.setText(0, TABLE_INDEX_PRICING_NLC, "NLC");

                headerVendorPrices.getCellFormatter().setVisible(0, TABLE_INDEX_PRICING_VENDORID, false);

                Button addButton = new Button("Add");
                headerVendorPrices.setWidget(0, TABLE_INDEX_PRICING_BUTTON, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                VendorPricesDialog vendorPricesDialog = new VendorPricesDialog();
                                vendorPricesDialog.updateButton.setText("Add");
                                vendorPricesDialog.setVendorPriceUpdateListener(new VendorPricesDialog.VendorPriceUpdateListener() {
                                        @Override
                                        public boolean onUpdate(double mop, double dp, double tp, double nlc, long vendorId) {
                                                if(!vendorExists(vendorId)) {
                                                        Window.alert("Vendor already exists");
                                                        return false;
                                                }
                                                /*if(!validateVendorPrices(mop, dp, tp)) {
                            return false;
                        }*/
                                                int row = tableVendorPrices.getRowCount();
                                                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_VENDORID, VENDOR_ID_WIDTH);
                                                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_VENDOR_DESC, VENDOR_DESC_WIDTH);
                                                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_MOP, PRICE_WIDTH);
                                                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_DP, PRICE_WIDTH);
                                                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_TP, PRICE_WIDTH);
                                                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_NLC, PRICE_WIDTH);

                                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_VENDORID, vendorId + "");
                                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_VENDOR_DESC, Utils.getVendorDesc(vendorId));
                                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_MOP, mop + "");
                                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_DP, dp + "");
                                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_TP, tp + "");
                                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_NLC, nlc + "");

                                                tableVendorPrices.getCellFormatter().setVisible(row, TABLE_INDEX_PRICING_VENDORID, false);
                                                return true;
                                        }
                                });
                                vendorPricesDialog.show();
                        }
                });
        }

        /**
         * initialises source prices table header. Creates an Add button and
         * adds click event listener to it to create and pop up a dialog for adding 
         * a prices for a new source 
         */
        private void initSourcePricingHeader(){
                headerSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, VENDOR_ID_WIDTH);
                headerSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SOURCE_DESC, VENDOR_DESC_WIDTH);
                headerSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_MRP, PRICE_WIDTH);
                headerSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE, PRICE_WIDTH);
                headerSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_BUTTON, BUTTON_WIDTH);

                headerSourcePrices.setText(0, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, "Source Id");
                headerSourcePrices.setText(0, TABLE_INDEX_SOURCE_PRICING_SOURCE_DESC, "Source");
                headerSourcePrices.setText(0, TABLE_INDEX_SOURCE_PRICING_MRP, "MRP");
                headerSourcePrices.setText(0, TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE, "Selling Price");

                headerSourcePrices.getCellFormatter().setVisible(0, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, false);

                Button addButton = new Button("Add");
                headerSourcePrices.setWidget(0, TABLE_INDEX_SOURCE_PRICING_BUTTON, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                SourcePricesDialog sourcePricesDialog = new SourcePricesDialog(mrp.getText().trim(), sellingPrice.getText().trim());
                                //SourcePricesDialog sourcePricesDialog = new SourcePricesDialog();
                                sourcePricesDialog.updateButton.setText("Add");
                                sourcePricesDialog.setSourcePriceUpdateListener(new SourcePricesDialog.SourcePriceUpdateListener() {
                                        @Override
                                        public boolean onUpdate(double mrp, double sellingPrice, long sourceId) {
                                                if(!sourceExists(sourceId)) {
                                                        Window.alert("Source already exists");
                                                        return false;
                                                }

                                                int row = tableSourcePrices.getRowCount();
                                                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, VENDOR_ID_WIDTH);
                                                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SOURCE_DESC, VENDOR_DESC_WIDTH);
                                                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_MRP, PRICE_WIDTH);
                                                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE, PRICE_WIDTH);

                                                tableSourcePrices.setText(row, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, sourceId + "");
                                                tableSourcePrices.setText(row, TABLE_INDEX_SOURCE_PRICING_SOURCE_DESC, Utils.getSourceDesc(sourceId));
                                                tableSourcePrices.setText(row, TABLE_INDEX_SOURCE_PRICING_MRP, mrp + "");
                                                tableSourcePrices.setText(row, TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE, sellingPrice + "");

                                                tableSourcePrices.getCellFormatter().setVisible(row, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, false);
                                                return true;
                                        }
                                });
                                sourcePricesDialog.show();
                        }
                });
        }

        /**
         * initialises similar items table header. Creates an Add button and
         * adds click event listener to it to create and pop up a dialog for adding 
         * a new similar item. 
         */
        private void initSimilarItemList() {
                headerSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_CATALOG_ITEM_ID, PRICE_WIDTH);
                headerSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_PRODUCT_GROUP, PRICE_WIDTH);
                headerSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_BRAND, PRICE_WIDTH);
                headerSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_MODEL_NUMBER, PRICE_WIDTH);
                headerSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_MODEL_NAME, PRICE_WIDTH);
                headerSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_CATEGORY, "150px");
                headerSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_BUTTON, BUTTON_WIDTH);

                headerSimilarItems.setText(0, TABLE_INDEX_SIMILAR_ITEMS_CATALOG_ITEM_ID, "Catalog ItemId");
                headerSimilarItems.setText(0, TABLE_INDEX_SIMILAR_ITEMS_PRODUCT_GROUP, "Product Group");
                headerSimilarItems.setText(0, TABLE_INDEX_SIMILAR_ITEMS_BRAND, "Brand");
                headerSimilarItems.setText(0, TABLE_INDEX_SIMILAR_ITEMS_MODEL_NUMBER, "Model Number");
                headerSimilarItems.setText(0, TABLE_INDEX_SIMILAR_ITEMS_MODEL_NAME, "Model Name");
                headerSimilarItems.setText(0, TABLE_INDEX_SIMILAR_ITEMS_CATEGORY, "Category");

                Button addButton = new Button("Add");
                headerSimilarItems.setWidget(0, TABLE_INDEX_SIMILAR_ITEMS_BUTTON, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                AddSimilarItemDialog addSimilarItemDialog = new AddSimilarItemDialog();
                                addSimilarItemDialog.setAddSimilarItemUpdateListener(new AddSimilarItemDialog.AddSimilarItemUpdateListener() {
                                        @Override
                                        public boolean onUpdate(long catalogItemId) {
                                                if (item.getSimilarItems().containsKey(catalogItemId)) {
                                                        Window.alert("Similar Item exists.");
                                                        return false;
                                                }
                                                else {
                                                        catalogService.addSimilarItem(item.getId(), catalogItemId, new AsyncCallback<Item>() {
                                                                @Override
                                                                public void onSuccess(Item similarItem) {
                                                                        if(similarItem != null) {
                                                                                GWT.log("Similar Item Added");
                                                                                Map<Long, Item> newsimilarItems = item.getSimilarItems();
                                                                                newsimilarItems.put(similarItem.getCatalogItemId(), similarItem);
                                                                                item.setSimilarItems(newsimilarItems);
                                                                                updateSimilarItemsTable(item.getSimilarItems());
                                                                                Window.alert("Similar Item Added successfully.");
                                                                        }
                                                                        else {
                                                                                GWT.log("Error Adding Similar Item");
                                                                                Window.alert("Error Adding Similar Item");
                                                                        }
                                                                }
                                                                @Override
                                                                public void onFailure(Throwable caught) {
                                                                        caught.printStackTrace();
                                                                        Window.alert("Error deleting Similar Item");
                                                                }
                                                        });
                                                        return true;
                                                }
                                        }
                                });
                                addSimilarItemDialog.show();
                        }
                });
        }
        private void initVatDetailsHeader(){
                headerVatDetails.getColumnFormatter().setWidth(TABLE_INDEX_STATE_NAME, "80px");
                headerVatDetails.getColumnFormatter().setWidth(TABLE_INDEX_STATE_TAX_PERCENTAGE, "50px");
                headerVatDetails.setText(0, TABLE_INDEX_STATE_NAME, "State Name");
                headerVatDetails.setText(0, TABLE_INDEX_STATE_TAX_PERCENTAGE, "Tax Percentage");

        }
        private void updateVatDetailsTable(Map<String,String> stateVatPercentage){
                tableVatDetails.removeAllRows();
                if(stateVatPercentage == null || stateVatPercentage.isEmpty()) {
                        return;
                }
                tableVatDetails.getColumnFormatter().setWidth(TABLE_INDEX_STATE_NAME, "80px");
                tableVatDetails.getColumnFormatter().setWidth(TABLE_INDEX_STATE_TAX_PERCENTAGE, "50px");
                int i=0;
                for(Entry<String,String> e : stateVatPercentage.entrySet()){
                        tableVatDetails.setText(i, TABLE_INDEX_STATE_NAME, e.getKey() +"");
                        if(e.getValue().equals("-1.0")){
                                tableVatDetails.setText(i, TABLE_INDEX_STATE_TAX_PERCENTAGE, "N.A" + "");
                        }
                        else{
                                tableVatDetails.setText(i, TABLE_INDEX_STATE_TAX_PERCENTAGE, e.getValue()+" %" + "");
                        }
                        i++;
                }
        }
        private void initIgnoredWarehouseHeader(){
                headerIgnoredWarehouse.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_NAME, "100px");
                headerIgnoredWarehouse.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_ADD_DEL_BUTTON, BUTTON_WIDTH);
                headerIgnoredWarehouse.setText(0, TABLE_INDEX_WAREHOUSE_NAME, "Warehouse Desc");
                Button addButton = new Button("Add");
                headerIgnoredWarehouse.setWidget(0,TABLE_INDEX_WAREHOUSE_ADD_DEL_BUTTON,addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                DeactivateWarehouseDialog deactivateWarehouseDialog = new DeactivateWarehouseDialog(new ArrayList<Long>(item.getVendorPricesMap().keySet()));
                                deactivateWarehouseDialog.updateButton.setText("Add");
                                deactivateWarehouseDialog.setDeactivateWarehouseListener(new DeactivateWarehouseDialog.DeactivateWarehouseListener(){
                                        @Override
                                        public boolean onUpdate(final long warehouseId) {
                                                if(Utils.getignoredInventoryUpdateItemsIdsWarehouseIds().contains(new ItemWarehouse(item.getId(),warehouseId))) {
                                                        Window.alert("Warehouse already deactivated");
                                                        return false;
                                                }
                                                catalogService.addtoIgnoredInventoryUpdateItemsIdsWarehouseIds(item.getId(),warehouseId,new AsyncCallback<Boolean>() {
                                                        @Override
                                                        public void onSuccess(Boolean result) {
                                                                if(result) {
                                                                        Utils.getignoredInventoryUpdateItemsIdsWarehouseIds().add(new ItemWarehouse(item.getId(),warehouseId));
                                                                        int index1 = tableIgnoredWarehouse.insertRow(0);
                                                                        addRowToIgnoredWarehouseTable(index1, warehouseId, Utils.getAllWarehouses().get(warehouseId));

                                                                        Window.alert("Warehouse deactivated successfully");
                                                                }
                                                                else {
                                                                        GWT.log("Error Deactivating warehouse");
                                                                        Window.alert("Error Deactivating warehouse");
                                                                }
                                                        }
                                                        @Override
                                                        public void onFailure(Throwable caught) {
                                                                caught.printStackTrace();
                                                                Window.alert("Error Deactivating warehouse");
                                                        }
                                                });
                                                return true;
                                        }
                                });
                                deactivateWarehouseDialog.show();
                        }
                });
        }


        private void initVoucherHeader(){
                headerVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_TYPE, ITEM_KEY_WIDTH);
                headerVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_AMOUNT, VENDOR_DESC_WIDTH);
                headerVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_ADD_EDIT_BUTTON, BUTTON_WIDTH);
                headerVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_DEL_BUTTON, BUTTON_WIDTH);

                headerVouchers.setText(0, TABLE_INDEX_VOUCHERS_TYPE, "Voucher Type");
                headerVouchers.setText(0, TABLE_INDEX_VOUCHERS_AMOUNT, "Voucher Amount");
                headerVouchers.getCellFormatter().setVisible(0, TABLE_INDEX_VOUCHERS_DEL_BUTTON, false);
                Button addButton = new Button("Add");
                headerVouchers.setWidget(0, TABLE_INDEX_VOUCHERS_ADD_EDIT_BUTTON, addButton);
                addButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                VoucherItemDialog voucherItemDialog = new VoucherItemDialog();
                                voucherItemDialog.updateButton.setText("Add");
                                voucherItemDialog.setVoucherUpdateListener(new VoucherItemDialog.VoucherUpdateListener() {
                                        @Override
                                        public boolean onUpdate(final String voucherType, final long voucherAmount) {
                                                if(!voucherExists(voucherType)) {
                                                        Window.alert("Voucher already exists");
                                                        return false;
                                                }
                                                Long voucherTypeValue = Utils.getVoucherTypeId(voucherType);;
                                                catalogService.addVoucher(item.getCatalogItemId(), voucherTypeValue, voucherAmount, new AsyncCallback<Boolean>() {
                                                        @Override
                                                        public void onSuccess(Boolean result) {
                                                                if(result) {
                                                                        GWT.log("Voucher Added");
                                                                        VoucherItemMapping newvoucher = new VoucherItemMapping(voucherAmount, voucherType);
                                                                        Map<String, VoucherItemMapping> newvouchersMap = item.getVouchersMap();
                                                                        newvouchersMap.put(voucherType, newvoucher);
                                                                        item.setVouchersMap(newvouchersMap);
                                                                        updateVoucherTable(item.getVouchersMap());
                                                                        Window.alert("Voucher Added successfully.");
                                                                }
                                                                else {
                                                                        GWT.log("Error Adding Voucher");
                                                                        Window.alert("Error Adding Voucher");
                                                                }
                                                        }
                                                        @Override
                                                        public void onFailure(Throwable caught) {
                                                                caught.printStackTrace();
                                                                Window.alert("Error deleting voucher");
                                                        }
                                                });
                                                return true;
                                        }
                                });
                                voucherItemDialog.show();
                        }
                });
        }
        
        private void getBulkPricingForItem(long item_id){
                catalogService.getBulkPricingByItemId(item_id, new AsyncCallback<List<BulkItemPricing>>() {
                        @Override
                        public void onSuccess(List<BulkItemPricing> result) {
                                updateBulkPricingTable(result);
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Unable to get bulk pricing for item");
                        }
                        
                });
        }


        private void updateBulkPricingTable(List<BulkItemPricing> items){
                tableBulkPricing.removeAllRows();
                tableBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_BULK_PRICING_ID, "5px");
                tableBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_QUANTITY, "5px");
                tableBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_PRICE, "5px");
                tableBulkPricing.getColumnFormatter().setWidth(TABLE_INDEX_BULK_PRICING_BUTTON, BUTTON_WIDTH);
                int i =0;
                for (BulkItemPricing result : items){
                        tableBulkPricing.setText(i, TABLE_INDEX_BULK_PRICING_ID, result.getId()+"");
                        tableBulkPricing.setText(i, TABLE_INDEX_QUANTITY, result.getQuantity()+"");
                        tableBulkPricing.setText(i, TABLE_INDEX_PRICE, result.getPrice()+"");
                        tableBulkPricing.getCellFormatter().setVisible(i, TABLE_INDEX_BULK_PRICING_ID, false);
                        Button deleteButton = new Button("Delete");
                        tableBulkPricing.setWidget(i, TABLE_INDEX_BULK_PRICING_BUTTON, deleteButton);
                        deleteButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        Cell cell = tableBulkPricing.getCellForEvent(event);
                                        int row = cell.getRowIndex();
                                        deleteBulkPricingForId(Long.valueOf(tableBulkPricing.getText(row, TABLE_INDEX_BULK_PRICING_ID)), item.getId());
                                }

                        });
                        i++;
                }
        }

        /**
         * Clear and populate item availability table.
         * @param availabilityMap
         */

        private void updateAvailabilityTable(Map<Long, ItemInventory> itemInventoryMap){
                availabilityTable.removeAllRows();
                if(itemInventoryMap == null || itemInventoryMap.isEmpty()) {
                        return;
                }
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_ID, "100px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_DESC, "300px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_INVA, "100px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_INVR, "100px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_HELD, "100px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_EBAY_HELD, "80px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_SNAPDEAL_HELD, "80px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_FLIPKART_HELD, "80px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_HOMESHOP18_HELD, "80px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_GET_BUTTON, "100px");
                availabilityTable.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_UPDATE_BUTTON, "100px");

                int i=0;
                for(ItemInventory warehousedata : itemInventoryMap.values()){
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_ID, warehousedata.getWarehouseId() + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_DESC, Utils.getWarehouseDesc(warehousedata.getWarehouseId()) + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_INVA, warehousedata.getAvailability() + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_INVR, warehousedata.getReserved() + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_HELD, warehousedata.getHeld() + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_EBAY_HELD, warehousedata.getEbayHeld() + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_SNAPDEAL_HELD, warehousedata.getSnapdealHeld() + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_FLIPKART_HELD, warehousedata.getFlipkartHeld() + "");
                        availabilityTable.setText(i, TABLE_INDEX_WAREHOUSE_HOMESHOP18_HELD, warehousedata.getHomeshop18Held() + "");

                        i++;
                }
        }

        /**
         * Clear and populate vendor item key table with keys in the passed argument.
         * With each row in the table, an edit button is created and click event listener 
         * is added to it to edit that vendor item key row.
         * @param vendorKeysMap
         */
        private void updateVendorKeysTable(Map<String, VendorItemMapping> vendorKeysMap){
                tableVendorItemKey.removeAllRows();

                if(vendorKeysMap == null || vendorKeysMap.isEmpty()) {
                        return;
                }
                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_VENDORID, VENDOR_ID_WIDTH);
                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_VENDOR_DESC, VENDOR_DESC_WIDTH);
                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_ITEM_KEY, ITEM_KEY_WIDTH);
                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_ITEM_KEY_OLD, ITEM_KEY_WIDTH);
                tableVendorItemKey.getColumnFormatter().setWidth(TABLE_INDEX_MAPPING_BUTTON, BUTTON_WIDTH);

                int i=0;
                for(Entry<String, VendorItemMapping> e : vendorKeysMap.entrySet()){
                        VendorItemMapping vendorMapping = e.getValue();
                        tableVendorItemKey.setText(i, TABLE_INDEX_MAPPING_VENDORID, vendorMapping.getVendorId() + "");
                        tableVendorItemKey.setText(i, TABLE_INDEX_MAPPING_VENDOR_DESC, Utils.getVendorDesc(vendorMapping.getVendorId()));
                        tableVendorItemKey.setText(i, TABLE_INDEX_MAPPING_ITEM_KEY, vendorMapping.getItemKey());
                        tableVendorItemKey.setText(i, TABLE_INDEX_MAPPING_ITEM_KEY_OLD, e.getKey().substring(e.getKey().indexOf(Item.KEY_SEPARATOR)+1));
                        Button editButton = new Button("Edit");
                        tableVendorItemKey.setWidget(i, TABLE_INDEX_MAPPING_BUTTON, editButton);
                        editButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        Cell cell = tableVendorItemKey.getCellForEvent(event);
                                        int row = cell.getRowIndex();
                                        long vendorId = Long.parseLong(tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_VENDORID));
                                        editVendorKey(vendorId, row);
                                }
                        });
                        tableVendorItemKey.getCellFormatter().setVisible(i, TABLE_INDEX_MAPPING_VENDORID, false);
                        tableVendorItemKey.getCellFormatter().setVisible(i, TABLE_INDEX_MAPPING_ITEM_KEY_OLD, false);
                        i++;
                }
        }

        /**
         * Clear and populate vendor prices table with prices in the passed argument.
         * With each row in the table, an edit button is created and click event listener 
         * is added to it to edit that vendor prices row.
         * @param vendorPricingMap
         */
        private void updateVendorPricingTable(Map<Long, VendorPricings> vendorPricingMap){
                tableVendorPrices.removeAllRows();

                if(vendorPricingMap == null || vendorPricingMap.isEmpty()) {
                        return;
                }
                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_VENDORID, VENDOR_ID_WIDTH);
                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_VENDOR_DESC, VENDOR_DESC_WIDTH);
                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_MOP, PRICE_WIDTH);
                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_DP, PRICE_WIDTH);
                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_TP, PRICE_WIDTH);
                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_NLC, PRICE_WIDTH);
                tableVendorPrices.getColumnFormatter().setWidth(TABLE_INDEX_PRICING_BUTTON, BUTTON_WIDTH);


                int i=0;
                for(VendorPricings vendorDetail : vendorPricingMap.values()){
                        tableVendorPrices.setText(i, TABLE_INDEX_PRICING_VENDORID, vendorDetail.getVendorId() + "");
                        tableVendorPrices.setText(i, TABLE_INDEX_PRICING_VENDOR_DESC, Utils.getVendorDesc(vendorDetail.getVendorId()));
                        tableVendorPrices.setText(i, TABLE_INDEX_PRICING_MOP, vendorDetail.getMop() + "");
                        tableVendorPrices.setText(i, TABLE_INDEX_PRICING_DP, vendorDetail.getDealerPrice() + "");
                        tableVendorPrices.setText(i, TABLE_INDEX_PRICING_TP, vendorDetail.getTransferPrice() + "");
                        tableVendorPrices.setText(i, TABLE_INDEX_PRICING_NLC, vendorDetail.getNlc() + "");
                        Button editButton = new Button("Edit");
                        tableVendorPrices.setWidget(i, TABLE_INDEX_PRICING_BUTTON, editButton);
                        editButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        Cell cell = tableVendorPrices.getCellForEvent(event);
                                        int row = cell.getRowIndex();
                                        long vendorId = Long.parseLong(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_VENDORID));
                                        editVendorPrices(vendorId, row);
                                }
                        });
                        tableVendorPrices.getCellFormatter().setVisible(i, TABLE_INDEX_PRICING_VENDORID, false);
                        i++;
                }
        }

        /**
         * Clear and populate vendor prices table with prices in the passed argument.
         * With each row in the table, an edit button is created and click event listener 
         * is added to it to edit that vendor prices row.
         * @param sourcePricingMap
         */
        private void updateSourcePricingTable(Map<Long, SourcePricings> sourcePricingMap){
                tableSourcePrices.removeAllRows();

                if(sourcePricingMap == null || sourcePricingMap.isEmpty()) {
                        return;
                }
                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, VENDOR_ID_WIDTH);
                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SOURCE_DESC, VENDOR_DESC_WIDTH);
                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_MRP, PRICE_WIDTH);
                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE, PRICE_WIDTH);
                tableSourcePrices.getColumnFormatter().setWidth(TABLE_INDEX_SOURCE_PRICING_BUTTON, BUTTON_WIDTH);

                int i=0;
                for(SourcePricings sourceDetail : sourcePricingMap.values()){
                        tableSourcePrices.setText(i, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, sourceDetail.getSourceId() + "");
                        tableSourcePrices.setText(i, TABLE_INDEX_SOURCE_PRICING_SOURCE_DESC, Utils.getSourceDesc(sourceDetail.getSourceId()));
                        tableSourcePrices.setText(i, TABLE_INDEX_SOURCE_PRICING_MRP, sourceDetail.getMrp() + "");
                        tableSourcePrices.setText(i, TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE, sourceDetail.getSellingPrice() + "");

                        Button editButton = new Button("Edit");
                        tableSourcePrices.setWidget(i, TABLE_INDEX_SOURCE_PRICING_BUTTON, editButton);
                        editButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        Cell cell = tableSourcePrices.getCellForEvent(event);
                                        int row = cell.getRowIndex();
                                        long sourceId = Long.parseLong(tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID));
                                        editSourcePrices(sourceId, row);
                                }
                        });
                        tableSourcePrices.getCellFormatter().setVisible(i, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID, false);
                        i++;
                }
        }

        /**
         * Clear and populate similar items table with items in the passed argument.
         * With each row in the table, an delete button is created and click event listener 
         * is added to it to delete that similar item row.
         * @param similarItems
         */
        private void updateSimilarItemsTable(Map<Long, Item> similarItems){
                tableSimilarItems.removeAllRows();

                if(similarItems == null || similarItems.isEmpty()) {
                        return;
                }
                tableSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_CATALOG_ITEM_ID, PRICE_WIDTH);
                tableSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_PRODUCT_GROUP, PRICE_WIDTH);
                tableSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_BRAND, PRICE_WIDTH);
                tableSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_MODEL_NUMBER, PRICE_WIDTH);
                tableSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_MODEL_NAME, PRICE_WIDTH);
                tableSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_CATEGORY, "150px");
                tableSimilarItems.getColumnFormatter().setWidth(TABLE_INDEX_SIMILAR_ITEMS_BUTTON, BUTTON_WIDTH);


                int i=0;
                for(Item similarItemDetail : similarItems.values()){
                        tableSimilarItems.setText(i, TABLE_INDEX_SIMILAR_ITEMS_CATALOG_ITEM_ID, similarItemDetail.getCatalogItemId() + "");
                        tableSimilarItems.setText(i, TABLE_INDEX_SIMILAR_ITEMS_PRODUCT_GROUP, similarItemDetail.getProductGroup() + "");
                        tableSimilarItems.setText(i, TABLE_INDEX_SIMILAR_ITEMS_BRAND, similarItemDetail.getBrand() + "");
                        tableSimilarItems.setText(i, TABLE_INDEX_SIMILAR_ITEMS_MODEL_NUMBER, similarItemDetail.getModelNumber() + "");
                        tableSimilarItems.setText(i, TABLE_INDEX_SIMILAR_ITEMS_MODEL_NAME, similarItemDetail.getModelName() + "");
                        tableSimilarItems.setText(i, TABLE_INDEX_SIMILAR_ITEMS_CATEGORY, similarItemDetail.getContentCategory() + "");

                        Button deleteButton = new Button("Delete");
                        tableSimilarItems.setWidget(i, TABLE_INDEX_SIMILAR_ITEMS_BUTTON, deleteButton);
                        deleteButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        Cell cell = tableSimilarItems.getCellForEvent(event);
                                        final int row = cell.getRowIndex();
                                        long catalogItemId = Long.parseLong(tableSimilarItems.getText(row, TABLE_INDEX_SIMILAR_ITEMS_CATALOG_ITEM_ID));

                                        catalogService.deleteSimilarItem(item.getId(), catalogItemId, new AsyncCallback<Boolean>() {
                                                @Override
                                                public void onSuccess(Boolean result) {
                                                        if(result) {
                                                                GWT.log("Similar Item deleted");
                                                                long catalogItemId = Long.parseLong(tableSimilarItems.getText(row, TABLE_INDEX_SIMILAR_ITEMS_CATALOG_ITEM_ID)); 
                                                                tableSimilarItems.removeRow(row);
                                                                Map<Long, Item> newsimilarItems = item.getSimilarItems();
                                                                newsimilarItems.remove(catalogItemId);
                                                                item.setSimilarItems(newsimilarItems);
                                                        }
                                                        else {
                                                                GWT.log("Error deleting Similar Item");
                                                                Window.alert("Error deleting Similar Item");
                                                        }
                                                }
                                                @Override
                                                public void onFailure(Throwable caught) {
                                                        caught.printStackTrace();
                                                        Window.alert("Error deleting Similar Item");
                                                }
                                        });
                                }
                        });
                        i++;
                }
        }

        private void updateVoucherTable(Map<String, VoucherItemMapping> vouchersMap){
                tableVouchers.removeAllRows();

                if(vouchersMap == null || vouchersMap.isEmpty()) {
                        return;
                }
                tableVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_TYPE, ITEM_KEY_WIDTH);
                tableVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_AMOUNT, VENDOR_DESC_WIDTH);
                tableVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_ADD_EDIT_BUTTON, BUTTON_WIDTH);
                tableVouchers.getColumnFormatter().setWidth(TABLE_INDEX_VOUCHERS_DEL_BUTTON, BUTTON_WIDTH);

                int i=0;
                for(VoucherItemMapping voucher : vouchersMap.values()){
                        tableVouchers.setText(i, TABLE_INDEX_VOUCHERS_TYPE, voucher.getVoucherType());
                        tableVouchers.setText(i, TABLE_INDEX_VOUCHERS_AMOUNT, voucher.getAmount() + "");

                        Button editButton = new Button("Edit");
                        tableVouchers.setWidget(i, TABLE_INDEX_VOUCHERS_ADD_EDIT_BUTTON, editButton);
                        editButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        Cell cell = tableVouchers.getCellForEvent(event);
                                        final int row = cell.getRowIndex();
                                        String voucherAmount = tableVouchers.getText(row, TABLE_INDEX_VOUCHERS_AMOUNT);
                                        VoucherItemDialog voucherDialog = new VoucherItemDialog(voucherAmount);
                                        voucherDialog.updateButton.setText("Update");
                                        voucherDialog.setVoucherUpdateListener(new VoucherItemDialog.VoucherUpdateListener() {
                                                @Override
                                                public boolean onUpdate(final String voucherType, final long voucherAmount) {
                                                        Long voucherTypeValue = Utils.getVoucherTypeId(voucherType);
                                                        catalogService.addVoucher(item.getCatalogItemId(), voucherTypeValue, voucherAmount, new AsyncCallback<Boolean>() {
                                                                @Override
                                                                public void onSuccess(Boolean result) {
                                                                        if(result) {
                                                                                GWT.log("Voucher Updated");
                                                                                VoucherItemMapping newvoucher = new VoucherItemMapping(voucherAmount, voucherType);
                                                                                Map<String, VoucherItemMapping> newvouchersMap = item.getVouchersMap();
                                                                                newvouchersMap.remove(voucherType);
                                                                                newvouchersMap.put(voucherType, newvoucher);
                                                                                item.setVouchersMap(newvouchersMap);
                                                                                updateVoucherTable(item.getVouchersMap());
                                                                                Window.alert("Voucher Updated successfully.");
                                                                        }
                                                                        else {
                                                                                GWT.log("Error Updating Voucher");
                                                                                Window.alert("Error Updating Voucher");
                                                                        }
                                                                }
                                                                @Override
                                                                public void onFailure(Throwable caught) {
                                                                        caught.printStackTrace();
                                                                        Window.alert("Error Updating voucher");
                                                                }
                                                        });
                                                        return true;
                                                }
                                        });
                                        voucherDialog.show();
                                }
                        });

                        Button deleteButton = new Button("Delete");
                        tableVouchers.setWidget(i, TABLE_INDEX_VOUCHERS_DEL_BUTTON, deleteButton);
                        deleteButton.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        Cell cell = tableVouchers.getCellForEvent(event);
                                        final int row = cell.getRowIndex();
                                        String voucherType = tableVouchers.getText(row, TABLE_INDEX_VOUCHERS_TYPE);
                                        Long voucherTypeValue = Utils.getVoucherTypeId(voucherType);
                                        catalogService.deleteVoucher(item.getCatalogItemId(), voucherTypeValue, new AsyncCallback<Boolean>() {
                                                @Override
                                                public void onSuccess(Boolean result) {
                                                        if(result) {
                                                                GWT.log("Voucher deleted");
                                                                String voucherType = tableVouchers.getText(row, TABLE_INDEX_VOUCHERS_TYPE);
                                                                tableVouchers.removeRow(row);
                                                                Map<String, VoucherItemMapping> newvouchersMap = item.getVouchersMap();
                                                                newvouchersMap.remove(voucherType);
                                                                item.setVouchersMap(newvouchersMap);
                                                        }
                                                        else {
                                                                GWT.log("Error deleting Voucher");
                                                                Window.alert("Error deleting Voucher");
                                                        }
                                                }
                                                @Override
                                                public void onFailure(Throwable caught) {
                                                        caught.printStackTrace();
                                                        Window.alert("Error deleting Voucher");
                                                }
                                        });
                                }
                        });
                        i++;
                }
        }
        private void updateTableIgnoredWarehouse(){
                tableIgnoredWarehouse.removeAllRows();
                List<ItemWarehouse> itemWarehouses = Utils.getignoredInventoryUpdateItemsIdsWarehouseIds();
                Map<Long,String> ignoredWarehouses = new HashMap<Long, String>();
                for(ItemWarehouse itemWarehouse:itemWarehouses){
                        if(itemWarehouse.getItemId()==item.getId()){
                                ignoredWarehouses.put(itemWarehouse.getWarehouseId(),Utils.getAllWarehouses().get(itemWarehouse.getWarehouseId()));     
                        }

                }               
                tableIgnoredWarehouse.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_NAME, "100px");
                tableIgnoredWarehouse.getColumnFormatter().setWidth(TABLE_INDEX_WAREHOUSE_ADD_DEL_BUTTON, BUTTON_WIDTH);

                int i=0;
                for(final Map.Entry<Long,String> entry : ignoredWarehouses.entrySet()){
                        addRowToIgnoredWarehouseTable(i, entry.getKey(), entry.getValue());
                        i++;
                }
        }

        private void addRowToIgnoredWarehouseTable(int i, final Long whId, final String whName) {
                tableIgnoredWarehouse.setText(i,TABLE_INDEX_WAREHOUSE_NAME,whName);
                Button deleteButton = new Button("Delete");
                tableIgnoredWarehouse.setWidget(i, TABLE_INDEX_WAREHOUSE_ADD_DEL_BUTTON, deleteButton);
                deleteButton.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                                Cell cell = tableIgnoredWarehouse.getCellForEvent(event);
                                final int row = cell.getRowIndex();
                                catalogService.deleteFromIgnoredInventoryUpdateItemsIdsWarehouseIds(item.getId(),whId, new AsyncCallback<Boolean>() {
                                        @Override
                                        public void onSuccess(Boolean result) {
                                                if(result) {
                                                        GWT.log("Warehouse will now be in sync");
                                                        tableIgnoredWarehouse.removeRow(row);
                                                        Window.alert("Warehouse deleted from list ");
                                                        Utils.getignoredInventoryUpdateItemsIdsWarehouseIds().remove(new ItemWarehouse(item.getId(),whId));
                                                }
                                                else {
                                                        GWT.log("Error deleting Warehouse");
                                                        Window.alert("Error deleting Warehouse");
                                                }
                                        }
                                        @Override
                                        public void onFailure(Throwable caught) {
                                                caught.printStackTrace();
                                                Window.alert("Error deleting Warehouse");
                                        }
                                });
                        }
                });

        }

        /**
         * called on the click event of update item button in ItemActions
         */
        void updateItem() {
                if(item == null) {
                        Window.alert("Please select an item to update.");
                        return;
                }
                try {
                        if(!createNewItem()) {
                                return;
                        }
                } catch(NumberFormatException ex) {
                        ex.printStackTrace();
                        GWT.log("Number format exception");
                }
                String paramsChanged = isItemChanged();
                if(paramsChanged.equals("")) {
                        Window.alert("Nothing to update. Please change intended item parameters and try again.");
                        return;
                } else {
                        if(item.getSameItemsWithDifferentColors().size()>0 && optionalChangedValMap.size()>0 ){
                                createDialog(paramsChanged);
                        } else {
                                String paramsChanged1  = "";
                                paramsChanged1 = "You have changed following items.\n" + paramsChanged;
                                Window.alert(paramsChanged1);
                                validateNUpdate();
                        }
                        if("\n-Expected Delay".equals(paramsChanged) || "\n-Has Serial Number Flag".equals(paramsChanged)){
                                catalogService.updateExpectedDelayOnProd(newItem, new AsyncCallback<String>() {
                                        @Override
                                        public void onSuccess(String result) {
                                                Window.alert(result);
                                        }
                                        @Override
                                        public void onFailure(Throwable caught) {
                                                Window.alert("Error while updating item on production");
                                        }
                                });
                        }
                }
        }


        private void validateNUpdate() {
                if(!Utils.validateItem(newItem)) {
                        return;
                }

                final String[] messageList = new String[2];

                String sellingpricemessage = compareSellingPricewithBreakEven();
                if(sellingpricemessage.equals("false")) {
                        return;
                }
                else if(!sellingpricemessage.equals("true")) {
                        messageList[0] = sellingpricemessage;
                }

                String preferredvendormessage = checkTransferPriceforPreferredVendor();
                if(preferredvendormessage.equals("false")) {
                        return;
                }
                else if(!preferredvendormessage.equals("true")) {
                        messageList[1] = preferredvendormessage;
                }

                /*if(!validatePrices()) {
            return;
        }*/
                catalogService.updateItem(newItem, new AsyncCallback<Boolean>() {
                        @Override
                        public void onSuccess(Boolean result) {
                                if(result) {
                                        for(int i = 0; i < messageList.length; i++) {
                                                if(messageList[i] != null) {
                                                        logAuthorization(messageList[i]);
                                                }
                                        }
                                        if(optionalChangedValMap.size()>0 || mandatoryChangedValMap.size()>0){
                                                for(Long itemId : item.getSameItemsWithDifferentColors()){
                                                        updateItem(itemId);
                                                }
                                        }
                                        item = newItem;
                                        GWT.log("Item updated. Id = " + item.getId());
                                        catalogDashboardPanel.getItemListWidget().updateItem(item);
                                        getFreshItemFromDB(item.getId());
                                        Window.alert("Item updated successfully.");
                                }
                                else {
                                        GWT.log("Error updating item");
                                        Window.alert("Error updating item");
                                }
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Error while updating item");
                        }
                });
        }

        private void getFreshItemFromDB(long id) {
                catalogService.getItem(id, new AsyncCallback<Item>() {
                        @Override
                        public void onSuccess(Item result) {
                                setItemDetails(result);
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Unable to fetch item details.");
                        }
                });
        }

        /**
         * This method is called while updating item.<br> It will create a new Item object and set 
         * its editable attributes with UI fields values and non-editable attributes with old Item
         * object attributes. This new Item object is then passed to the service to update item in the database.
         * <br>If update is successful, the old Item object is replaced with the new Item object. 
         * @return true if new Item object is created successfully
         *     <br>false if some error occurs due to NumberFormatException
         */
        private boolean createNewItem() {

                newItem = new Item();
                newItem.setId(item.getId());
                newItem.setProductGroup(productGroup.getText().trim());
                newItem.setBrand(brand.getText().trim());
                newItem.setModelNumber(modelNumber.getText().trim());
                newItem.setModelName(modelName.getText().trim());
                newItem.setColor(color.getText().trim());
                newItem.setContentCategory(contentCategory.getText());
                newItem.setComments(comments.getText().trim());
                newItem.setCatalogItemId(Long.parseLong(catalogItemId.getText()));
                in.shop2020.catalog.dashboard.shared.PrivateDeal privateDeal = new in.shop2020.catalog.dashboard.shared.PrivateDeal();
                Date dealStartDt  = dealStartDate.getValue();
                Date dealEndDt  = dealEndDate.getValue();
                try {
                        if(!dealPrice.getText().trim().isEmpty()) {
                                double dpValue = Double.parseDouble(dealPrice.getText().trim());
                                if(dpValue <= 0) {
                                        throw new NumberFormatException("Negative value of Deal price");
                                }
                                privateDeal.setDealPrice(dpValue);
                        }
                        else{
                                privateDeal.setDealPrice(0);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Deal Price format/value. Value should be greater than zero");
                        return false;
                }
                if(dealStartDt!=null && privateDeal.getDealPrice() >0){
                        privateDeal.setStartDate(dealStartDt.getTime());
                }
                else if(dealStartDt!=null && privateDeal.getDealPrice()==0){
                        Window.alert("Invalid Deal Price format/value. Value should be greater than zero");
                        return false;
                }
                else if(dealStartDt==null && privateDeal.getDealPrice()>0){
                        Window.alert("Enter valid Start Date");
                        return false;
                }
                /*              if(isDealActive.getValue() && dealStartDt.getTime() < System.currentTimeMillis()){
                        Window.alert("Deal Start Date < Current Date (Either mark InActive or Change Deal Start Date)");
                        return false;
                }*/
                if(dealEndDt!=null && privateDeal.getDealPrice() >0){
                        privateDeal.setEndDate(dealEndDt.getTime());
                }
                else if(dealEndDt!=null && privateDeal.getDealPrice()==0){
                        Window.alert("Invalid Deal Price format/value. Value should be greater than zero");
                        return false;
                }
                else if(dealEndDt==null && privateDeal.getDealPrice()>0){
                        Window.alert("Enter valid End Date");
                        return false;
                }
                if(dealEndDt!=null && dealStartDt!=null && dealEndDt.getTime() < dealStartDt.getTime()){
                        Window.alert("End date can't be less than start date");
                        return false;
                }
                try {
                        if(dealFreebieOption.getSelectedIndex()==1 && freebieItemId.getText().trim().isEmpty()){
                                Window.alert("Invalid Freebie ItemId");
                                return false;
                        }
                        if(dealFreebieOption.getSelectedIndex()==2 && dealFreebieItemId.getText().trim().isEmpty()){
                                Window.alert("Invalid Deal Freebie ItemId");
                                return false;
                        }
                        if(!dealFreebieItemId.getText().trim().equals("")) {
                                long dealFreeItemId = Long.parseLong(dealFreebieItemId.getText().trim());
                                if(dealFreeItemId < 0) {
                                        throw new NumberFormatException("Negative value of dealFreebieItemId ");
                                }
                                privateDeal.setDealFreebieItemId(dealFreeItemId);
                                if(dealFreebieOption.getSelectedIndex()==1){
                                        if(Long.parseLong(freebieItemId.getText().trim()) < 0) {
                                                throw new NumberFormatException("Negative value of dealFreebieItemId ");
                                        }
                                        privateDeal.setDealFreebieItemId(Long.parseLong(freebieItemId.getText().trim()));
                                }
                                privateDeal.setDealFreebieOption(Long.valueOf(dealFreebieOption.getSelectedIndex()));
                        }
                        else{
                                privateDeal.setDealFreebieItemId(0L);
                                privateDeal.setDealFreebieOption(Long.valueOf(dealFreebieOption.getSelectedIndex()));
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid deal freebie ItemId");
                        return false;
                }
                /*if(dealTextOption.getSelectedIndex()==1 && bestDealsText.getText().trim().isEmpty()){
                        Window.alert("Invalid Best Deals Text");
                        return false;
                }*/
                if(dealTextOption.getSelectedIndex()==1){
                        privateDeal.setDealText(bestDealsText.getText().trim());
                        privateDeal.setDealTextOption((long) dealTextOption.getSelectedIndex());
                }
                else if(dealTextOption.getSelectedIndex()==2 && dealText.getText().trim().isEmpty()){
                        Window.alert("Please enter some deal Text");
                        return false;
                }
                else{
                        privateDeal.setDealText(dealText.getText().trim());
                        privateDeal.setDealTextOption((long) dealTextOption.getSelectedIndex());
                }
                privateDeal.setCod(isCodOnDeal.getValue());
                privateDeal.setActive(isDealActive.getValue());
                try{
                        if(dealRank.getText().trim().isEmpty()){
                                privateDeal.setRank(10000L);
                        }
                        else{
                                if(Long.parseLong(dealRank.getText().trim()) < 0){
                                        throw new NumberFormatException(); 
                                }
                                privateDeal.setRank(Long.parseLong(dealRank.getText().trim()));
                        }
                }
                catch(NumberFormatException nex){
                        Window.alert("Invalid Deals Rank");
                        return false;
                }
                newItem.setPrivateDeal(privateDeal);
                if(newItem.getPrivateDeal().getDealPrice()==0 && (newItem.getPrivateDeal().getDealPrice()!=item.getPrivateDeal().getDealPrice())){
                        Window.alert("Deal Price can't be zero");
                        return false;
                }
                try {
                        if(!mrp.getText().trim().isEmpty()) {
                                double mrpValue = Double.parseDouble(mrp.getText().trim());
                                if(mrpValue <= 0) {
                                        throw new NumberFormatException("Negative value of MRP");
                                }
                                newItem.setMrp(mrpValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid MRP format/value. Value should be greater than zero");
                        return false;
                }
                try {
                        if(!sellingPrice.getText().trim().isEmpty()) {
                                double spValue = Double.parseDouble(sellingPrice.getText().trim());
                                if(spValue <= 0) {
                                        throw new NumberFormatException("Negative value of Selling price");
                                }
                                newItem.setSellingPrice(spValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Selling Price format/value. Value shoule be greater than zero");
                        return false;
                }
                try {
                        if(!packQuantity.getText().trim().isEmpty()) {
                                long packQuantityValue = Long.parseLong(packQuantity.getText().trim());
                                if(packQuantityValue < 1) {
                                        throw new NumberFormatException("Illegal value of PackQuantity");
                                }
                                newItem.setPackQuantity(packQuantityValue);
                        }
                        else{
                                Window.alert("Invalid PackQuantity format/value. Value should can't be empty");
                                return false;
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid PackQuantity format/value. Value should be greater than zero");
                        return false;
                }
                try {
                        if(!quantityStep.getText().trim().isEmpty()) {
                                long quantityStepValue = Long.parseLong(quantityStep.getText().trim());
                                if(quantityStepValue < 1) {
                                        throw new NumberFormatException("Illegal value of Quantity Step");
                                }
                                newItem.setQuantityStep(quantityStepValue);
                        }
                        else{
                                Window.alert("Invalid Quantity Step format/value. Value should can't be empty");
                                return false;
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Quantity Step format/value. Value should be greater than zero");
                        return false;
                }
                try {
                        if(!minimumBuyQuantity.getText().trim().isEmpty()) {
                                long minimumBuyQuantityValue= Long.parseLong(minimumBuyQuantity.getText().trim());
                                if(minimumBuyQuantityValue < 1) {
                                        throw new NumberFormatException("Illegal value of Min Buy Qty");
                                }
                                newItem.setMinimumBuyQuantity(minimumBuyQuantityValue);
                        }
                        else{
                                Window.alert("Invalid Min Buy Qty format/value. Value should can't be empty");
                                return false;
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Min Buy Qty format/value. Value should be greater than zero");
                        return false;
                }
                
                try {
                        if(!maximumBuyQuantity.getText().trim().isEmpty()) {
                                long maximumBuyQuantityValue= Long.parseLong(maximumBuyQuantity.getText().trim());
                                if(maximumBuyQuantityValue < 0) {
                                        throw new NumberFormatException("Illegal value of Max Buy Qty");
                                }
                                newItem.setMaximumBuyQuantity(maximumBuyQuantityValue);
                        }
                        else{
                                Window.alert("Invalid Max Buy Qty format/value. Value should can't be empty");
                                return false;
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Min Buy Qty format/value.");
                        return false;
                }
                
                if (Long.parseLong(maximumBuyQuantity.getText().trim()) > 0 && Long.parseLong(maximumBuyQuantity.getText().trim()) < Long.parseLong(minimumBuyQuantity.getText().trim())){
                        Window.alert("MaxBuyQty can't be greater than MinBuyQty.");
                        return false;
                }

                if(newItem.getPrivateDeal().getDealPrice()!=0 && newItem.getPrivateDeal().getDealPrice() >= newItem.getSellingPrice()){
                        Window.alert("Deal Price can't be more than Selling Price");
                        return false;
                }
                try {
                        if(!weight.getText().trim().isEmpty()) {
                                double wtValue = Double.parseDouble(weight.getText().trim());
                                if(wtValue <= 0) {
                                        throw new NumberFormatException("Negative value of Weight");
                                }
                                newItem.setWeight(wtValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid weight format/value. Value should be greater than zero");
                        return false;
                }
                try {
                        if(!startDate.getTextBox().getText().trim().equals("")) {
                                newItem.setStartDate(startDate.getValue().getTime());
                        }
                } catch(Exception ex) {
                        Window.alert("Invalid start date format");
                        return false;
                }
                newItem.setBestDealsText(bestDealsText.getText().trim());
                newItem.setBestDealsDetailsText(bestDealsDetailsText.getText().trim());
                newItem.setBestDealsDetailsLink(bestDealsDetailsLink.getText().trim());
                Date comingSoonStartDt  = comingSoonStartDate.getValue();
                Date expectedArrivalDt  = expectedArrivalDate.getValue();
                if(comingSoonStartDt == null){
                        newItem.setComingSoonStartDate(null);
                }else {
                        newItem.setComingSoonStartDate(comingSoonStartDt.getTime());
                }
                if(expectedArrivalDt == null){
                        newItem.setExpectedArrivalDate(null);
                }else {
                        newItem.setExpectedArrivalDate(expectedArrivalDt.getTime());
                }
                try {
                        if(!bestDealsValue.getText().trim().equals("")) {
                                double bdValue = Double.parseDouble(bestDealsValue.getText().trim());
                                if(bdValue < 0) {
                                        throw new NumberFormatException("Negative value of BestDealValue");
                                }
                                newItem.setBestDealsValue(bdValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid best deal value format");
                        return false;
                }

                try {
                        if(!bestSellingRank.getText().trim().equals("")) {
                                long bsrValue = Long.parseLong(bestSellingRank.getText().trim());
                                if(bsrValue < 0) {
                                        throw new NumberFormatException("Negative value of Best Selling Rank");
                                }
                                newItem.setBestSellingRank(bsrValue);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid best selling rank format");
                        return false;
                }
                newItem.setDefaultForEntity(defaultForEntity.getValue());
                newItem.setRisky(risky.getValue());

                try {
                        if(!minStockLevel.getText().trim().equals("")) {
                                long minStock = Long.parseLong(minStockLevel.getText().trim());
                                if(minStock < 0) {
                                        throw new NumberFormatException("Negative value of Minimum Stock Level");
                                }
                                newItem.setMinStockLevel(minStock);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid minimum Stock Level format");
                        return false;
                }

                try {
                        if(!numOfDaysStock.getText().trim().equals("")) {
                                long numDays = Long.parseLong(numOfDaysStock.getText().trim());
                                if(numDays < 0) {
                                        throw new NumberFormatException("Negative value of num Of Days ");
                                }
                                newItem.setNumOfDaysStock(new Long(numDays).intValue());
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid number Of Days format");
                        return false;
                }
                newItem.setShowSellingPrice(showSellingPrice.getValue());
                newItem.setHoldOverride(holdOverride.getValue());
                try {
                        String expectedDelayText = expectedDelay.getText().trim();
                        if(!expectedDelayText.equals("")){
                                newItem.setExpectedDelay(Integer.parseInt(expectedDelayText));
                        }
                } catch(NumberFormatException nfe) {
                        Window.alert("Invalid expected delay");
                        return false;
                }
                try {
                        if(!freebieItemId.getText().trim().equals("")) {
                                long freeItemId = Long.parseLong(freebieItemId.getText().trim());
                                if(freeItemId < 0) {
                                        throw new NumberFormatException("Negative value of freebieItemId ");
                                }
                                newItem.setFreebieItemId(new Long(freeItemId));
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid freebie ItemId");
                        return false;
                }
                if((item.getPreferredVendor() == null || item.getVendorPricesMap() == null || item.getVendorPricesMap().isEmpty()) && preferredVendor.getSelectedIndex() == 0) {
                        newItem.setPreferredVendor(item.getPreferredVendor());
                }
                else {
                        long vendorId = Utils.getVendorId(preferredVendor.getItemText(preferredVendor.getSelectedIndex()));
                        newItem.setPreferredVendor(vendorId);
                }
                newItem.setPreferredInsurer(Long.parseLong(preferredInsurer.getValue(preferredInsurer.getSelectedIndex())));
                newItem.setWarehouseStickiness(warehouseStickiness.getValue());
                newItem.setHasItemNo(hasItemNo.getValue());
                newItem.setItemType(itemType.getValue());
                newItem.setAsin(asin.getText().trim());
                try {
                        if(!holdInventory.getText().trim().equals("")) {
                                long hold_inventory = Long.parseLong(holdInventory.getText().trim());
                                if(hold_inventory < 0) {
                                        throw new NumberFormatException("Negative value of Hold Inventory");
                                }
                                newItem.setHoldInventory(hold_inventory);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Hold Inventory Value");
                        return false;
                }

                try {
                        if(!defaultInventory.getText().trim().equals("")) {
                                long default_inventory = Long.parseLong(defaultInventory.getText().trim());
                                if(default_inventory < 0) {
                                        throw new NumberFormatException("Negative value of Default Inventory");
                                }
                                newItem.setDefaultInventory(default_inventory);
                        }
                } catch(NumberFormatException ex) {
                        Window.alert("Invalid Default Inventory Value");
                        return false;
                }
                /*Create an instance of VendorPricings for each row in vendor pricing table. Set the vendor prices to the instance.
          Add the instance to map and set the map to the item instance created above.*/
                Map<Long, VendorPricings> vendorPrices = new HashMap<Long, VendorPricings>();
                VendorPricings v;
                for(int row = 0; row < tableVendorPrices.getRowCount(); row++) {
                        v = new VendorPricings();
                        v.setMop(Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_MOP)));
                        v.setDealerPrice(Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_DP)));
                        v.setTransferPrice(Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_TP)));
                        v.setNlc(Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_NLC)));
                        v.setVendorId(Long.parseLong(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_VENDORID)));
                        vendorPrices.put(v.getVendorId(), v);
                }
                newItem.setVendorPricesMap(vendorPrices);
                newItem.setItemStatusDesc(statusDesc.getText().trim());

                /*Create an instance of VendorPricings for each row in vendor pricing table. Set the vendor prices to the instance.
        Add the instance to map and set the map to the item instance created above.*/
                Map<String, VendorItemMapping> vendorMappings = new HashMap<String, VendorItemMapping>();
                VendorItemMapping vMapping;
                for(int row = 0; row < tableVendorItemKey.getRowCount(); row++) {
                        vMapping = new VendorItemMapping();
                        vMapping.setItemKey(tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_ITEM_KEY));
                        vMapping.setVendorId(Long.parseLong(tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_VENDORID)));
                        vendorMappings.put(vMapping.getVendorId() + Item.KEY_SEPARATOR + tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_ITEM_KEY_OLD), vMapping);
                }
                newItem.setVendorKeysMap(vendorMappings);

                /*Create an instance of SourcePricings for each row in source pricing table. Set the source prices to the instance.
        Add the instance to map and set the map to the item instance created above.*/
                Map<Long, SourcePricings> sourcePrices = new HashMap<Long, SourcePricings>();
                SourcePricings s;
                for(int row = 0; row < tableSourcePrices.getRowCount(); row++) {
                        s = new SourcePricings();
                        s.setMrp(Double.parseDouble(tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_MRP)));
                        s.setSellingPrice(Double.parseDouble(tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE)));
                        s.setSourceId(Long.parseLong(tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID)));
                        sourcePrices.put(s.getSourceId(), s);
                }
                newItem.setSourcePricesMap(sourcePrices);

                newItem.setContentCategoryId(item.getContentCategoryId());
                newItem.setFeatureId(item.getFeatureId());
                newItem.setFeatureDescription(item.getFeatureDescription());
                newItem.setAddedOn(item.getAddedOn());
                newItem.setRetireDate(item.getRetireDate());
                newItem.setUpdatedOn(item.getUpdatedOn());
                newItem.setItemStatus(item.getItemStatus());
                newItem.setItemInventory(item.getItemInventory());
                newItem.setSimilarItems(item.getSimilarItems());
                newItem.setVouchersMap(item.getVouchersMap());

                return true;
        }

        /**
         * This method is called when Edit button is clicked corresponding to a row in 
         * vendor prices table. It will pop up a form to edit the vendor prices.
         * @param vendorId
         * @param row
         */
        private void editVendorPrices(final long vendorId, final int row) {
                String mop = tableVendorPrices.getText(row, TABLE_INDEX_PRICING_MOP);
                String dp = tableVendorPrices.getText(row, TABLE_INDEX_PRICING_DP);
                String tp = tableVendorPrices.getText(row, TABLE_INDEX_PRICING_TP);
                String nlc = tableVendorPrices.getText(row, TABLE_INDEX_PRICING_NLC);
                VendorPricesDialog pricesDialog = new VendorPricesDialog(mop, dp, tp, nlc);
                pricesDialog.updateButton.setText("Update");
                pricesDialog.setVendorPriceUpdateListener(new VendorPricesDialog.VendorPriceUpdateListener() {
                        @Override
                        public boolean onUpdate(double mop, double dp, double tp, double nlc, long vendorId) {
                                if(!validateVendorPrices(mop, dp, tp, nlc)) {
                                        return false;
                                }
                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_MOP, mop + "");
                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_DP, dp + "");
                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_TP, tp + "");
                                tableVendorPrices.setText(row, TABLE_INDEX_PRICING_NLC, nlc + "");
                                return true;
                        }
                });
                pricesDialog.show();
        }

        /**
         * This method is called when Edit button is clicked corresponding to a row in 
         * vendor prices table. It will pop up a form to edit the vendor prices.
         * @param vendorId
         * @param row
         */
        private void editSourcePrices(final long sourceId, final int row) {
                String mrp = tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_MRP);
                String sellingPrice = tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE);
                SourcePricesDialog pricesDialog = new SourcePricesDialog(mrp, sellingPrice);
                pricesDialog.updateButton.setText("Update");
                pricesDialog.setSourcePriceUpdateListener(new SourcePricesDialog.SourcePriceUpdateListener() {
                        @Override
                        public boolean onUpdate(double mrp, double sellingPrice, long sourceId) {
                                if(!validateSourcePrices(mrp, sellingPrice)) {
                                        return false;
                                }
                                tableSourcePrices.setText(row, TABLE_INDEX_SOURCE_PRICING_MRP, mrp + "");
                                tableSourcePrices.setText(row, TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE, sellingPrice + "");
                                return true;
                        }
                });
                pricesDialog.show();
        }


        /**
         * This method is called when Edit button is clicked corresponding to a row in 
         * vendor item key table. It will pop up a form to edit the item key.
         * @param vendorId
         * @param row
         */
        private void editVendorKey(final long vendorId, final int row) {
                String key = tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_ITEM_KEY);
                VendorMappingDialog mappingDialog = new VendorMappingDialog(productGroup.getText().trim(), brand.getText().trim(), 
                                modelNumber.getText().trim(), color.getText().trim(), key);
                mappingDialog.updateButton.setText("Update");
                mappingDialog.setVendorMappingUpdateListener(new VendorMappingDialog.VendorMappingUpdateListener() {
                        @Override
                        public boolean onUpdate(String itemKey, long vendorId) {
                                if(itemKey == null || itemKey.equals("")) {
                                        Window.alert("Item key cannot be empty.");
                                        return false;
                                }
                                tableVendorItemKey.setText(row, TABLE_INDEX_MAPPING_ITEM_KEY, itemKey);
                                return true;
                        }
                });
                mappingDialog.show();
        }

        /**
         * This method compares all the editable UI fields values with attributes in the item object.
         * If they differ, the attribute name is appended to a string.
         * @return String showing attributes which are changed by the user for confirmation.
         *      <br>Empty string if nothing is changed.
         */
        private String isItemChanged() {
                StringBuilder sb = new StringBuilder("");
                mandatoryChangedValMap = new HashMap<String, Object>();
                optionalChangedValMap = new HashMap<String, Object>();
                if(!checkParameterIfEqual(brand.getText().trim(), item.getBrand())) {
                        mandatoryChangedValMap.put(MANDATORY_BRAND, brand.getText().trim());
                        sb.append("\n-Brand");
                }
                if(!checkParameterIfEqual(modelNumber.getText().trim(), item.getModelNumber())) {
                        mandatoryChangedValMap.put(MANDATORY_MODEL_NO, modelNumber.getText().trim());
                        sb.append("\n-Model Number");
                }
                if(!checkParameterIfEqual(modelName.getText().trim(), item.getModelName())) {
                        mandatoryChangedValMap.put(MANDATORY_MODEL_NAME, modelName.getText().trim());
                        sb.append("\n-Model Name");
                }
                if(!checkParameterIfEqual(color.getText().trim(), item.getColor())) {
                        sb.append("\n-Color");
                }
                if(!checkParameterIfEqual(statusDesc.getText().trim(), item.getItemStatusDesc())) {
                        sb.append("\n-Status Description");
                }
                if(!checkParameterIfEqual(comments.getText().trim(), item.getComments())) {
                        sb.append("\n-Comments");
                }
                if(!checkParameterIfEqual(newItem.getMrp(), item.getMrp())) {
                        mandatoryChangedValMap.put(MANDATORY_MRP, newItem.getMrp());
                        sb.append("\n-MRP");
                }
                if(!checkParameterIfEqual(newItem.getSellingPrice(), item.getSellingPrice())) {
                        optionalChangedValMap.put(OPTIONAL_SELLING_PRICE, newItem.getSellingPrice());
                        sb.append("\n-Selling Price");
                }
                if(!checkParameterIfEqual(newItem.getWeight(), item.getWeight())) {
                        mandatoryChangedValMap.put(MANDATORY_WEIGHT, newItem.getWeight());
                        sb.append("\n-Weight");
                }
                if(!checkParameterIfEqual(bestDealsText.getText().trim(), item.getBestDealsText())) {
                        mandatoryChangedValMap.put(MANDATORY_BEST_DEAL_TEXT, bestDealsText.getText().trim());
                        sb.append("\n-Best Deal Text");
                }
                if(!checkParameterIfEqual(bestDealsDetailsText.getText().trim(), item.getBestDealsDetailsText())) {
                        mandatoryChangedValMap.put(MANDATORY_BEST_DEAL_DETAIL_TEXT, bestDealsDetailsText.getText().trim());
                        sb.append("\n-Best Deal Detail Text");
                }
                if(!checkParameterIfEqual(bestDealsDetailsLink.getText().trim(), item.getBestDealsDetailsLink())) {
                        mandatoryChangedValMap.put(MANDATORY_BEST_DEAL_DETAIL_LINK, bestDealsDetailsLink.getText().trim());
                        sb.append("\n-Best Deal Detail Link");
                }
                if(!checkParameterIfEqual(newItem.getBestDealsValue(), item.getBestDealsValue())) {
                        sb.append("\n-Best Deal Value");
                }
                if(!checkParameterIfEqual(newItem.getBestSellingRank(), item.getBestSellingRank())) {
                        sb.append("\n-Best Selling Rank");
                }
                if(!checkParameterIfEqual(newItem.getMinStockLevel(), item.getMinStockLevel())) {
                        sb.append("\n-Min Stock Level");
                }
                if(!checkParameterIfEqual(newItem.getNumOfDaysStock(), item.getNumOfDaysStock())) {
                        sb.append("\n-Number Of Days Of Stock");
                }
                if(item.isDefaultForEntity() != defaultForEntity.getValue()) {
                        sb.append("\n-Default For Entity Flag");
                }
                if(item.isRisky() != risky.getValue()) {
                        sb.append("\n-Risky Flag");
                }
                if(!checkParameterIfEqual(newItem.getStartDate(), item.getStartDate())) {
                        sb.append("\n-Start Date");
                }
                if(!checkParameterIfEqual(newItem.getExpectedArrivalDate(), item.getExpectedArrivalDate())) {
                        sb.append("\n-Expected Arrival Date");
                }
                if(!checkParameterIfEqual(newItem.getComingSoonStartDate(), item.getComingSoonStartDate())) {
                        sb.append("\n-Coming Soon Start Date");
                }
                if(!checkParameterIfEqual(newItem.getExpectedDelay(), item.getExpectedDelay())) {
                        sb.append("\n-Expected Delay");
                }
                if(item.isWarehouseStickiness() != warehouseStickiness.getValue()) {
                        sb.append("\n-Warehouse Stickiness Flag");
                }
                if(!checkParameterIfEqual(newItem.getPreferredVendor(), item.getPreferredVendor())) {
                        optionalChangedValMap.put(OPTIONAL_PREFERRED_VENDOR, newItem.getPreferredVendor());
                        sb.append("\n-Preferred Vendor");
                }
                if(!checkParameterIfEqual(newItem.getPreferredInsurer(), item.getPreferredInsurer())) {
                        optionalChangedValMap.put(OPTIONAL_PREFERRED_INSURER, newItem.getPreferredInsurer());
                        sb.append("\n-Preferred Insurer");
                }
                if(item.isHasItemNo() != hasItemNo.getValue()) {
                        sb.append("\n-Has Item Number Flag");
                }
                if(item.isItemType() != itemType.getValue()) {
                        sb.append("\n-Has Serial Number Flag");
                }
                if(item.isShowSellingPrice() != showSellingPrice.getValue()) {
                        sb.append("\n-Coming Soon item pricing marked");
                }
                if(item.isHoldOverride() != holdOverride.getValue()) {
                        sb.append("\n-Hold Override is marked");
                }
                if(!checkParameterIfEqual(newItem.getFreebieItemId(), item.getFreebieItemId())) {
                        optionalChangedValMap.put(OPTIONAL_FREEBIE_ITEM_ID, freebieItemId.getText().trim());
                        sb.append("\n-Freebie Item Id");
                }
                if(newItem.getPrivateDeal().getDealFreebieItemId()!=0){
                        if(newItem.getPrivateDeal().getDealFreebieItemId()!=item.getPrivateDeal().getDealFreebieItemId()) {
                                sb.append("\n-Deal Freebie Item Id");
                        }
                }
                if(newItem.getPrivateDeal().getDealPrice()!=item.getPrivateDeal().getDealPrice()) {
                        sb.append("\n-Deal Price");
                }
                if(newItem.getPrivateDeal().getDealFreebieOption().longValue()!=item.getPrivateDeal().getDealFreebieOption().longValue()) {
                        sb.append("\n-Deal Freebie Option");
                }
                if(!newItem.getPrivateDeal().getDealText().equalsIgnoreCase(item.getPrivateDeal().getDealText())) {
                        sb.append("\n-Deal Text " + newItem.getPrivateDeal().getDealText() +" "+item.getPrivateDeal().getDealText());
                }
                if(newItem.getPrivateDeal().getDealTextOption()!=item.getPrivateDeal().getDealTextOption()) {
                        sb.append("\n-Deal Text Option");
                }
                if(newItem.getPrivateDeal().getRank().longValue()!=item.getPrivateDeal().getRank().longValue()) {
                        sb.append("\n-Deal Rank"+" "+newItem.getPrivateDeal().getRank().longValue()+" "+item.getPrivateDeal().getRank().longValue());
                }
                if(newItem.getPrivateDeal().isCod()!=item.getPrivateDeal().isCod()) {
                        sb.append("\n-Is Deal Cod");
                }
                if(newItem.getPrivateDeal().isActive()!=item.getPrivateDeal().isActive()) {
                        sb.append("\n-Is Deal Active");
                }
                if(!checkParameterIfEqual(newItem.getPrivateDeal().getStartDate(),item.getPrivateDeal().getStartDate())) {
                        sb.append("\n-Deal Start Date");
                }
                if(!checkParameterIfEqual(newItem.getPrivateDeal().getEndDate(),item.getPrivateDeal().getEndDate())) {
                        sb.append("\n-Deal End Date");
                }
                if(!checkParameterIfEqual(asin.getText().trim(), item.getAsin())) {
                        sb.append("\n-Asin");
                }
                if(!checkParameterIfEqual(newItem.getHoldInventory(), item.getHoldInventory())) {
                        sb.append("\n-Hold Inventory");
                }
                if(!checkParameterIfEqual(newItem.getDefaultInventory(), item.getDefaultInventory())) {
                        sb.append("\n-Default Inventory");
                }
                if(!checkParameterIfEqual(newItem.getPackQuantity(),item.getPackQuantity())) {
                        mandatoryChangedValMap.put(OPTIONAL_PACK_QUANTITY, newItem.getPackQuantity());
                        sb.append("\n-PackQuantity");
                }
                if(!checkParameterIfEqual(newItem.getQuantityStep(),item.getQuantityStep())) {
                        mandatoryChangedValMap.put(OPTIONAL_QUANTITY_STEP, newItem.getQuantityStep());
                        sb.append("\n-Quantity Step");
                }

                if(!checkParameterIfEqual(newItem.getMinimumBuyQuantity(),item.getMinimumBuyQuantity())) {
                        mandatoryChangedValMap.put(OPTIONAL_MINIMUM_BUY_QTY, newItem.getMinimumBuyQuantity());
                        sb.append("\n-Min Buy Qty");
                }
                
                if(!checkParameterIfEqual(newItem.getMaximumBuyQuantity(),item.getMaximumBuyQuantity())) {
                        mandatoryChangedValMap.put(OPTIONAL_MAXIMUM_BUY_QTY, newItem.getMaximumBuyQuantity());
                        sb.append("\n-Max Buy Qty");
                }

                VendorPricings vendorPricings;
                long vendorId;
                boolean vendorPricingsChanged = false;
                for(int row = 0; row < tableVendorPrices.getRowCount(); row++) {
                        vendorId = Long.parseLong(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_VENDORID));
                        vendorPricings = item.getVendorPricesMap().get(vendorId);
                        if(vendorPricings == null) {
                                sb.append("\n-Vendor Prices (Vendor:" + vendorId + ")");
                                vendorPricingsChanged = true;
                                continue;
                        }
                        if(vendorPricings.getMop() != Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_MOP))) {
                                vendorPricingsChanged = true;
                                sb.append("\n-MOP (Vendor:" + vendorId + ")");
                        }
                        if(vendorPricings.getDealerPrice() != Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_DP))) {
                                vendorPricingsChanged = true;
                                sb.append("\n-Dealer Price (Vendor:" + vendorId + ")");
                        }
                        if(vendorPricings.getTransferPrice() != Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_TP))) {
                                vendorPricingsChanged = true;
                        }
                        if(vendorPricings.getNlc() != Double.parseDouble(tableVendorPrices.getText(row, TABLE_INDEX_PRICING_NLC))) {
                                vendorPricingsChanged = true;
                        }
                }
                if(vendorPricingsChanged){
                        sb.append("\n-Vendor Pricing");
                        optionalChangedValMap.put(OPTIONAL_VENDOR_PRICING, newItem.getVendorPricesMap());
                }

                SourcePricings sourcePricings;
                boolean sourcePricingsChanged = false;
                long sourceId;
                for(int row = 0; row < tableSourcePrices.getRowCount(); row++) {
                        sourceId = Long.parseLong(tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID));
                        sourcePricings = item.getSourcePricesMap().get(sourceId);
                        if(sourcePricings == null) {
                                sourcePricingsChanged = true;
                                sb.append("\n-Source Prices (Source:" + sourceId + ")");
                                continue;
                        }
                        if(sourcePricings.getMrp() != Double.parseDouble(tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_MRP))) {
                                sourcePricingsChanged = true;
                                sb.append("\n-MRP (Source:" + sourceId + ")");
                        }
                        if(sourcePricings.getSellingPrice() != Double.parseDouble(tableSourcePrices.getText(row, TABLE_INDEX_SOURCE_PRICING_SELLING_PRICE))) {
                                sourcePricingsChanged = true;
                                sb.append("\n-Selling Price (Source:" + sourceId + ")");
                        }

                }
                if(sourcePricingsChanged){
                        sb.append("\n-Source Pricing");
                        optionalChangedValMap.put(OPTIONAL_SOURCE_PRICING, newItem.getSourcePricesMap());
                }
                VendorItemMapping mapping;
                String old_key, new_key;
                for(int row = 0; row < tableVendorItemKey.getRowCount(); row++) {
                        vendorId = Long.parseLong(tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_VENDORID));
                        old_key = tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_ITEM_KEY_OLD);
                        new_key = tableVendorItemKey.getText(row, TABLE_INDEX_MAPPING_ITEM_KEY);
                        mapping = item.getVendorKeysMap().get(vendorId + Item.KEY_SEPARATOR + old_key);
                        if(mapping == null || !old_key.equals(new_key)) {
                                sb.append("\n-Vendor Key (Vendor:" + vendorId + ",Key: = " + old_key + ")");
                                continue;
                        }
                }
                return sb.toString();
        }

        @SuppressWarnings("unused")
        private boolean validatePrices() {
                if(newItem.getSellingPrice() > newItem.getMrp()) {
                        Window.alert("Selling price cannot be more than MRP");
                        return false;
                }
                for(VendorPricings v : newItem.getVendorPricesMap().values()) {
                        if(newItem.getMrp() < v.getMop()) {
                                Window.alert("MRP cannot be less than MOP. Vendor: " + v.getVendorId());
                                return false;
                        }
//                      if(v.getTransferPrice() > v.getMop()) {
//                              Window.alert("Transfer Price cannot be more than MOP. Vendor: " + v.getVendorId());
//                              return false;
//                      }
                }
                return true;
        }

        private boolean validateVendorPrices(double mop, double dp, double tp, double nlc) {
                if(item.getMrp() != null && item.getMrp() < mop) {
                        Window.alert("MOP cannot be more than MRP.");
                        return false;
                }
//              if(tp > mop) {
//                      Window.alert("Transfer Price cannot be more than MOP.");
//                      return false;
//              }
//              if(tp < nlc) {
//                      Window.alert("Transfer Price cannot be less than NLC.");
//                      return false;
//              }
                return true;
        }

        private boolean validateSourcePrices(double mrp, double sellingPrice) {
                if(sellingPrice > mrp) {
                        Window.alert("Selling Price cannot be more than MRP.");
                        return false;
                }
                return true;
        }


        public long getItemId() {
                return item == null ? 0 : item.getId();
        }

        public Item getItem() {
                return item;
        }

        private boolean voucherExists(String voucherType) {
                for(int i = 0; i < tableVouchers.getRowCount(); i++) {
                        if(voucherType.equals(tableVouchers.getText(i, TABLE_INDEX_VOUCHERS_TYPE))) {
                                return false;
                        }
                }
                return true;
        }

        /**
         * This method is used while adding vendor prices to ensure that there is only one row in the table for a vendor.
         * @param vendorId
         * @return true if parameter vendor Id is already added to vendor prices table.
         *      <br>else false
         */
        private boolean vendorExists(long vendorId) {
                long id;
                for(int i = 0; i < tableVendorPrices.getRowCount(); i++) {
                        id = Long.parseLong(tableVendorPrices.getText(i, TABLE_INDEX_PRICING_VENDORID));
                        if(vendorId == id) {
                                return false;
                        }
                }
                return true;
        }

        /**
         * This method is used while adding source prices to ensure that there is only one row in the table for a source.
         * @param sourceId
         * @return true if parameter vendor Id is already added to source prices table.
         *      <br>else false
         */
        private boolean sourceExists(long sourceId) {
                long id;
                for(int i = 0; i < tableSourcePrices.getRowCount(); i++) {
                        id = Long.parseLong(tableSourcePrices.getText(i, TABLE_INDEX_SOURCE_PRICING_SOURCE_ID));
                        if(sourceId == id) {
                                return false;
                        }
                }
                return true;
        }

        /**
         * This method is used to check if any of the string item attributes is changed by the user.
         * @param o1
         * @param o2
         * @return true if two strings are equal
         *      <br>true if one of them is null and another is empty.
         *      <br>false otherwise
         */
        
        private boolean checkParameterIfEqual(Object o1, Object o2) {
                if(o1 == o2) {
                        return true;
                }
                if(o1 != null && o2 != null && o1.equals(o2)) {
                        return true;
                }
                if((o1 == null && o2.equals("")) || (o2 == null && o1.equals(""))) {
                        return true;
                }
                return false;
        }

        public void setCatalogDashboardPanel(CatalogDashboard catalogDashboardPanel) {
                this.catalogDashboardPanel = catalogDashboardPanel;
        }

        private String compareSellingPricewithBreakEven() {
                String message = "false";
                if(newItem.getWeight() == null) {
                        Window.alert("Weight is empty.");
                        return message;
                }
                if(newItem.getSellingPrice() == null) {
                        Window.alert("Selling Price is empty.");
                        return message;
                }

                double transferPrice;
                if(newItem.getPreferredVendor() == null && !newItem.getVendorPricesMap().isEmpty()) {
                        transferPrice = -1;
                        for(VendorPricings vendorDetail : newItem.getVendorPricesMap().values()){
                                if(transferPrice > vendorDetail.getNlc() || transferPrice == -1){
                                        transferPrice = vendorDetail.getNlc();
                                }
                        }
                }
                else if(!newItem.getVendorPricesMap().isEmpty() && newItem.getVendorPricesMap().containsKey(newItem.getPreferredVendor())){
                        transferPrice = newItem.getVendorPricesMap().get(newItem.getPreferredVendor()).getNlc();                
                }
                else{
                        Window.alert("Add vendor to Vendor Prices and then change the Selling Price.");
                        return message;
                }

                double weightfactor = Math.ceil((newItem.getWeight() * 1000)/Double.parseDouble(ConfigMap.get("courier_weight_factor")));
                double couriercost = Double.parseDouble(ConfigMap.get("courier_cost_factor")) * weightfactor;
                double costfactor = (Double.parseDouble(ConfigMap.get("transfer_price_percentage")) * transferPrice)/100;
                double breakeven;
                if(costfactor < Double.parseDouble(ConfigMap.get("transfer_price_factor"))){
                        breakeven = transferPrice + couriercost + Double.parseDouble(ConfigMap.get("breakeven_additon_factor"));
                }
                else{
                        breakeven = (transferPrice + couriercost)/Double.parseDouble(ConfigMap.get("breakeven_divisor"));
                }

                if(breakeven > newItem.getSellingPrice()) {
                        message = "Selling Price("+newItem.getSellingPrice()+") is less than Breakeven Price("+breakeven+").";
                        if(Window.confirm(message)){
                                return message;
                        }
                        else{
                                message = "false";
                                Window.alert("Updation of Item is canceled.");
                                return message;
                        }
                }
                else {
                        message = "true";
                        return message;
                }
        }

        private String checkTransferPriceforPreferredVendor() {
                String message = "false";
                if(newItem.getPreferredVendor() == null) {
                        message = "true";
                        return message;
                }
                else if(!newItem.getVendorPricesMap().isEmpty() && newItem.getVendorPricesMap().containsKey(newItem.getPreferredVendor())){
                        double transferPrice = newItem.getVendorPricesMap().get(newItem.getPreferredVendor()).getTransferPrice();
                        double mintransferPrice = -1;
                        String minvendor = "";
                        boolean compareTransferPrices = false;
                        for(VendorPricings vendorDetail : newItem.getVendorPricesMap().values()){
                                if(mintransferPrice > vendorDetail.getTransferPrice() || mintransferPrice == -1){
                                        mintransferPrice = vendorDetail.getTransferPrice();
                                        minvendor = Utils.getVendorDesc(vendorDetail.getVendorId());
                                }
                        }
                        if(!checkParameterIfEqual(newItem.getPreferredVendor(), item.getPreferredVendor()) || item.getVendorPricesMap().isEmpty()) {
                                compareTransferPrices = true;
                        }
                        else {
                                double oldmintransferPrice = -1;
                                for(VendorPricings vendorDetail : item.getVendorPricesMap().values()){
                                        if(oldmintransferPrice > vendorDetail.getTransferPrice() || oldmintransferPrice == -1){
                                                oldmintransferPrice = vendorDetail.getTransferPrice();
                                        }
                                }
                                if(mintransferPrice < oldmintransferPrice){
                                        compareTransferPrices = true;
                                }
                        }
                        if(compareTransferPrices && transferPrice > mintransferPrice){
                                message = "Transfer Price("+transferPrice+") of Preferred Vendor("+Utils.getVendorDesc(newItem.getPreferredVendor())+") is more than Transfer Price("+mintransferPrice+") of "+minvendor+".";
                                if(Window.confirm(message)){
                                        return message;
                                }
                                else{
                                        message = "false";
                                        Window.alert("Updation of Item is canceled.");
                                        return message;
                                }
                        }
                        else {
                                message = "true";
                                return message;
                        }
                }
                else{
                        Window.alert("Add vendor to Vendor Prices and then change the Preferred Vendor.");
                        return message;
                }
        }

        private boolean checkBulkPricing(long quantity) {
                long row_quantity;
                for(int i = 0; i < tableBulkPricing.getRowCount(); i++) {
                        row_quantity = Long.parseLong(tableBulkPricing.getText(i, TABLE_INDEX_QUANTITY));
                        if(quantity == row_quantity) {
                                return false;
                        }
                }
                return true;
        }

        public void logAuthorization(String message) {
                String username = catalogDashboardPanel.uname;
                catalogService.addAuthorizationLog(newItem.getId(), username, message, new AsyncCallback<Boolean>() {
                        @Override
                        public void onSuccess(Boolean result) {
                                if(result) {
                                        GWT.log("Event is added");
                                }
                                else {
                                        GWT.log("Error adding the event");
                                        Window.alert("Error adding the event");
                                }
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Error while adding the event");
                        }
                });
        }

        @Override
        public void setComingSoonStartDate(Date date) {
                this.comingSoonStartDate.setValue(date);

        }

        @Override
        public void setBestDealsText(String bestDealsText) {
                this.bestDealsText.setValue(bestDealsText);

        }

        @Override
        public void setExpectedArrivalDate(Date date) {
                this.expectedArrivalDate.setValue(date);

        }

        @Override
        public String getBestDealsText() {
                return this.bestDealsText.getValue();
        }

        public void setBestDealsDetailsText(String bestDealsDetailsText) {
                this.bestDealsDetailsText.setValue(bestDealsDetailsText);

        }

        public String getBestDealsDetailsText() {
                return this.bestDealsDetailsText.getValue();
        }

        @Override
        public Date getComingSoonStartDate() {
                return this.comingSoonStartDate.getValue();
        }

        @Override
        public Date getExpectedArrivalDate() {
                return this.expectedArrivalDate.getValue();
        }
        @UiHandler("comingSoonButton")
        void onComingSoonButtonClick(ClickEvent event) {
                ComingSoonDialog cd = new ComingSoonDialog(this);
                cd.show();
        }

        private void createDialog(String changedString) {
                VerticalPanel vp = new VerticalPanel();
                final DialogBox db = new DialogBox();
                db.setText("Changed fields");

                vp.add(new Label("Check the fields to update all SKUs with similar entity."));
                vp.add(new Label("--------------------------------------------------------"));
                CheckBox allChecked = new CheckBox("Select all");
                if(optionalChangedValMap.size()>1){
                        allChecked.setName("all");
                        allChecked.addClickHandler(new ClickHandler() {
                                @Override
                                public void onClick(ClickEvent event) {
                                        CheckBox cb = (CheckBox)event.getSource();
                                        VerticalPanel vp = (VerticalPanel)cb.getParent();
                                        Iterator<Widget> iterator = vp.iterator();
                                        while(iterator.hasNext()){
                                                Widget w = iterator.next();
                                                if(w instanceof CheckBox){
                                                        CheckBox cbox = (CheckBox)w;
                                                        if(cbox.getName()!="all"){
                                                                cbox.setValue(cb.getValue());
                                                        }
                                                }
                                        }
                                        if(cb.getValue()){
                                                cb.setText("Deselect all");
                                        }else {
                                                cb.setText("Select all");
                                        }
                                }
                        });
                        vp.add(allChecked);
                }
                String[] changedFields = changedString.split("\n-");
                for(String changeField : changedFields){
                        if(optionalChangedValMap.containsKey(changeField)){
                                CheckBox ch = new CheckBox(changeField); 
                                ch.getElement().getStyle().setPadding(10d, Unit.PX);
                                vp.add(ch);
                        } else {
                                Label l = new Label(changeField);
                                l.getElement().getStyle().setMarginLeft(10d, Unit.PX);
                                l.getElement().getStyle().setPadding(10d, Unit.PX);
                                vp.add(l);
                        }
                }

                Button submitButton = new Button();
                submitButton.setText("Update");
                submitButton.addClickHandler(new ClickHandler() {

                        @Override
                        public void onClick(ClickEvent event) {
                                Button b  = (Button)event.getSource();
                                VerticalPanel vp = (VerticalPanel)b.getParent();
                                Iterator<Widget> iterator = vp.iterator();
                                while(iterator.hasNext()){
                                        Widget w = iterator.next();
                                        if(w instanceof CheckBox){
                                                CheckBox cbox = (CheckBox)w;
                                                if(cbox.getName()!="all"){
                                                        if(!cbox.getValue()){
                                                                optionalChangedValMap.remove(cbox.getText());
                                                        }
                                                }
                                        }
                                }
                                db.hide();
                                List<Item> items = new ArrayList<Item>();
                                items.add(newItem);
                                validateNUpdate();
                                /*for(Long id : item.getSameItemsWithDifferentColors()){
                                        catalogService.getItem(id, new AsyncCallback<Item>() {
                                    @Override
                                    public void onSuccess(Item result) {
                                        items.add(e)
                                    }
                                    @Override
                                    public void onFailure(Throwable caught) {
                                        caught.printStackTrace();
                                        Window.alert("Unable to fetch item details.");
                                    }
                                });
                                }*/
                        }

                });
                vp.add(submitButton);
                db.add(vp); 
                db.center();
                db.show();   
        }

        private void updateItem(Long itemId) {
                catalogService.getItem(itemId, new AsyncCallback<Item>() {
                        @Override
                        public void onSuccess(Item result) {
                                final Item res = result;
                                if(mandatoryChangedValMap.containsKey(MANDATORY_BRAND)){
                                        result.setBrand((String)mandatoryChangedValMap.get(MANDATORY_BRAND));
                                }
                                if(mandatoryChangedValMap.containsKey(MANDATORY_BEST_DEAL_TEXT)){
                                        result.setBestDealsText((String)mandatoryChangedValMap.get(MANDATORY_BEST_DEAL_TEXT));
                                }
                                if(mandatoryChangedValMap.containsKey(MANDATORY_BEST_DEAL_DETAIL_TEXT)){
                                        result.setBestDealsDetailsText((String)mandatoryChangedValMap.get(MANDATORY_BEST_DEAL_DETAIL_TEXT));
                                }
                                if(mandatoryChangedValMap.containsKey(MANDATORY_BEST_DEAL_DETAIL_LINK)){
                                        result.setBestDealsDetailsLink((String)mandatoryChangedValMap.get(MANDATORY_BEST_DEAL_DETAIL_LINK));
                                }
                                if(mandatoryChangedValMap.containsKey(MANDATORY_MODEL_NAME)){
                                        result.setModelName((String)mandatoryChangedValMap.get(MANDATORY_MODEL_NAME));
                                }
                                if(mandatoryChangedValMap.containsKey(MANDATORY_MODEL_NO)){
                                        result.setModelNumber((String)mandatoryChangedValMap.get(MANDATORY_MODEL_NO));
                                }
                                if(mandatoryChangedValMap.containsKey(MANDATORY_WEIGHT)){
                                        result.setWeight((Double)mandatoryChangedValMap.get(MANDATORY_WEIGHT));
                                }
                                if(mandatoryChangedValMap.containsKey(MANDATORY_MRP)){
                                        result.setMrp((Double)mandatoryChangedValMap.get(MANDATORY_MRP));
                                }
                                if(optionalChangedValMap.containsKey(OPTIONAL_FREEBIE_ITEM_ID)) {
                                        result.setFreebieItemId((Long)optionalChangedValMap.get(OPTIONAL_FREEBIE_ITEM_ID));
                                }
                                if(optionalChangedValMap.containsKey(OPTIONAL_PREFERRED_VENDOR)){
                                        result.setPreferredVendor((Long)optionalChangedValMap.get(OPTIONAL_PREFERRED_VENDOR));
                                }
                                if(optionalChangedValMap.containsKey(OPTIONAL_PREFERRED_INSURER)){
                                        result.setPreferredInsurer((Long)optionalChangedValMap.get(OPTIONAL_PREFERRED_INSURER));
                                }
                                if(optionalChangedValMap.containsKey(OPTIONAL_SELLING_PRICE)){
                                        result.setSellingPrice((Double)optionalChangedValMap.get(OPTIONAL_SELLING_PRICE));
                                }
                                if(optionalChangedValMap.containsKey(OPTIONAL_SOURCE_PRICING)){
                                        result.setSourcePricesMap((Map<Long, SourcePricings>) optionalChangedValMap.get(OPTIONAL_SOURCE_PRICING));
                                }
                                if(optionalChangedValMap.containsKey(OPTIONAL_VENDOR_PRICING)){
                                        result.setVendorPricesMap((Map<Long, VendorPricings>) optionalChangedValMap.get(OPTIONAL_VENDOR_PRICING));
                                }

                                catalogService.updateItem(result, new AsyncCallback<Boolean>() {

                                        @Override
                                        public void onSuccess(Boolean result1) {
                                                if(result1) {
                                                        Window.alert(res.getId() + " updated Successfully");
                                                }

                                        }

                                        @Override
                                        public void onFailure(Throwable caught) {
                                                caught.printStackTrace();
                                                Window.alert("Error updating item " + res.getId());

                                        }
                                });
                        }
                        @Override
                        public void onFailure(Throwable caught) {
                                caught.printStackTrace();
                                Window.alert("Unable to fetch item details.");
                        }
                });
        }

        @Override
        public void setShowPrice(boolean b) {
                this.showSellingPrice.setValue(b);
        }

        @Override
        public boolean isShowPrice() {
                return this.showSellingPrice.getValue();
        }
}