/*!
 * author: Felipe Tonon
 */

var globalListingId = 0;
var globalCatParent = -1;

CategorieGrid = function(o){
/*
	Ext.ns("Ext.ux.renderer");

	Ext.ux.renderer.ComboRenderer = function(options) {
		var value = options.value;
		var combo = options.combo;

		var returnValue = value;
		var valueField = combo.valueField;
			
		var idx = combo.store.findBy(function(record) {
			if(record.get(valueField) == value) {
				returnValue = record.get(combo.displayField);
				return true;
			}
		});
		
		// This is our application specific and might need to be removed for your apps
		if(idx < 0 && value == 0) {
			returnValue = '';
		}
		
		return returnValue;
	};

	Ext.ux.renderer.Combo = function(combo) {
		return function(value, meta, record) {
			return ExtHelper.renderer.ComboRenderer({value: value, meta: meta, record: record, combo: combo});
		};
	}
*/
	var urlActionFile = "http://www.pubblicommerce.com/action_categorie.php";

    var columns = [
        {header: "id", width: 70, sortable: false, dataIndex: 'id', hidden : true},
        {id:'categories_name',header: "Titolo", width: 160, sortable: true, dataIndex: 'categories_name', 
				editor: new Ext.form.TextField({allowBlank: false})
		},
        {id:'categories_description', header: "Descrizione", sortable: true, dataIndex: 'categories_description',
				editor: new Ext.form.TextField({allowBlank: true})
		},
        {header: "Qt Sotto Cat.", width: 70, sortable: false, dataIndex: 'num_sotto_cat', renderer : formatQt},
        {header: "Qt Prodotti", width: 70, sortable: false, dataIndex: 'num_prodotti', renderer : formatQt},
        {header: "Azioni", width: 120, sortable: false, dataIndex: 'actions', renderer : formatActions},
		{header: "Genitora", width: 70, sortable: false, dataIndex: 'categoria_genitora', renderer : formatGenitora, hidden : true},		
    ];

	function formatQt(value, p, record) {
		if (Number(value) < 1){
			return value;
		} else {
			return String.format('<b>{0}</b>', value);
		}
	}
	
	function formatGenitora(value, p, record) {
		if (!value) {
			return "";
		}	
		var valueJSON = stringToJson(value);
		return valueJSON.name;
	}
	
	function formatActions(value, p, record) {
		if (!value) {
			return "";
		}
		var valueJSON = stringToJson(value);
		var templatePresence = '<font color="#000000">{0}</font>';
		var strCatChildren = valueJSON.num_cat_children;
		if (valueJSON.num_cat_children > 0) {
			strCatChildren = String.format(templatePresence, valueJSON.num_cat_children);
		}
		var strNumProdotti = valueJSON.num_prodotti;
		if (valueJSON.num_prodotti > 0) {
			strNumProdotti = String.format(templatePresence, valueJSON.num_prodotti);
		}
		return String.format('<a href="ecommerce.php?lid={0}&categories_id={1}">Modifica</a>' + 
				'&nbsp;&nbsp;&nbsp;<a href="prodotti.php?lid={0}&categories_id={1}">Prodotti</a> ', 
				globalListingId, valueJSON.id); 
				
		/* 
		return String.format('<a href="ecommerce.php?lid={0}&categories_id={1}">Sotto categorie({3})</a>' + 
				' <a href="prodotti.php?lid={0}&categories_id={1}">Prodotti({2})</a> ', 
				globalListingId, valueJSON.id, strNumProdotti, strCatChildren);  
		*/				
	};
	
	function handleResponseEdit(e, data, textStatus, jqXHR, isAdding) {
		// alert(data);
		var responseJSON = eval('(' + data + ')');
		if (responseJSON.success) {
			Ext.Msg.show({
                title: 'Saved',
                msg: 'Saved successfully!',
                modal: true,
                icon: Ext.Msg.INFO,
                buttons: Ext.Msg.OK
            });
			e.record.commit(); // mark as saved
			CategorieGrid.store.reload();
		} else {
			Ext.Msg.show({
                title: 'Data Problem',
                msg: 'It was not possible to update the data!',
                modal: true,
                icon: Ext.Msg.INFO,
                buttons: Ext.Msg.OK
            });
		}
	};
	
	function afterEdit(e) {
		var idCategoria = -1;
		var isAdding = true;
		
		if (Number(e.record.data.id)) {
			idCategoria = e.record.data.id;
			isAdding = false;
		}
		var dataJson = {
			id : idCategoria,
			fieldIndex : e.column,
			fieldName : e.field,
			newValue : clearSpecialChars(e.value)
		};
		
		e.grid.body.mask('Working...');
		$.ajax({
		  url: urlActionFile + "?listing_id=" + globalListingId  + '&categories_id=' + globalCatParent,
		  type: "POST",
		  data: dataJson,
		  success: function(data, textStatus, jqXHR){
			handleResponseEdit(e, data, textStatus, jqXHR, isAdding);
			e.grid.body.unmask();
		  },
		  error: function(jqXHR, textStatus, errorThrown) {
			alert("request error");
			e.grid.body.unmask();
		  }
		});

	};	
	
	function addItem(button) {
		var Categoria = CategorieGrid.store.recordType;
		var c = new Categoria({
			// categories_name: 'Nuova Categoria',
			categories_name: '',
			num_sotto_cat: 0,
			num_prodotti: 0,
		});
		button.ownerCt.ownerCt.stopEditing();
		CategorieGrid.store.insert(0, c);
		button.ownerCt.ownerCt.startEditing(0, 1);
	}
	
	function handleResponseDelete(data, textStatus, jqXHR) {
		var responseJSON;
		if (data) {
			responseJSON = eval('(' + data + ')');
		}
		
		if (responseJSON.success) {
			CategorieGrid.store.reload();
			Ext.Msg.show({
                title: 'Success',
                msg: 'The data was successfully removed!',
                modal: true,
                icon: Ext.Msg.INFO,
                buttons: Ext.Msg.OK
            });
		} else {
			Ext.Msg.show({
                title: 'Data Problem',
                msg: 'It was not possible to remove the data!',
                modal: true,
                icon: Ext.Msg.INFO,
                buttons: Ext.Msg.OK
            });
		}
	};	
	
	function deleteItemConfirmed(button, arg1, objectModal) {
		var gridCategoria = objectModal.scope;
		if (button == "yes") {
			gridCategoria.body.mask('Working...');
			var id = gridCategoria.selModel.selection.record.data.id;
			if (id) {
				$.ajax({
				  url: urlActionFile + "?deleting=1&listing_id=" + globalListingId,
				  type: "POST",
				  data: {"id" : id},
				  success: function(data, textStatus, jqXHR){
					handleResponseDelete(data, textStatus, jqXHR);
					gridCategoria.body.unmask();
				  },
				  error: function(jqXHR, textStatus, errorThrown) {
					alert("request error");
					gridCategoria.body.unmask();
				  }
				});	
			} else {
				gridCategoria.store.reload();
				gridCategoria.body.unmask();
			}
		}
	};
	
	function deleteItem(button) {
		var id = 0;
		
		var selection = button.ownerCt.ownerCt.selModel.selection;
		if (selection) {
		
			var jsonColumns = selection.record.data
			var name = jsonColumns.categories_name;
			var jsonActions = stringToJson(jsonColumns.actions);
			
			id = jsonColumns.id;
			if (jsonColumns.num_prodotti < 1 && jsonActions.num_cat_children < 1) {
				var msg = 'Do you really want to remove the categorie <b>' + name + '</b> ?';
				Ext.Msg.confirm('Removing', msg, deleteItemConfirmed, button.ownerCt.ownerCt);			
			} else {
				var msgImpossible = String.format('It is not possible to remove the categorie <b>{0}</b> <br>since it has subcategories or products attached!',
						name);
			
				Ext.Msg.show({
					title: 'Deleting...',
					msg: msgImpossible,
					modal: true,
					icon: Ext.Msg.INFO,
					buttons: Ext.Msg.OK
				});	
			
			}
			
		} else {
			Ext.Msg.show({
				title: 'Deleting...',
				msg: 'You must select a row',
				modal: true,
				icon: Ext.Msg.INFO,
				buttons: Ext.Msg.OK
			});	
		}
	}

	CategorieGrid.store = new Ext.data.Store({
        url: urlActionFile + '?reading=1&listing_id=' + globalListingId + '&categories_id=' + globalCatParent ,
		autoLoad : true,
		sortInfo: {field:'categories_name', direction:'ASC'},
        reader: new Ext.data.XmlReader({
            // records will have a 'plant' tag
            record: 'categoria',
            // use an Array of field definition objects to implicitly create a Record constructor
            fields: [
                // the 'name' below matches the tag name to read, except 'availDate'
                // which is mapped to the tag 'availability'
                {name: 'id', type: 'string'},
                {name: 'categories_name', type: 'string'},
				{name: 'categories_description', type: 'string'},
				{name: 'num_sotto_cat', type: 'string'},		
				{name: 'num_prodotti', type: 'string'},		
				{name: 'actions', type: 'string'},		
				{name: 'categoria_genitora', type: 'string'},		
            ]
        }),
	});	
	
	Ext.apply(this, o);
	
    CategorieGrid.superclass.constructor.call(this, {
		tbar: [{
			text: 'Aggiungere',
			handler : function(){
				addItem(this);
			}
		},{
			text: 'Rimuovere',
			handler : function(button){
				deleteItem(this);
			}
		},{
			text: 'Aggiornare',
			handler : function(button){
				// reloads the grid
				button.ownerCt.ownerCt.getStore().reload();
			}			
		}],
		listeners: {afteredit : function(e) {afterEdit(e)}},
        store: CategorieGrid.store,
		colModel :  new Ext.grid.ColumnModel({ columns : columns}),
        autoExpandColumn: 'categories_description',
		autoHeight: true,
        // height:350,
        // width:600
    });
}

