
//GLOBAL Vars
var form_ct;
var tb_subscribe;
var InfoDialog;

Ext.QuickTips.init();

function togglect()
{
	el = form_ct;
	if (el.isDisplayed())
	{
		Ext.get('pur-grid').setDisplayed(true);
		document.getElementById('orm_link').style.display = 'block';
		el.setDisplayed(false);
	}
	else
	{
		el.setDisplayed(true);
		Ext.get('pur-grid').setDisplayed(false);
		document.getElementById('orm_link').style.display = 'none';
	}
};

regions = new Hashtable();
codes = new Hashtable();

function createSubscription(){
	SubscriptionDialog.showDialog(); 
};

var showHelp; 

function showHelpBox() {
        showHelp.alignTo('show-help-link', 'tl', [3,3]);
        showHelp.show()
}	



Ext.onReady(function(){
	SubscriptionDialog.init();	
	Ext.enotdata.data_sources.load({params:{start:0, limit:50}});

    showHelp = Ext.get('show-help');
    var closeBtn = Ext.get('show-help-close');
    closeBtn.on('click', showHelp.hide, showHelp, true);
	
    

var InfoDialog = function(){

    var dialog, showBtn;
    
    var toggleTheme = function(){
        Ext.get(document.body, true).toggleClass('xtheme-gray');
    };
    // return a public interface
    return {
        init : function(){
             
        },
        
        showDialog : function(otype, o_id){
            if(!dialog){ 
                dialog = new Ext.LayoutDialog("info-dlg", { 
                        //modal:true,
                        width:800,
                        height:500,
                        shadow:true,
                        minWidth:300,
                        minHeight:300,
                        proxyDrag: true,
	                    center: {
	                        autoScroll:true,
	                        tabPosition: 'top',
	                        closeOnTab: true,
	                        alwaysShowTabs: true
	                    }
                });
                dialog.addKeyListener(27, dialog.hide, dialog);
                dialog.addButton('Закрыть', dialog.hide, dialog);
                
                var layout = dialog.getLayout();
                layout.beginUpdate();
		panel =  new Ext.ContentPanel('center', {title: 'Информация о закупке'});
		if (otype == 1)
		{
		    panel.setUrl("/purchase/" + o_id + "/short/");	
		}
		else
		{
		    panel.setUrl('/organization/' +o_id + "/short/");	
		}
	        layout.add('center', panel);
	        layout.endUpdate();
            }
	    else
	    {
		if (otype == 1)
		{
		    var mgr = panel.setUrl("/purchase/" + o_id + "/short/");	
		    mgr.loadScripts = true;		    
		    panel.load('/purchase/' +o_id + "/short/");	
		}
		else
		{
		    var mgr = panel.setUrl('/organization/' +o_id + "/short/");	
		    mgr.loadScripts = true;		    
		    panel.load('/organization/' +o_id + "/short/");	
		}
	    }
	    dialog.show('submit-btn');
        }
    };
}();

Ext.EventManager.onDocumentReady(InfoDialog.init, InfoDialog, true);

function showOrganization(o_id)
{
	InfoDialog.showDialog(2, o_id);
};

function showPurchase(o_id)
{
	InfoDialog.showDialog(1, o_id);
};

 
    var ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/purchase/data.json'			
        }),
        reader: new Ext.data.JsonReader({
            root: 'purchases',
            totalProperty: 'totalCount',
            id: 'purchase_id'
        }, [
            {name: 'title', mapping: 'title'},
            {name: 'purchase_id', mapping: 'purchase_id'},
            {name: 'price', mapping: 'price'},
			{name: 'customer_id', mapping: 'customer_id'},
			{name: 'ptype_abbr', mapping: 'ptype_abbr'},			
			{name: 'bidSubmissionEndDate', mapping: 'bidSubmissionEndDate'},			
			{name: 'date_modified', mapping: 'date_modified'},			
            {name: 'customer_name', mapping: 'customer_name'}
        ]),
		baseParams : {'types':'0'}, 
        remoteSort: true
    });

	
	// =================== Таблица закупок =================	
    function renderTitle(value, p, record){
        return String.format('<a href="#"><b>{1}</b></a>', record.data["purchase_id"], value);
    }

    function renderOrg(value, p, record){
		if (record.data["customer_id"] != 0) {		
        	return String.format('<a href="#"><b>{1}</b></a>', record.data["customer_id"], value);
		}			
		else
		{
        	return String.format('<b>{0}</b>', value);		
		}
    }

    var cm = new Ext.grid.ColumnModel([
		{
           id: 'ptype',
           header: "Способ закупки",
           dataIndex: 'ptype_abbr',
           width: 50,
           css: 'white-space:normal;'
        },	
	{
           id: 'title',
           header: "Наименование",
           dataIndex: 'title',
           width: 300,
           renderer: renderTitle,
           css: 'white-space:normal;'
        },{
           header: "Заказчик",
           dataIndex: 'customer_name',
           width: 200,
           hidden: false,
           renderer: renderOrg,
	 css: 'white-space:normal;'
        },
		{
           id: 'price',
           header: "Цена",
           dataIndex: 'price',
           width: 60,
           css: 'white-space:normal;'
        },
		{
           id: 'submissionEnd',
           header: "Дата окончания приёма заявок",
           dataIndex: 'bidSubmissionEndDate',
           width: 70,
           css: 'white-space:normal;'
        },
		{
           id: 'date_modified',
           header: "Дата изменения",
           dataIndex: 'date_modified',
           width: 70,
           css: 'white-space:normal;'
        }	
			
		]);

    

    var grid = new Ext.grid.Grid('pur-grid', {
        ds: ds,
        cm: cm,
		autoExpandColumn :'title',
		autoExpandMax : 1000,		
        selModel: new Ext.grid.RowSelectionModel({singleSelect:true}),
		loadingText: "Идёт загрузка данных...",
        enableColLock:false,
        loadMask: true
    });
    grid.on('cellclick', function(grd, rowIndex, columnIndex, evt)
    {
	var r = ds.getAt(rowIndex);
        var fieldName = cm.getDataIndex(columnIndex);
	if (fieldName == 'customer_name')
	{
	    var o_id = r.get('customer_id');    
	    showOrganization(o_id);
	}
	else if (fieldName == 'title')
	{
	    var o_id = r.get('purchase_id');    
	    showPurchase(o_id);
	}	
    });
    
    var rz = new Ext.Resizable('pur-grid', {
        wrap:true,
        minHeight:100,
        pinned:true,
        handles: 'se'
    });
    rz.on('resize', grid.autoSize, grid);

    // render it
    grid.render();
	//ds.load({params:{start:0, limit:25}});
	
	// Initialize form-ct
	form_ct = Ext.get('form-ct');
	form_ct.setVisibilityMode(Ext.Element.DISPLAY);
		
    var gridFoot = grid.getView().getFooterPanel(true);

    // add a paging toolbar to the grid's footer
    var paging = new Ext.PagingToolbar(gridFoot, ds, {
        pageSize: 25,
        displayInfo: true,
        displayMsg: 'Закупки {0} - {1} из {2}',
        emptyMsg: ""
    });
	
	

    /*
     * ================  Поиск по закупкам  =======================
     */
    var form = new Ext.form.Form({
        labelAlign: 'left',
        labelWidth: '125',
	width: 700,
		method: 'GET',
		url: '/purchase/'
    });
	var form_p = form;
	form_subfields = form;

    form.column({width:400, labelWidth:250}); 
    form.fieldset(
        {legend:'Параметры поиска',labelAlign: 'top'},
        new Ext.form.ComboBox({
            fieldLabel: 'Статус закупки',
            hiddenName:'statuses',
            store: new Ext.data.SimpleStore({
                fields: ['code', 'name'],
                data : Ext.enotdata.pur_statuses
            }),
            displayField:'name',
			valueField:'code',
			value: 0,
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText:'Выберите статус закупки...',
            selectOnFocus:true,
            width:290
        }),		
        new Ext.form.TextField({
            fieldLabel: 'Ключевые слова (<a id="show-help-link" onclick="javascript:showHelpBox()"> подсказка по поиску </a>)',
            name: 'keywords',
            allowBlank:true,
			width:290,				
            value: ''
        }),
        new Ext.form.ComboBox({
            fieldLabel: 'Способ закупки',
            hiddenName:'types',
            store: new Ext.data.SimpleStore({
                fields: ['code', 'name'],
                data : Ext.enotdata.ptypes
            }),
            displayField:'name',
			valueField:'code',
			value: '0,1,2,3,4,5',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText:'Выберите способ закупки...',
            selectOnFocus:true,
            width:290
        }),
        new Ext.form.TriggerField({
            fieldLabel: 'Регионы',
            name: 'regions',
			onTriggerClick: function(form, action){
				RegionsDialog.showDialog(form_p); 
    			},						
			readOnly: true,			
			width:290,				
            value: ''
        }),

        new Ext.form.TriggerField({
            fieldLabel: 'Коды товаров',
            name: 'codes',
			onTriggerClick: function(form, action){
				ClassifierDialog.showDialog(form_p); 
    			},			
			readOnly: true,
			width:290,
            value: ''
        }),
	
        new Ext.form.ComboBox({
            fieldLabel: 'Источник информации',
            hiddenName:'sources',
            store:  Ext.enotdata.data_sources,
            displayField:'name',
			valueField:'code',
			value: '',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText:'Выберите источник.',
            selectOnFocus:true,
            width:290
        })
		
    );

    form.fieldset(
        {legend:'Цена (в тысячах рублей)', hideLabels:false, labelWidth: 20},
        new Ext.form.NumberField({
            fieldLabel: 'От',

            name: 'min_price',
            width:190,
            allowBlank:true
        }),
        new Ext.form.NumberField({
            fieldLabel: 'До',
		
            name: 'max_price',
            width:190,
            allowBlank:true
        })
    );
    form.end();
    form.column({width:250, labelWidth:155, style: 'margin-left:10px'}); 

/*    form.end(); 

    
    form.column(
        {width:250, style:'margin-left:10px', clear:true}
    );
*/


    form.fieldset(
        {legend:'Дата публикации', hideLabels:false, labelWidth: 20},
        new Ext.form.DateField({
            fieldLabel: 'От',
			format: 'd.m.Y',
            name: 'pub_start',
            width:190,
            allowBlank:true
        }),
        new Ext.form.DateField({
            fieldLabel: 'До',
			format: 'd.m.Y',
            name: 'pub_end',
            width:190,
            allowBlank:true
        })
    );
    form.fieldset(
        {legend:'Дата завершения приёма заявок', hideLabels:false, labelWidth: 20},
        new Ext.form.DateField({
            fieldLabel: 'От',
			format: 'd.m.Y',
            name: 'unseal_start',
            width:190,
            allowBlank:true
        }),
        new Ext.form.DateField({
            fieldLabel: 'До',
			format: 'd.m.Y',
            name: 'unseal_end',
            width:190,
            allowBlank:true
        })
    );
    form.fieldset(
        {legend:'Дата последнего изменения', hideLabels:false, labelWidth: 20},
        new Ext.form.DateField({
            fieldLabel: 'От',
			format: 'd.m.Y',
            name: 'modified_start',
            width:190,
            allowBlank:true
        }),
        new Ext.form.DateField({
            fieldLabel: 'До',
			format: 'd.m.Y',
            name: 'modified_end	',
            width:190,
            allowBlank:true
        })
    );
    form.fieldset(
        {legend:'Дополнительные параметры', hideLabels:false, labelWidth: 150, labelAlign:'top'},
        new Ext.form.ComboBox({
            fieldLabel: 'Торги для малого предпринимательства',
            hiddenName:'smbpurchase',
			labelWidth: 150,
            store: new Ext.data.SimpleStore({
                fields: ['code', 'name'],
                data : Ext.enotdata.smb_types
            }),
            displayField:'name',
			valueField:'code',
			value: '-1',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText:'Выберите значение...',
            selectOnFocus:true,
            width:150
        })
	);	
    form.end(); // close the column

    
    form.applyIfToFields({
        width:230
    });


  function purSearchSubmit(){
	Ext.get('pur-grid').setDisplayed(true);
	document.getElementById('form-ct').style.display = 'none';
	document.getElementById('orm_link').style.display = 'block';
  	ds.baseParams = form.getValues();
	ds.load({params:{start:0, limit:25}});
  };
  

    form.addButton(
	{text: 'Найти',
	 handler: purSearchSubmit});

    form.render('form-ct');

		
	//form.render(gridHead);
	
	
	var rtree;	
	rtree = new Ext.tree.TreePanel('tree-div', {
		animate:true,
		loader: new Ext.tree.CustomUITreeLoader({
			dataUrl:'/regions/tree.json',
			baseAttr: {
				uiProvider: Ext.tree.CheckboxNodeUI
			}
		}),
		enableDD:true,
		animate: true,
		containerScroll: true,
		rootUIProvider: Ext.tree.CheckboxNodeUI,
		selModel:new Ext.tree.CheckNodeMultiSelectionModel(),
		rootVisible:false
	});
	
	rtree.on('check', function(node, state, bulk) {

		
		if (state)
		{
			regions.put(node.id, node.text);
		}			
		else
		{
			regions.remove(node.id);				
		}
		RegionsDialog.getDialogForm().findField('regions').setValue(regions.keys.join(','));
	}, rtree);

	// set the root node
	root = new Ext.tree.AsyncTreeNode({
		text: 'root',
		draggable:false,
		id:'0',
		uiProvider: Ext.tree.CheckboxNodeUI
	});
	rtree.setRootNode(root);

	// render the tree



var RegionsDialog = function(){
    // define some private variables
    var dialog, showBtn;
	var dialog_form;
    
    // return a public interface
    return {
        init : function(theform){
         showBtn = Ext.get('show-dialog-btn');
             // attach to click event
             showBtn.on('click', this.showDialog, this);
        },
		
		getDialogForm : function()
		{
			return dialog_form;
		},
       
        showDialog : function(theform){
			dialog_form = theform;
                if(!dialog){ // lazy initialize the dialog and only create it once
                dialog = new Ext.BasicDialog("regions-dlg", { 
                        autoTabs:false,
                        width:600,
                        height:350,
                        shadow:true,
                        minWidth:300,
                        minHeight:250,
                        proxyDrag: true
                });
                dialog.addKeyListener(27, dialog.hide, dialog);
                dialog.addButton('Закрыть', dialog.hide, dialog);
            }
			
            dialog.show(showBtn.dom);
			rtree.render();
        }
    };
}();		


	var	ctree = new Ext.tree.TreePanel('ctree-div', {
		animate:true,
		loader: new Ext.tree.CustomUITreeLoader({
			dataUrl:'/classifier/tree.json',
			baseAttr: {
				uiProvider: Ext.tree.CheckboxNodeUI
			}
		}),
		enableDD:true,
		animate: true,
		containerScroll: true,
		rootUIProvider: Ext.tree.CheckboxNodeUI,
		selModel:new Ext.tree.CheckNodeMultiSelectionModel(),
		rootVisible:false
	});
	
	ctree.on('check', function(node, state, bulk) {

		
		if (state)
		{
			codes.put(node.id, node.text);
		}			
		else
		{
			codes.remove(node.id);				
		}
		ClassifierDialog.getDialogForm().findField('codes').setValue(codes.keys.join(','));
	}, ctree);

	// set the root node
	root = new Ext.tree.AsyncTreeNode({
		text: 'root',
		draggable:false,
		id:'NULL',
		uiProvider: Ext.tree.CheckboxNodeUI
	});
	ctree.setRootNode(root);
	// render the tree



var ClassifierDialog = function(){
    // define some private variables
    var dialog, showBtn;
	var dialog_form;
    
    // return a public interface
    return {
        init : function(){
             showBtn = Ext.get('show-dialog-btn2');
             // attach to click event
             showBtn.on('click', this.showDialog, this);
        },
		
		getDialogForm : function()
		{
			return dialog_form;
		},
       
        showDialog : function(theform){
			dialog_form = theform;

            if(!dialog){ // lazy initialize the dialog and only create it once
                dialog = new Ext.BasicDialog("classifier-dlg", { 
                        autoTabs:false,
                        width:600,
                        height:350,
                        shadow:true,
                        minWidth:300,
                        minHeight:250,
                        proxyDrag: true
                });
                dialog.addKeyListener(27, dialog.hide, dialog);
                dialog.addButton('Закрыть', dialog.hide, dialog);
            }
			ctree.render();
            dialog.show(showBtn.dom);

        }
    };
}();		

	ClassifierDialog.init();	
	RegionsDialog.init();	
});
