/*!
 * author: Felipe Tonon
 */
 
var globalListingId = 0;
var globalCategoriesId = 0;

/*
	functions
*/
function lightBoxImages(arg1, arg2, arg3) {
	var i = 0;
	var prefixo = "link_image_";
	while (getById(prefixo + i)) {
		$('#' + prefixo + i).lightBox();
		i++;
	}
}
function rimuovereImmagine(idImage, dsPath) {

	function rimuovereImmagine_confirmed(button, idImage, dsPath) {
		if (button == "yes") {
			var dataJson = {
				removingImage : 1,
				'idImage' : idImage,
				'dsPath' : dsPath,
			};
			$.ajax({
				url: "action_prodotti.php",
				type: "POST",
				data: dataJson,
				success: function(data, textStatus, jqXHR){
					pImages.getUpdater().showLoading();
					pImages.getUpdater().refresh(lightBoxImages);	
					msgExt("Image removed successfuly!", "Success" );
				},
				error: function(jqXHR, textStatus, errorThrown) {
					msgExt("Error while trying to remove image!", "Errore!");
					pImages.getUpdater().refresh();	
				}
			});
		}
	}

	Ext.Msg.confirm(
		'Removing', 
		'Do you really want to remove this image?', 
		function(button, arg2, arg3) { 
			rimuovereImmagine_confirmed(button, idImage, dsPath) 
		}, 
		this
	);

}


/* Grid Class:*/
ProdottiGrid = function(limitColumns){

	var urlActionFile = "http://www.pubblicommerce.com/action_prodotti.php";

    var columns = [
        {header: "id", width: 45, sortable: false, dataIndex: 'id'},
        {id:'nomep', header: "Nome", sortable: true, dataIndex: 'nomep',
				editor: new Ext.form.TextField({allowBlank: true})
		},
        {id:'descp', header: "Descrizione", sortable: true, dataIndex: 'descp',
				editor: new Ext.form.TextField({allowBlank: true})
		},		
        {id:'categories_name',header: "Categoria", width: 160, sortable: true, dataIndex: 'categories_name'},
        {id:'pricep',header: "Price", width: 80, sortable: true, dataIndex: 'pricep',
			editor: new Ext.form.NumberField({
                    allowBlank: false,
                    allowNegative: false,
                    maxValue: 100000
                }), renderer : formatPrice},
		{header: "Azioni", width: 120, sortable: false, dataIndex: 'actions', renderer : formatActions},				
        //{header: "Image", width: 100, sortable: false, dataIndex: 'img_cat'},
    ];
	
	function formatActions(value, p, record) {
		return String.format('<a href="prodotti.php?id_prodotto={0}&lid={1}">Modifica</a>', value, globalListingId);
	}

	function formatPrice(value, p, record) {
		//return String.format('<a href="{0}">{0}</a>', value); 
		// var values = value.split("|");
		
		var v = value;
		v = (Math.round((v-0)*100))/100;
		v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
		return ('&euro;' + v).replace(/\./, ',');
	};		
	
	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
			if (isAdding) {
				ProdottiGrid.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 idItem = -1;
		var isAdding = true;
		
		if (Number(e.record.data.id)) {
			idItem = e.record.data.id;
			isAdding = false;
		}
		var dataJson = {
			id : idItem,
			fieldIndex : e.column,
			fieldName : e.field,
			newValue : e.value
		};
		
		e.grid.body.mask('Working...');
		$.ajax({
		  url: urlActionFile + "?listing_id=" + globalListingId + "&categories_id=" + globalCategoriesId,
		  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 Record = ProdottiGrid.store.recordType;
		var c = new Record({
			categories_name: '',
		});
		button.ownerCt.ownerCt.stopEditing();
		ProdottiGrid.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) {
			ProdottiGrid.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 gridInQuestion = objectModal.scope;
		if (button == "yes") {
			gridInQuestion.body.mask('Working...');
			var id = gridInQuestion.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);
					gridInQuestion.body.unmask();
				  },
				  error: function(jqXHR, textStatus, errorThrown) {
					alert("request error");
					gridInQuestion.body.unmask();
				  }
				});	
			} else {
				gridInQuestion.store.reload();
				gridInQuestion.body.unmask();
			}
		}
	};
	
	function deleteItem(button) {
		var id = 0;
		
		var selection = button.ownerCt.ownerCt.selModel.selection;
		if (selection) {
			var name = selection.record.data.categories_name;
			id = selection.record.data.id;
			var msg = 'Do you really want to remove the categorie <b>' + name + '</b> ?';
			Ext.Msg.confirm('Removing', msg, deleteItemConfirmed, button.ownerCt.ownerCt);			
		} else {
			Ext.Msg.show({
				title: 'Deleting...',
				msg: 'You must select a row',
				modal: true,
				icon: Ext.Msg.INFO,
				buttons: Ext.Msg.OK
			});	
		}
	}

	ProdottiGrid.store = new Ext.data.Store({
        url: urlActionFile + '?reading=1&listing_id=' + globalListingId + '&categories_id=' + globalCategoriesId,
		autoLoad : true,
		sortInfo: {field:'nomep', direction:'ASC'},
        reader: new Ext.data.XmlReader({
            // records will have a 'plant' tag
            record: 'prodotto',
            // 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: 'nomep', type: 'string'},
				{name: 'descp', type: 'string'},		
                {name: 'categories_name', type: 'string'},
                {name: 'pricep', type: 'string'},
                {name: 'actions', type: 'string'},
            ]
        }),
	});	
	
    ProdottiGrid.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: ProdottiGrid.store,
		colModel :  new Ext.grid.ColumnModel({ columns : columns}),
        autoExpandColumn: 'descp',
		autoHeight: true,	
        // height:350,
        // width:600
    });
}

