/*
 * Ext JS Library 2.2.1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.onReady(function(){
    Ext.QuickTips.init();


    // shorthand alias
    var fm = Ext.form;

    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store (created below)
    var cm = new Ext.grid.ColumnModel(
    		[	
    			{id:'id', editable:false, header: "Id", dataIndex: 'id', sortable:true, width: 32, editor: new fm.NumberField({allowBlank: false,allowNegative: false,maxValue: 100000})},    		 	
    			{id:'ad', header: "Adi", dataIndex: 'ad', sortable:true, width:160, editor: new fm.TextField({allowBlank: true}), renderer: _decodeURI},
    		 	{id:'aciklama', header: "Aciklamasi", dataIndex: 'aciklama', sortable:true, editor: new fm.TextField({allowBlank: false}), renderer: _decodeURI},
    		 	{id:'adres', editable:true, header: "Adresi", dataIndex: 'adres', sortable:true, width: 62, editor: new fm.TextField({allowBlank: true}), renderer: adresiAyarla}
	         ]);

    // by default columns are sortable
    cm.defaultSortable = true;

    // this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    var Plant = Ext.data.Record.create([
           // the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name: 'id', type: 'number'},
           {name: 'ad', type: 'string'},
           {name: 'aciklama', type: 'string'},
           {name: 'adres', type: 'string'}
      ]);

    // create the Data Store
    var kaynak = new Ext.data.JsonStore
	({
		totalProperty: "toplamKayit",  
		url: 'JsonDondur.aspx?pSecim=8',
	    root: 'programlar',
	    id:'jSProgramlar',
	    idProperty: 'id',
	    remoteSort: true,
	    fields: [{name:'id', type:'number'}, 'ad', 'aciklama', 'adres']
	}) ;
	kaynak.setDefaultSort('id', 'asc');
	//kaynak.load({params:{start: 0, limit: 1}, callback:function(){alert(kaynak.getAt(0).get('name'));}}) ;	

    // create the editor grid
    var grid = new Ext.grid.EditorGridPanel({
        store: kaynak,
        cm: cm,
        id:'editableGrid',
        autoExpandColumn: 'aciklama',
        //renderTo: 'editor-grid',
        //width:900,
        //height:300,
		//layout: 'fit',
        title:'Faydali Programlar',
        frame:true,
        clicksToEdit:1,
        tbar: [{text: 'Ekle',handler : function(){
                var p = new Plant({
                	id: 0,
                	ad: 'program adi',
                	adres: 'indirme adresi',
                	aciklama: 'ne ise yaradigi'
                });
                grid.stopEditing();
                kaynak.insert(0, p);
                grid.startEditing(0, 0);
            }
        },
        {text: 'Kaydet',handler : 
        	function(){kaydet();}
        }],
        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: kaynak,
            id: '_bbar',
            displayInfo: true,
            displayMsg: 'Gosterilen program {0}-{1}  Toplam:{2}',
            emptyMsg: "Gosterecek program yok."
        })
    });
	var _viewport = new Ext.Viewport({
        layout: 'fit',
        items: grid,
        renderTo: Ext.getBody()
    });  
    // trigger the data store load
    kaynak.load({
        params: {
            start: 0,
            limit: 10
        }
    });	
});

// yenile butonuna basildiginda sunucu tarafinda anlamak icin gereken kisim.

Ext.PagingToolbar.prototype.doRefresh = function() {
    gridYenile(this);
    };
    
function gridYenile(pThis){
    var o = {}, pn = pThis.getParams();
    o[pn.start] = pThis.cursor;
    o[pn.limit] = pThis.pageSize;
    o["iseYenilensin"] = 1;
    if(pThis.fireEvent('beforechange', pThis, o) !== false){
        pThis.store.load({params:o});
    }
}
// bitti

function adresiAyarla(value, p, record) {
    return '<a href="' + decodeURI(value) + '" target="_blank"><img src="../resimLer/download.gif" alt="Indir" title="Indir"/></a>';
}

function _decodeURI(value, p, record) {
    return value ;
}

function kaydet(){
    var jsonData = '[';
    var i = 0 ;
    var jsonKaynak = Ext.getCmp('editableGrid').getStore() ;
    for(i=0; i<jsonKaynak.getCount(); i++) 
    {
        record = jsonKaynak.getAt(i);
        if (record.dirty)
        	jsonData += Ext.util.JSON.encode(record.data) + ',' ;
    } 
    jsonData = jsonData.substring(0, jsonData.length-1) + ']'; 
    //a();
    //jsonData = Ext.getCmp('editableGrid').getStore().getModifiedRecords() ;                       
    //jsonData = Ext.util.JSON.encode(jsonData); 		
	Ext.Ajax.request({
	    url:'JsonDondur.aspx', 
	  	params:{pSayfa:'Programlar', pJsonData:jsonData, pIslem:'Guncelle'},
	  	success: function(result, request)
        {
	  		var res = new Object();
          	res = Ext.util.JSON.decode(result.responseText);
          	if (res.success == true)
          	{
          		gridYenile(Ext.getCmp("_bbar")) ;
          	}
          	else
          	{
          		Ext.MessageBox.alert('Sunucu Hatasi', res.hata);
          	}
        }
	});        
} 




