/*-------------------------------------------------------------------------
*
*                MainGrid.js
*
*   Programmer:  John Major
*                Pierce & Associates, P.C.
*
*   Date:        01/09/11
*
*   Description: Sales Bid Information External
*-------------------------------------------------------------------------
*   Special  Instructions:
*	  *None
*-------------------------------------------------------------------------
*       Modifications by Pierce & Associates, P.C.
*-------------------------------------------------------------------------
* Mod#  |   Date   | Programmer   |   Description
*-------------------------------------------------------------------------
* PA01  | 01/31/11 | John Major   | Add Google Maps for multiple properties
*       |          |              |  and stop using MapQuest for single
*       |          |              |  property view and use Google Maps
*       |          |              | 
*-------------------------------------------------------------------------
*
*
*-------------------------------------------------------------------------*/
Ext.ns('saleBidExt.grid');

saleBidExt.grid.MainGrid = Ext.extend(Ext.grid.GridPanel,{
	initComponent : function(){
	this.buildSelectionModel();  //PA01
		this.buildStore();
		this.saleBidDetailTpl = this.createSaleGridTemplate();
		this.saleBidExpander  = this.createsaleBidExpander();
		
 		Ext.apply(this, {
 			loadMask   : true,
 			title      : '<DIV ALIGN=CENTER><b>Sale Bid Information - Pierce & Associates, P.C.</b></div>',
 			stripeRows : true,
 			//iconCls    : 'date',
 			store      : this.saleBidstore,
 			plugins    : this.saleBidExpander,
			columns    : this.buildColumns(),
			//PA01sm         : this.selModel(),
			sm         : this.checkboxSM,  //PA01
			tbar       : this.buildToolbar(), //PA01
			bbar       : this.buildBottomToolbar()
		});
 
		saleBidExt.grid.MainGrid.superclass.initComponent.call(this);
		
		// after we make our call to the "initComponent" of our superclass....now is
		// when we will add any relevant listeners or register any custom events...
		//
		this.on({
			scope       : this,
			afterrender : this.onSaleAfterRender,
			cellclick   : this.onCellClick
		});
		
		this.saleBidstore.on({
			scope      : this,
			beforeload : this.onBeforeLoad
		});
		
		//PA01 Start
		this.checkboxSM.on({
			scope      : this,
			selectionchange : this.onSelChg
		});
		
		this.addEvents({
			geoMap 		: true,
			geoMapMult 	: true,
			accept 		: true
		});
		//PA01 End
	},
	//Great the Template for Property Information in the Expander
	createSaleGridTemplate: function() {
		return new Ext.XTemplate('<hr><table border="0" class=\'x-defendant-grid-detail\'\'>',
			'<tr class=\'x-defendant-grid-detail-row\'\'>',
		        '<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b>Sale Location:</b>',
		        '</td>',
		        '<td align=left>',
					'&nbsp;{SALE1}&nbsp;{SALE2}',
		        '</td>',
		        '<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b>Sale Time:</b>',
				'</td>',
				'<td align=left>',
					'&nbsp;{[this.getTime(values.SAOFC, values.SATME, values.SATMX)]}',
				'</td>',
		    '</tr>',
		    '<tr class=\'x-defendant-grid-detail-row\'\'>',
	        	'<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b></b>',
				'</td>',
				'<td align=left>',
					'&nbsp;',
				'</td>',
			'</tr>',
		    '<tr class=\'x-defendant-grid-detail-row\'\'>',
	        	'<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b>Plaintiff:</b>',
				'</td>',
				'<td align=left>',
					'&nbsp;{PLNTF}{PLNF2}',
				'</td>',
			'</tr>',
			'<tr class=\'x-defendant-grid-detail-row\'\'>',
				'<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b>Defendant:</b>',
				'</td>',
				'<td align=left>',
					'&nbsp;{[this.getDefendant(values.FNAME, values.LNAME)]}',
				'</td>',
			'</tr>',
			'<tr class=\'x-defendant-grid-detail-row\'\'>',
        		'<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b></b>',
				'</td>',
				'<td align=left>',
					'&nbsp;',
				'</td>',
			'</tr>',
			'<tr class=\'x-defendant-grid-detail-row\'\'>',
	        	'<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b>ANTICIPATED Opening</b>',
					'</td>',
			'</tr>',
		    '<tr class=\'x-defendant-grid-detail-row\'\'>',
		        '<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b>Bid by Plaintiff:</b>',
		        '</td>',
		        '<td align=left>',
					'&nbsp;{[this.getBidAmount(values.SALAM)]}',
		        '</td>',
		        '<td class=\'x-defendant-grid-detail-left-td\'\'>',
					'<b>Judgment Amount:</b>',
				'</td>',
				'<td align=left>',
					'&nbsp;{[this.getJudgmentAmount(values.JDJAM)]}',
				'</td>',
		    '</tr>',
	        '</table><hr>',{
				getBidAmount : function (amount) {
				if (amount > 0) {
					return Ext.util.Format.usMoney(amount);
				} else {
					return 'Unvailable';
				}
			}
			},{
				getJudgmentAmount : function (amount) {
				if (amount > 0) {
					return Ext.util.Format.usMoney(amount);
				} else {
					return 'Unvailable';
				}
			}
			},{
				getTime : function (salOfc, salTime, salTimeOvr) {
				var saleAmount = ' ';
				if (salOfc.trim()!= 'The Judicial Sales Corp.' && salOfc.trim()!= 'Intercounty Judicial Sale') {
					saleAmount = 'See Publication';
				} else {
					saleAmount = salTime;
				}
				if (salTimeOvr.trim() != '') {
					saleAmount = salTimeOvr;
				}
				return Ext.util.Format.uppercase(saleAmount);
			}
			},{
				getDefendant : function (firstName, lastName) {
				var defendantName = ' ';
				defendantName = firstName + ' ' + lastName + ' ET AL.';
				return defendantName;
			}
			});
	},
	
	createsaleBidExpander: function() {
		return new Ext.ux.grid.RowExpander({
            tpl: this.saleBidDetailTpl
        })
	},
	
	buildColumns : function(){
		return [
		this.saleBidExpander,
		this.checkboxSM,  //PA01
		{
			header    : '<b>PB</b>',
			dataIndex :	'CASNO',
			hidden    : true,
			width     : 70
		},{
			header    : '<b>Sale Date</b>',
			dataIndex :	'SCH17',
			hidden    : false,
			width     : 80,
			sortable  : true,
			renderer  : Pierce.util.cymdToMdy
		},{
			id        : 'MapIcon',
			header    : '<b>Map</b>',
			align     : 'center',
			renderer  : function() {
				return '<img src="/vvresources/icons/new_map.png" class="centeredImage" alt="Show Property Map Powered by Google Maps" title="Show Property Map Powered by Google Maps">'
			},
			width     : 50
		},{
			header    : '<b>Common Address</b>',
			dataIndex :	'ADR',
			hidden    : false,
			sortable  : true,
			width     : 290
		},{
			header    : '<b>Brief Property Description</b>',
			dataIndex :	'PRDSC',
			hidden    : false,
			sortable  : true,
			width     : 450
		},{
			header    : '<b>Court Case #</b>',
			dataIndex :	'COURT',
			hidden    : false,
			sortable  : true,
			width     : 100
		},{
			header    : '<b>PIN #</b>',
			dataIndex :	'TXID1',
			hidden    : false,
			width     : 120
		}];
	},
	
	//PA01 Start
	buildSelectionModel : function(){
		this.checkboxSM = new Ext.grid.CheckboxSelectionModel();
	},
	
	buildToolbar : function(){
		return [{
			text    : '<b>Map - Multiple Properties</b>',
			tooltip : 'Show Map with multiple Properties Powered by Google Maps, if you have properties in different cities please use the zoom button on the map window.',
			//iconCls : 'map_go',
			iconCls : 'new_map',
			itemId  : 'btn_geoMap',
			id		: 'btngeoMap',
			scope   : this,
			handler : this.onGeoMap
		},{
            xtype: 'tbseparator'
        },{
			text    : '<b>Clear Selected</b>',
			tooltip : 'Unselect any properties that are currently selected below',
			iconCls : 'delete',
			scope   : this,
			handler : this.onSelClear
		}];
	},
	
	onGeoMap : function(mapZoom){
		if (this.getSelectionModel().hasSelection()) {
		var propertysSelected = [];
		var centerProperty = [];

		//Google Maps requires a center property at all times so just pull the first property
		var propertySels = this.getSelectionModel().getSelections();
		centerProperty.push({geoCodeAddr: propertySels[0].data.GEOCD, marker: {title: propertySels[0].data.GEOCD + ' - ' + propertySels[0].data.PRDSC}});
		
		//Pull all checked/selected properties in this grid
		var allProps = [];
		var ix=0;
		this.getSelectionModel().each(function(rec) {
			propertysSelected.push({geoCodeAddr: rec.get('GEOCD'), marker: {title: rec.get('GEOCD') + ' - ' + rec.get('PRDSC')}, listeners: {click: function(e){Ext.Msg.show({
				title: 'Property Info',
				iconCls : 'new_map',
				msg: rec.get('ADR') + '<br><br><u>Description:</u> ' + rec.get('PRDSC') + '<br><br><u>Sale Date:</u> ' + Pierce.util.cymdToMdy(rec.get('SCH17')),
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.INFO
			});}}});
			allProps[ix]=propertysSelected[ix];
			ix++	
		});
	 	
	 	//Google Maps allows no more than 10 properties at a time if more is passed
	 	// google currently issues a error message
	 	if (ix > 10) {
	 		Ext.Msg.show({
				title: 'Multiple Property Map',
				msg: 'Please select no more than 10 properties at a time.',
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
		  return;
	 	}
		
	 	//If map zoom is not equal to 15 then its a multiple property view so set to 11
	 	if (mapZoom != 15) {
        	var mapZoom = 11;
        }
	 	
		//console.log(ix);
		if (ix > 1) {
			this.fireEvent('geoMapMult');
		} else {
			this.fireEvent('geoMap');
		}
		
		var geoWindow = new Ext.Window({
			layout: 'fit',
            title: '<b>Google Maps, Property(s) Map</b>',
            closeAction: 'hide',
            iconCls : 'new_map',
            modal: true,
            resizable: true,
            constrain: true,
            draggable: true,
            width:700,
            height:510,
			items: [{
				xtype: 'gmappanel',
				zoomLevel: mapZoom,
				gmapType: 'map',
				id: 'my_map',
				mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
				mapControls: [new GSmallMapControl(),'GMapTypeControl','NonExistantControl'],
				setCenter: centerProperty[0],
			    markers: allProps
			}]
		}).show();
	  } else {
		  Ext.Msg.show({
				title: 'Multiple Property Map',
				msg: 'Please Select at least one property to view.',
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
		  return;
	  }
	},
	
	onSelChg : function(){
		var numberSel=0;
		numberSel = this.getSelectionModel().getCount();
		if (numberSel > 1) {
	 		
	 	}
	},
	
	//Clear current selected properties in the grid
	onSelClear : function(){
		this.checkboxSM.clearSelections();
	}, //PA01 End
	
	buildStore : function(){
		this.saleBidstore = new Ext.data.JsonStore({
			remoteSort: true,
			sortInfo: {																										
				field: 'SCH17',																					
				direction: 'asc'																							
			},
			totalProperty: "totalCount",
			url      : '/apps21e/slb00001r.pgm',
			root     : 'saleBidGrid',
			fields   : ['FRMID','CASNO','SAOFC','SATME','SALE1','SALE2','SCH17','SALAM','PLNTF','PLNF2','FNAME', 'LNAME', 'ADR', 'PRDSC', 'COURT', 'JDJAM', 'TXID1', 'SATMX','GEOCD']
		});
	},
	
	buildBottomToolbar : function(){
		return new Ext.PagingToolbar({
			pageSize: 50,
			store: this.saleBidstore,
			displayInfo: true,
			displayMsg: 'Showing Property(s) {0} - {1} of {2}',
			emptyMsg: "No property(s) to display"
		});
	},
	
	selModel : function(){
			return new Ext.grid.RowSelectionModel({
                listeners: {
					scope: this,
                    rowselect: function(selModel, rowIndex){
                        var store = this.getStore();
                        store.currentRecord = store.getAt(rowIndex);
                        store.currentIndex = rowIndex;
					}
				}
			});
	},
	    	
	onBeforeLoad : function(){
		this.startPage = 0;
		this.saleBidstore.baseParams = {
			action : 'get_propertys',
			limit  : 50,
			start  : this.startPage,
			startDate  : this.startDate, 
			endDate    : this.endDate,
			commonAddress: this.commonAddress,
			bidAmount: this.bidAmount,
			bidMin: this.bidMin,
			bidMax: this.bidMax
		};
	},
	
	onCellClick : function(g,row,col){
		if (this.getColumnModel().getColumnId(col) == 'MapIcon'){
			var mapZoom = 15;  //PA01
			this.onGeoMap(mapZoom);  //PA01
		}
	},
	
	onSaleAfterRender: function() {
		var termsWindow = new Ext.Window({
			modal 		  : true,
			closable	  : false,
			width 		  : 700,
			height		  : 510,
			title		  : '<b>Important Information Concerning the Sale Bid Information Website</b>',
			autoScroll	  : true,
			buttonAlign: 'center',
			border        : false,
			constrain	  : true,
            draggable	  : true,
            iconCls 	  : 'exclamation',
			items		  : [{
				html : "<table style='font-size:12px;padding:6px;'><tr><th><b><u>Sale terms:</u> The real estate shall be sold at public auction to the highest bidder for cash; the deposit required at time of sale will be between ten percent (10%) and twenty five percent (25%) of the successful bid, and the officer conducting the sale shall announce the terms of the sale prior to the auction.&nbsp;&nbsp;The balance of the bid amount is required to be paid within twenty-four (24) hours of the Sale.&nbsp;&nbsp;All payments of the amount bid shall be in cash or certified funds payable to the Special Commissioner conducting the Sale." +
						"<br><br>The subject property is subject to general real estate taxes, special assessments or special taxes levied against said real estate and is offered for sale without any representation as to quality or quantity of title and without recourse to Plaintiff and in (as is) condition.&nbsp;&nbsp;The sale is further subject to all prior, recorded, and unreleased mortgages and liens of record.&nbsp;&nbsp;The sale is further subject to confirmation by the court.&nbsp;&nbsp;No refunds." +
						"<br><br>Prospective bidders are admonished to do a title search, property tax search, judgment and lien search and check the court file prior to the sale." +
						"<br><br>Upon payment in full of the amount bid, the purchaser shall receive a Certificate of Sale, which will entitle the purchaser to a Deed to the real estate after confirmation of the sale." +
						"<br><br>Pierce & Associates does not guarantee or warrant the accuracy of the following information." +
						"<br><br>The property will NOT be open for inspection and Plaintiff makes no representation as to the condition of the property.&nbsp;&nbsp;Prospective bidders are admonished to check the Court file to verify all information.&nbsp;&nbsp;There is no guarantee as to the condition of the title.&nbsp;&nbsp;This may not be a first mortgage." +
						"<br><br><u>NOTE:</u> Pursuant to the Fair Debt Collection Practices Act you are advised that Plaintiff's Attorney is deemed to be a debt collector attempting to collect a debt and any information obtained will be used for that purpose.&nbsp;&nbsp;No further information is available." +
						"<br><br>The information contained herein is subject to change without notice and the sale may be continued or cancelled.&nbsp;&nbsp;Pierce & Associates also advises that there is risk involved in the purchase of real estate at foreclosures sales, and if you are interested in bidding at a foreclosure sale, you should consult with your own attorney.&nbsp;&nbsp;Pierce & Associates will not give advice as to the matters concerning the bidding at a foreclosure sale, and will not be responsible or liable for any information contained herein or matters affecting the sale.&nbsp;&nbsp;Pierce & Associates represents the Plaintiff in these proceedings, and as such, cannot give legal advice to any other party that might be interested in bidding at the sale.<br><br><br>&nbsp;</b></th></tr></table>"
			}],
			buttons: [{
                text: 'Accept',
                iconCls: 'accept',
                scope: this,
                handler: function(){
                	termsWindow.close();
                	this.getStore().load();
                	this.fireEvent('accept');
            	}
            }]
		}).show();
	},
	
	onRebuildSaleBidSearch: function(searchParms) {
		this.startDate = searchParms.searchFmDate; 
		this.endDate = searchParms.searchEndDate;
		this.commonAddress = searchParms.searchAddress;
		this.bidAmount = searchParms.bidAmount;
		this.bidMin = searchParms.bidMin;
		this.bidMax = searchParms.bidMax;
		this.startPage = 0;
		this.getBottomToolbar().moveFirst();
	}
});
