Ext.app.App=function(cfg){
	Ext.apply(this,cfg);
	this.addEvents({
		'ready':true,
		'beforeunload':true,
		'resize':true
	});
	Ext.onReady(this.initApp,this);
};

Ext.extend(Ext.app.App,Ext.util.Observable,{
    isReady:false,
	initApp:function(){
		/*if (Ext.isIE)
			setTimeout("rbApp.init();",500);
		else*/
			this.init();
		Ext.EventManager.on(window,'beforeunload',this.onUnload,this);
		Ext.EventManager.on(window,'resize',this.onResize,this);
		this.fireEvent('ready',this);
		this.isReady=true;
	},
	onReady:function(fn,scope){
		if(!this.isReady){
			this.on('ready',fn,scope);
		}else{
			fn.call(scope,this);
		}
	},
	onUnload:function(e){
		if(this.fireEvent('beforeunload',this)===false){
			e.stopEvent();
		}
	}
});

rbApp=new Ext.app.App({
	location:false,
	have_arr:[],
	need_arr:[],
	need_table_height:70,
	start_with:1,
	init:function(){
		this.div_have_area_text=document.getElementById('rb_app_have_area_text');
		this.div_have_area_button=document.getElementById('rb_app_have_area_button');

		this.div_need_area_text=document.getElementById('rb_app_need_area_text');
		this.div_need_area_button=document.getElementById('rb_app_need_area_button');

		Ext.getBody().on('resize',this.resizeBody,this);
		//if(self.location.href.indexOf('wa_current.php')>0)this.location=true;
		this.location=true;
		///Ext.QuickTips.init();
		///Ext.form.Field.prototype.msgTarget='side';
		this.btn_win_have=new Ext.Button({
			///disabled:true,
			cls:'mybutton-have-class',
			scope:this,
			handler:this.btnWinHaveClick,
			text: '>'
		});
		this.btn_win_have.render(this.div_have_area_button);
		//var wrap=this.createWrap(RB_APP_RES_BUTTON_HAVE_NAME,this.btn_win_have);
		//this.ct_have.appendChild(wrap);
		
		var DIV=document.createElement('DIV');
		DIV.style.cssText='font-family:Arial;font-size:14;font-weight:bold;';
		DIV.innerHTML=RB_APP_RES_BUTTON_HAVE_NAME;

		this.div_have_area_text.appendChild(DIV);

		this.have_store=new Ext.data.SimpleStore({
			fields:[
				{name:'id'},
				{name:'text'}
			]
		});

		this.have_store.on('datachanged',this.haveChanged,this);

		this.havetext=new Ext.form.TextArea({
			renderTo:'rb_app_have_area_panel',
			width: 300,
			height: 20,
			value: '',
			cls: 'tovars_list',
			readOnly: true
		});

		this.btn_win_need=new Ext.Button({
			//disabled:true,
			cls:'mybutton-need-class',
			scope:this,
			handler:this.btnWinNeedClick,
			text: '>'
		});
		//var wrap=this.createWrap(RB_APP_RES_BUTTON_NEED_NAME,this.btn_win_need);
		//this.ct_need.appendChild(wrap);
		
		DIV=document.createElement('DIV');
		DIV.style.cssText='font-family:Arial;font-size:14;font-weight:bold;';
		DIV.innerHTML=RB_APP_RES_BUTTON_NEED_NAME;

		this.div_need_area_text.appendChild(DIV);
		this.btn_win_need.render(this.div_need_area_button)

		this.need_store=new Ext.data.SimpleStore({
			fields:[
				{name:'id'},
				{name:'text'}
			]
		});
		this.need_store.on('datachanged',this.needChanged,this);

		this.needtext=new Ext.form.TextArea({
			renderTo:'rb_app_need_area_panel',
			width: 300,
			height: 20,
			value: '',
			cls: 'tovars_list',
			readOnly: true
		});

		if(this.location){

			this.store_for_result_grid=new Ext.data.Store({
				url:'wa_search_lots.php',
				reader:new Ext.data.JsonReader({
					id:'LOTNUMBER',
					root:'row'
				},[
					{name:'LOTNUMBER'},
					{name:'RBOKP'},
					{name:'RBTOVARNAME'},
					{name:'RBEDIZM'},
					{name:'RBTOVARNUMBER'},
					{name:'RBTOVARCOST'},
					{name:'RBTOVAR2OKP'},
					{name:'RBTOVARSUM'},
					{name:'RBDELIVERY'},
					{name:'RBREGIONID'},
					{name:'RBDELIVERY'}
				])
			});

			var tooltipRenderer = function (data, metadata, record, rowIndex, columnIndex, store) {
				//metadata.attr = 'ext:qtip="' + data + '" style="height: 60px; white-space: normal; font-size: 11px;"';
				if (data=='')
					metadata.attr = 'style="height: 60px; white-space: normal; font-size: 11px;"';
				else
				{
					var datacopy = data;

					metadata.attr = 'onmouseover="Tip(\'' + escape(datacopy) + '\', BGCOLOR, \'#c4d7f5\', WIDTH, \'-240\', FONTCOLOR, \'#333333\', FONTFACE, \'Tahoma\');" onmouseout="UnTip();" style="height: 60px; white-space: normal; font-size: 11px;"';
				}
				return data;
			};

			var descRenderer = function (data, metadata, record, rowIndex, columnIndex, store) {
				
				metadata.attr = '';
				return '&nbsp;&nbsp;&nbsp;&nbsp;<img src="/images/list16.png" style="cursor:pointer" onclick="rbApp.lotDesc();"/>';
			};

			var div=document.getElementById('rb_app_grid_area');
			this.result_grid=new Ext.grid.GridPanel({
				store:this.store_for_result_grid,
				columns:[
					{header:'Description',width:60, sortable:true, renderer: descRenderer},
					{header:RB_APP_RES_GRID_COLUMN_NAME,width:200,dataIndex:'RBTOVARNAME',sortable:true, renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_EDIZM,width:50,dataIndex:'RBEDIZM',sortable:true, renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_NUM,width:50,dataIndex:'RBTOVARNUMBER',sortable:true,align:'right', renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_COST,width:70,dataIndex:'RBTOVARCOST',sortable:true,align:'right', renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_SUM,width:70,dataIndex:'RBTOVARSUM',sortable:true,align:'right', renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_SEARCH,width:100,dataIndex:'RBTOVAR2OKP',sortable:true, renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_REG,width:100,dataIndex:'RBREGIONID',sortable:true, renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_CODE,width:80,dataIndex:'RBOKP',sortable:true,align:'right', renderer: tooltipRenderer},
					{header:RB_APP_RES_GRID_COLUMN_COMMENT,width:200,dataIndex:'RBDELIVERY',sortable:true, renderer: tooltipRenderer}
				],
				renderTo:'rb_app_grid_area',
				width:div.offsetWidth,
				height:div.offsetHeight,
				viewConfig:{forceFit:true},
				//stripeRows:true,
				loadMask:true
            		});

			this.result_grid.on('render', function()
			{
				this.result_grid.tip = new Ext.ToolTip({
				view: this.result_grid.getView(),
				target: this.result_grid.getView().mainBody,
				delegate: '.x-grid3-row',
				trackMouse: true,
				renderTo: document.body,
				listeners: {
					beforeshow: function updateTipBody(tip) {
					tip.body.dom.innerHTML = "Over row " + tip.view.findRowIndex(tip.triggerElement);
					}
				}
				});
			});
			this.result_grid.getView().emptyText='Нет данных';
			//this.store_for_result_grid.on('loadexception',function(){if (!this.store_for_result_grid.getCount()) Ext.Msg.alert('', 'Лотов, удовлетворяющих критериям поиска, не найдено');},this);

            		this.loadFullResults();
		}



		this.win_have=new Ext.Window({
			title:RB_APP_RES_WINDOW_HAVE_TITLE,
			active_node:null,
			autoHeight:true,
			width:550,
                	layout:'fit',
                	closeAction:'hide',
                	plain: true,
			pageX:380,
			pageY:230,
			animCollapse:false,
			constrain:true,
			shadow:'frame',
			//shadowOffset:6,
			//onEsc:Ext.EmptyFn,
			//tools:[],
			layout:'fit',
			items:this.tree_have=new Ext.tree.TreePanel({
				rootVisible:false,
				border:false,
				height: 400,
				width: 500,
				autoScroll: true,
				animate: true,
				enableDD: false,
				containerScroll: true,
				border: false,
				
				loader:new Ext.tree.TreeLoader({
					url:'wa_tree-data_en.php',
					baseAttrs:{
						//uiProvider:'col',
						iconCls:'task',
						checked:false
					}
				}),
				
				root: {
					nodeType: 'async',
					text: 'Positions',
					draggable: false,
					id: 'source'
				}
			}),
			buttons:[{
				text:RB_APP_RES_WINDOW_BUTTON_NAME,
				handler:this.clickHaveButton,
				scope:this
			}]
		});
		this.win_have.on('beforeclose',this.winHaveClose,this);
		this.win_have.on('show',this.winHaveShow,this);
		this.tree_have.on('click',this.treeHaveClick,this);
		this.tree_have.on('dblclick',this.treeHaveDblclick,this);
		this.tree_have.on('checkchange',this.treeHaveCheck,this);

		var check_str=[];
		//for(var i=0;i<this.need_arr.length;i++)check_str[i]=this.need_arr[i][1];
		for(var i=0;i<this.need_arr.length;i++)check_str[i]=this.need_arr[i][0];
		check_str=check_str.join(';');


		this.win_need=new Ext.Window({
			title:RB_APP_RES_WINDOW_NEED_TITLE,
			active_node:null,
			autoHeight:true,
			width:550,
                	layout:'fit',
                	closeAction:'hide',
                	plain: true,
			pageX:700,
			pageY:230,
			animCollapse:false,
			constrain:true,
			shadow:'frame',
			//shadowOffset:6,
			//onEsc:Ext.EmptyFn,
			//tools:[],
			layout:'fit',
			items:this.tree_need=new Ext.tree.TreePanel({
				rootVisible:false,
				border:false,
				height: 400,
				width: 500,
				autoScroll: true,
				animate: true,
				enableDD: false,
				containerScroll: true,
				border: false,
				
				loader:new Ext.tree.TreeLoader({
					url:'wa_tree-data_en.php',
					baseAttrs:{
						iconCls:'task',
						checked:false
					}
				}),
				
				root: {
					nodeType: 'async',
					text: 'Positions',
					draggable: false,
					id: 'source'
				}
			}),
			buttons:[{
				text:RB_APP_RES_WINDOW_BUTTON_NAME,
				handler:this.clickNeedButton,
				scope:this
			}]

		});
		this.win_need.on('beforeclose',this.winNeedClose,this);
		this.win_need.on('show',this.winNeedShow,this);
		this.tree_need.on('click',this.treeNeedClick,this);
		this.tree_need.on('dblclick',this.treeNeedDblclick,this);
		this.tree_need.on('checkchange',this.treeNeedCheck,this);

		this.btn_prev=new Ext.Button({
			scope:this,
			iconCls: 'left_arrow_btn',
			renderTo: 'div_listing_prev',
			scale: 'medium',
			disabled: true,
			handler: function(){
				this.start_with -= 35;
				if (this.start_with == 1) 
					this.btn_prev.disable();
				this.loadFullResults();
			}
		});
		this.btn_next=new Ext.Button({
			scope:this,
			iconCls: 'right_arrow_btn',
			renderTo: 'div_listing_next',
			scale: 'medium',
			handler: function(){
				this.start_with += 35;
				if (this.start_with == 36)
					this.btn_prev.enable();
				this.loadFullResults();
			}
		});
	},
	////// Handlers
	btnWinHaveClick:function(){
		//this.win_need.setVisible(false);
		this.win_have.show();
	},
	btnWinNeedClick:function(){
		this.win_have.setVisible(false);
		this.win_need.show();
	},
	btnShowClick:function(){
		this.win_need.setVisible(false);
		this.win_have.setVisible(false);
		if(this.location){
			this.loadFullResults();
		}else{
			var form=new hiddenForm('wa_current.php');
			for(var i=0,len=this.need_arr.length;i<len;i++){
				form.addField('needname[]',this.need_arr[i][0]);
				form.addField('need[]',this.need_arr[i][1]);
			}
			form.addField('havename[]',this.have_arr[0][0]);
			form.addField('have[]',this.have_arr[0][1]);
			form.submit();
		}
	},
	/// win_have handlers
	winHaveClose:function(){
		this.win_have.setVisible(false);
		return false;
	},
	winHaveShow:function(){
		this.tree_need.syncSize();
	},
	clickHaveButton:function(){
		var an=this.win_have.active_node;
		if(an)an.getUI().toggleCheck(true);
		this.loadFullResults();
		this.winHaveClose();
	},
	/// win_need handlers
	winNeedClose:function(){
		this.win_need.setVisible(false);
		return false;
	},
	winNeedShow:function(){
		this.tree_need.syncSize();
	},
	clickNeedButton:function(){
		var an=this.win_need.active_node;
		if(an)an.getUI().toggleCheck(true);
		this.loadFullResults();
		this.winNeedClose();
	},
	/// tree_have handlers
	treeHaveClick:function(node,e){
		if(node)node.getUI().toggleCheck();
	},
	treeHaveDblclick:function(node,e){
	},
	treeHaveCheck:function(node,ch){
		///node.fireEvent('click',node);

		node.cascade(function(n) {
			if (n.id!=node.id)
			{
				if (node.getUI().isChecked())
					n.getUI().toggleCheck(true);
				else
					n.getUI().toggleCheck(false);
			}
		}, node);

		var obj=[node.attributes.id, node.attributes.text];
		if(ch){
			if(this.have_arr.indexOfCode(obj)==-1){
				this.have_arr[this.have_arr.length]=obj;
				this.have_store.loadData(this.have_arr);
			}
		}else{
			this.have_arr.removeCode(obj);
			this.have_store.loadData(this.have_arr);
		}

		var havelist = '';
		for(var i=0;i<this.have_arr.length;i++) havelist += this.have_arr[i][1] + '; ';
		this.havetext.setValue(havelist);
	},
	/// end tree_have handlers

	/// tree_need handlers
	treeNeedClick:function(node,e){
		if(node)node.getUI().toggleCheck();
	},
	treeNeedCheck:function(node,ch){
		///node.fireEvent('click',node);

		node.cascade(function(n) {
			if (n.id!=node.id)
			{
				if (node.getUI().isChecked())
					n.getUI().toggleCheck(true);
				else
					n.getUI().toggleCheck(false);
			}
		}, node);

		var obj=[node.attributes.id, node.attributes.text];
		if(ch){
			if(this.need_arr.indexOfCode(obj)==-1){
				this.need_arr[this.need_arr.length]=obj;
				this.need_store.loadData(this.need_arr);
			}
		}else{
			this.need_arr.removeCode(obj);
			this.need_store.loadData(this.need_arr);
		}
		var needlist = '';
		for(var i=0;i<this.need_arr.length;i++) needlist += this.need_arr[i][1] + '; ';
		this.needtext.setValue(needlist);
	},
	treeNeedDblclick:function(node,e){
	},
	/// end tree_need handlers
/*	onResize:function(){
		var bw=Math.round((Ext.lib.Dom.getViewWidth()/4)-34);
		///alert(bw);
		this.haveTable.setWidth(bw);
		this.needTable.setSize(bw,this.need_table_height);
	},*/
	haveChanged:function(){
		//this.haveTable.expand(true);
		//this.loadCountResults();
	},
	needChanged:function(){
		//this.needTable.expand(true);

		/*if(store.getCount()>0){
			this.needTable.expand(true);
			this.loadCountResults();
		}else{
			///this.needTable.collapse(true);
			this.show_button.reset();
		}*/
	},
	loadFullResults:function(){
		var have=[];
		var need=[];
		var region_id, good, cost;
		
		good = document.getElementById('good').value;

		region_id = document.getElementById('selectregion').options[document.getElementById('selectregion').selectedIndex].value;
		country_id = document.getElementById('country').options[document.getElementById('country').selectedIndex].value;
	
		cost = document.getElementById('cost').value;

		if (this.have_arr.length>0){
			for(var i=0;i<this.have_arr.length;i++)have[i]=this.have_arr[i][0];
			have=have.join(';');
		}

		if (this.need_arr.length>0){
			for(var i=0;i<this.need_arr.length;i++)need[i]=this.need_arr[i][0];
			need=need.join(';');
		}
		this.store_for_result_grid.removeAll();
		this.result_grid.getStore().load({
			params:{
				action:'full',
				need:need,
				have:have,
				country:country_id,
				RegionID:region_id,
				DescrWords:good,
				Cost:cost,
				StartWith:this.start_with
			}
		});
		
		if (typeof(additionalActions) == "function")
			additionalActions();
	},
	clearSearch:function(){
		
		this.have_store.removeAll();
		this.need_store.removeAll();
		this.need_arr=[];
		this.have_arr=[];
		this.havetext.setValue('');
		this.needtext.setValue('');

		document.getElementById('good').value = '';
		region_id = document.getElementById('selectregion').options[0].selected = true;
		document.getElementById('cost').value = '';
		
		this.loadFullResults();
	},
	lotDesc:function(){
		lot_record = this.result_grid.getSelectionModel().getSelected();
		lot_id = lot_record.get('LOTNUMBER');

		window.open('hotlots/wa_lotdesc_no_design.php?lot_id='+lot_id,'_blank','width=800, height=800, scrollbars=yes, menubar=yes');
	},
	loadCountResults:function(){
		if(this.have_arr.length>0&&this.need_arr.length>0){
			var need=[];
			//var have=this.have_arr[0][1];
			var have=this.have_arr[0][0];
			//for(var i=0;i<this.need_arr.length;i++)need[i]=this.need_arr[i][1];
			for(var i=0;i<this.need_arr.length;i++)need[i]=this.need_arr[i][0];
			need=need.join(';');
			this.show_button.load({need:need,have:have});
		}
	},

	createWrap:function(text,button){
		var TABLE=document.createElement('TABLE');
		TABLE.width='100%';
		var TBODY=document.createElement('TBODY');
		TABLE.appendChild(TBODY);
		var TR=document.createElement('TR');
		TBODY.appendChild(TR);
		var TD=document.createElement('TD');
		TD.style.cssText='font-family:tahoma;font-size:14;font-weight:bold;';
		TR.appendChild(TD);
		TD.innerHTML=text;
		var TD=document.createElement('TD');
		TD.align='right';
		TR.appendChild(TD);
		button.render(TD);
		return TABLE;
	}

});

Ext.tree.ColumnTree=Ext.extend(Ext.tree.TreePanel,{
    lines:true,
    borderWidth:Ext.isBorderBox?0:2,//the combined left/right border for each cell
    cls:'x-column-tree',

    onRender:function(){
        Ext.tree.ColumnTree.superclass.onRender.apply(this, arguments);
        this.headers=this.body.createChild({cls:'x-tree-headers'},this.innerCt.dom);
        var cols=this.columns;
        var c;
        var totalWidth=0;
        for(var i=0,len=cols.length;i<len;i++){
             c=cols[i];
             totalWidth+=c.width;
             this.headers.createChild({
                 cls:'x-tree-hd '+(c.cls?c.cls+'-hd':''),
                 cn:{
                     cls:'x-tree-hd-text',
                     html:c.header
                 },
                 style:'width:'+(c.width-this.borderWidth)+'px;'
             });
        }
        this.headers.createChild({cls:'x-clear'});
        // prevent floats from wrapping when clipped
        this.headers.setWidth(totalWidth);
        this.innerCt.setWidth(totalWidth);
    }
});

Ext.tree.ColumnNodeUIE=Ext.extend(Ext.tree.TreeNodeUI,{
    focus: Ext.emptyFn,//prevent odd scrolling behavior
    renderElements:function(n,a,targetNode,bulkRender){
        this.indentMarkup=n.parentNode?n.parentNode.ui.getChildIndent():'';

        var t=n.getOwnerTree();
        var cols=t.columns;
        var bw=t.borderWidth;
        var c=cols[0];
        var cb=typeof a.checked=='boolean';

        var buf=[
             '<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf ', a.cls,'">',
                '<div class="x-tree-col" style="width:',c.width-bw,'px;">',
                    '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
                    '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow">',
                    '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on">',
                    cb?('<input class="x-tree-node-cb" type="checkbox" '+(a.checked?'checked="checked" />':'/>')):'',
                    '<a hidefocus="on" class="x-tree-node-anchor" href="',a.href ? a.href : "#",'" tabIndex="1" ',
                    a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '>',
                    '<span unselectable="on">', n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),"</span></a>",
                "</div>"];
         for(var i=1,len=cols.length;i<len;i++){
             c = cols[i];
             buf.push('<div class="x-tree-col ',(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
                        '<div class="x-tree-col-text">',(c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),"</div>",
                      "</div>");
         }
         buf.push(
            '<div class="x-clear"></div></div>',
            '<ul class="x-tree-node-ct" style="display:none;"></ul>',
            "</li>");
        if(bulkRender!==true&&n.nextSibling&&n.nextSibling.ui.getEl()){
            this.wrap=Ext.DomHelper.insertHtml("beforeBegin",n.nextSibling.ui.getEl(), buf.join(""));
        }else{
            this.wrap=Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
        }
        this.elNode=this.wrap.childNodes[0];
        this.ctNode=this.wrap.childNodes[1];
        var cs=this.elNode.firstChild.childNodes;
        this.indentNode=cs[0];
        this.ecNode=cs[1];
        this.iconNode=cs[2];
        var index = 3;
        if(cb){
            this.checkbox = cs[3];
			// fix for IE6
			this.checkbox.defaultChecked = this.checkbox.checked;
            index++;
        }
        this.anchor = cs[index];
        this.textNode = cs[index].firstChild;
    },
    onDblClick:function(e){
        e.preventDefault();
        if(this.disabled)return;
        if(!this.animating&&this.node.isExpandable())this.node.toggle();
        this.fireEvent('dblclick',this.node,e);
    }
});

Ext.applyIf(Array.prototype,{
	indexOfCode:function(o){
		for(var i=0,len=this.length;i<len;i++){if(this[i][1]==o[1])return i;}
		return -1;
	},
	removeCode:function(o){
		var index=this.indexOfCode(o);
		if(index!=-1){this.splice(index,1);}
		return this;
    }
});


hiddenForm=function(url){
	var form=this.form=document.createElement('FORM');
	form.action=url;
	form.method='POST';
	document.body.appendChild(form);
}
hiddenForm.prototype.addField=function(name,val){
	var field=document.createElement('INPUT');
	field.setAttribute('type','hidden');
	field.setAttribute('name',name);
	field.setAttribute('value',val);
	this.form.appendChild(field);
}
hiddenForm.prototype.submit=function(){this.form.submit();}
