var store;

Ext.onReady(function(){
    store = new Ext.data.JsonStore({
        root: 'properties',
        totalProperty: 'totalCount',
        idProperty: 'id',
        remoteSort: true,
       fields: [
            'title', 'price', 'publicremarks', 'id','bedrooms','bathrooms','city','address','marker','squareFeet','yearBuilt','acres','subdivision','marker'
        ],
        proxy: new Ext.data.HttpProxy({
            url: 'ajax_grid.php'
        })
    });
    store.setDefaultSort('price', 'desc');
     store.on('load',dataStoreLoaded);
	
     theGridConf = {
	
			region: 'south', 
			id: 'grid',
			split: true,
			height: 200,
			layout: 'fit',
			//minSize: 75,      
			//maxSize: 300,
			xtype: 'grid',
			 store: store,
        trackMouseOver:false,
        disableSelection:false,
        loadMask: true,
	//columnLines: true,
	selModel: new Ext.grid.RowSelectionModel({listeners:{rowselect: gridRowSelect}}) ,
        columns:[{
            id: 'subdivision', 
            header: "Subdivision",
            dataIndex: 'subdivision',
	    renderer: renderSubdivision,
           // width: 180,
            sortable: false
        },
	{
		id: 'bedrooms', 
		header: "Beds",
		dataIndex: 'bedrooms',
		width: 50
	},
	{
		id: 'bathrooms', 
		header: "Baths",
		dataIndex: 'bathrooms',
		width: 50
	},
	{
		id: 'sqft', 
		header: "Sqft.",
		dataIndex: 'squareFeet',
		width: 50
	},
	{
		id: 'lotsize', 
		header: "Acres",
		dataIndex: 'acres',
		width: 50
	},
	{
		id: 'mls', 
		header: "MLS #",
		dataIndex: 'id',
		width: 70,
		renderer: renderMLSNumber
	},
	{
            id: 'price',
            header: "Price",
            dataIndex: 'price',
            width: 65,
            renderer: Ext.util.Format.usMoney,
            sortable: true
        }],

        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            showPreview:false,
            getRowClass : function(record, rowIndex, p, store){
                if(this.showPreview){
                    p.body = '<p><a href="javascript:showDetails(\''+record.id+'\');"><img src="http://www.centraloregonrealtors.com/listings/thmbvga/th'+record.id+'.jpg" align="left"></a>'+record.data.address+'<br><br>'+record.data.publicremarks+' <a href="javascript:showDetails(\''+record.id+'\');">Show Details</a></p>';
                    return 'x-grid3-row-expanded';
                }
                return 'x-grid3-row-collapsed';
            }
        },

        tbar: new Ext.PagingToolbar({
            pageSize: 25,
            store: store,
           items:[
                '-', {
                pressed: false,
                enableToggle:true,
                text: 'List/Map View',
                cls: 'x-btn-text-icon details',
                toggleHandler: function(btn, pressed){
                    var view = Ext.getCmp('grid').getView();
                    view.showPreview = pressed;
                    view.refresh();
		    if(pressed)
		    {
			    
			   Ext.getCmp('centerPanel').remove('grid',false);
			  // theGrid.setHeight(500);
			    Ext.getCmp('cards').add(theGrid);
			   Ext.getCmp('cards').layout.setActiveItem(1);
			    Ext.getCmp('cards').doLayout(false,true);
			    Ext.getCmp('overviewPanel').collapse(false);
			   
		    }
		    else
		    {
			    Ext.getCmp('cards').remove('grid',false);
			    theGrid.setHeight(200);
			    Ext.getCmp('centerPanel').add(theGrid);
			    Ext.getCmp('cards').layout.setActiveItem(0);
			     Ext.getCmp('cards').doLayout(false,true);
			     Ext.getCmp('overviewPanel').expand(false);
		    }
                }
            }]

        })
    
			     
     };
     var theGrid = new Ext.grid.GridPanel(theGridConf);
     var viewPanel = new Ext.Viewport({
	   
	   
	    layout: 'border',
	    items: [{
		region:'north',
		id: 'headerContainer',
		layout: 'fit',
		contentEl: 'headerDiv'
	    },
	    {
		    title: 'Search Central Oregon MLS ',
		region:'west',
		width: 250,
		collapsible: true,   
		id: 'west-region-container',
		layout: 'fit',
		contentEl: 'searchForm',
		autoScroll: true
	    },{
		region: 'center',
		layout: 'card',
		activeItem: 0,
		id: 'cards',
		items: [
		{
			region: 'center',
			layout: 'border',
			id: 'centerPanel',
			items: [{
				region: 'center', 
				layout: 'fit',
				xtype: 'gmappanel',
				zoomLevel: 12,
				gmapType: 'map',
				setCenter: {
				lat: '44.0581728',
				long: '-121.3153096'
				},
				id: 'map',
				hidden: false
	
			},
			theGrid
			]
		
		}]
		

	    },{
		title: 'Property Preview ',
		region:'east',
		width: 250,
		collapsible: true,  
		cmargins: '5 5 0 5',
		id: 'overviewPanel',
		contentEl: 'overviewPanelDiv',
		layout: 'fit',
		bodyStyle: 'background-color:#ffffff;'
	    }]
	});


    

    // pluggable renders
    function renderMLSNumber(value, p, record){
	  return '<a href="javascript:showDetails(\''+record.id+'\');">' + value + '</a>'  
    }
    
    function renderSubdivision(value, p, record){
        //return String.format(
        //        '{0} bed, {1} bath in {2}',
        //        record.data.bedrooms, record.data.bathrooms, record.data.city);
	if(value =='cla' || value =='Cla' || value =='' )
		return 'M&B';
	return value;
    }
    function renderLast(value, p, r){
        return String.format('{0}<br/>by {1}', value.dateFormat('M j, Y, g:i a'), r.data['lastposter']);
    }


});

function dataStoreLoaded(store,records,options)
{
	map = Ext.getCmp('map');
	for(i=0; i<records.length; i++)
	{
		if(records[i].get('address').trim() != '')
		{
			
			
			html = getInfoWindowHtml(records[i]); 
			
			gShowAddress(addressFull,html,records[i].id);
		}
	}
}

function getInfoWindowHtml(record)
{
	address = record.get('address');
	city = record.get('city');
	subdivision = record.get('subdivision');
	addressFull = address + ' ' +city + ' oregon';
	id = record.get('id');
	bathrooms = record.get('bathrooms');
	bedrooms = record.get('bedrooms');
	publicremarks = record.get('publicremarks');
	price = Ext.util.Format.usMoney(record.get('price'));
	squareFeet = record.get('squareFeet');
	
	return '<table width="400" border="0" cellspacing="0" cellpadding="0" class="thTable"><tr><td valign="top" width="160"><img src="http://www.centraloregonrealtors.com/listings/thmbvga/th'+id+'.jpg" border="0" alt="" height="120" width="160"></td><td align="left" style="padding-left: 10px;padding-top:5px;background:url(yw_corner-lt.jpg) top left no-repeat;" valign="top"><h3>MLS#:'+id+'</h3><span class="price">'+price+'</span><br>'+address+', '+ city +'<br>'+ subdivision +'<br>'+ bedrooms +' Bed&nbsp;&nbsp;'+ bathrooms +' Bath&nbsp;&nbsp;'+ squareFeet +' SqFt.<br><a href="javascript:showDetails(\''+id+'\');">Show Details</a></td></tr></table>';
}

function gShowAddress(addy,html,record)
{
	geocoder = new GClientGeocoder();
			geocoder.getLatLng(addy,function (point)
			{
				
				if(point)
				{
					map = Ext.getCmp('map');
					map.gmap.setCenter(point, 11);
					
					var customIcon = new GIcon(G_DEFAULT_ICON);
					customIcon.image = "http://coar.centraloregonrealtors.com/gobend/marker2.gif";
					
					marker = new GMarker(point,{ icon:customIcon })
					GEvent.addListener(marker,"click", function() {
							map.gmap.openInfoWindowHtml(point, html);
							markerSelEvent(point);
					});
				
					
					//map.gmap.addOverlay(marker);
					map.mgr.addMarker(marker,6);
					property = store.getById(record);
					property.set('marker',point);
				
				}
			
			}
			);
}

function markerSelEvent(point)
{
	record = store.getAt(store.find('marker',point));
	previewProperty(record);
	Ext.getCmp('grid').getSelectionModel().suspendEvents();
	Ext.getCmp('grid').getSelectionModel().selectRecords(new Array(record));
	//Ext.getCmp('grid').getView().focusRow(1);
	Ext.getCmp('grid').getSelectionModel().resumeEvents();
}


function gridRowSelect(model,index,record)
{
	previewProperty(record);
	map = Ext.getCmp('map');
	point = record.get('marker');
	
	if(point  && point != '')
	{
		map.gmap.setCenter(point, 11);
		marker = map.mgr.getMarker(point.lat(),point.lng(),6);
		marker.openInfoWindowHtml(getInfoWindowHtml(record));
	}
	else
	{
		map.gmap.closeInfoWindow();
	}
}

function previewProperty(record)
{
	address = record.get('address');
	city = record.get('city');
	subdivision = record.get('subdivision');
	addressFull = address + ' ' +city + ' oregon';
	
	id = record.get('id');
	point = record.get('marker');
	bathrooms = record.get('bathrooms');
	bedrooms = record.get('bedrooms');
	description = record.get('publicremarks');
	if(record.get('yearBuilt')>0)
		yearBuilt = record.get('yearBuilt');
	else
		yearBuilt = '';
	if(record.get('squareFeet') > 0)
		squareFeet = record.get('squareFeet');
	else
		squareFeet= '';
	if(record.get('acres') > 0)
		acres = record.get('acres')+' acres';
	else
		acres = '';
	price = addCommas(record.get('price'));
	publicremarks = record.get('publicremarks');
	table1 = '<div class="table1"><ul id="right"><li>Baths: '+bathrooms+'</li><li>Year Built: '+yearBuilt+'</li></ul><ul id="left"><li>Beds: '+bedrooms+'</li><li>SqFt.:  '+squareFeet+'</li><li class="long">Lot Size:  '+acres+'</li></ul></div>';
	html = '<div class="details"><div style="text-align:center"><a href="javascript:showDetails(\''+id+'\');"><img src="http://www.centraloregonrealtors.com/listings/thmbvga/th'+id+'.jpg" border="0" alt="" height="120" width="160"></a></div><h3>MLS#:'+id+'</h3><p style="padding:5px;"><span class="price">$'+price+'</span><br>'+subdivision+'<br />';
		
	if(address.trim() != '')
		html = html+address+', '+ city +'<br>';
	if(description != ''){
		tmp = description.split(" ");
		html=html+'</p><p style="border-top:1px dotted black;padding-top:5px;margin-top:5px;background:#eeeeee">';
		if(tmp.length > 30){
			for(i = 0; i < 31; i++){
				html = html+tmp[i]+" ";
			}
		}
		else{
			html = html + description;
		}
		html = html+'... <a href="javascript:showDetails(\''+id+'\');">read more</a>.';
	}
	html= html+'</p>'+ table1+'<br><br><a href="javascript:showDetails(\''+id+'\');" class="searchButton">Show Details</a></div>';
	Ext.get('overviewPanelDiv').update(html);
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


function showListPreview()
{
	var view = Ext.getCmp('grid').getView();
	view.showPreview = true;
	view.refresh();
	
	Ext.getCmp('centerPanel').remove('grid',false);
	Ext.getCmp('cards').add(Ext.getCmp('grid'));
	Ext.getCmp('cards').layout.setActiveItem(1);
	Ext.getCmp('cards').doLayout(false,true);
	Ext.getCmp('overviewPanel').collapse(false);	
}

function showDetails(id)
{
	
            win = new Ext.Window({
                layout:'fit',
                width:700,
                height:500,
                //closeAction:'hide',
                plain: true
		
            });
       
        win.show(this);
	Ext.get(win.body.id).update('<iframe border="0" width="100%" height="100%" src="http://coar.centraloregonrealtors.com/gobend/detailsView.php?rowid='+id+'"></iframe>');

}

function searchMLS()
{
	map = Ext.getCmp('map');
	map.gmap.clearOverlays();
	
	if(document.getElementById('bankowned').checked)
		termData = 'yes';
	else
		termData = 'no';
	
	store.load({params:{start:0, limit:25, action: 'newquery', 
	proptype: document.getElementById('proptype').options[document.getElementById('proptype').selectedIndex].value,
	area: document.getElementById('area').options[document.getElementById('area').selectedIndex].value,
	minprice: document.getElementById('minprice').options[document.getElementById('minprice').selectedIndex].value,
	maxprice: document.getElementById('maxprice').options[document.getElementById('maxprice').selectedIndex].value,
	bedroomslow: document.getElementById('beds').options[document.getElementById('beds').selectedIndex].value,
	bathroomslows: document.getElementById('baths').options[document.getElementById('baths').selectedIndex].value,
	minacres: document.getElementById('minacres').options[document.getElementById('minacres').selectedIndex].value,
	maxacres: document.getElementById('maxacres').options[document.getElementById('maxacres').selectedIndex].value,
	addition: document.getElementById('addition').options[document.getElementById('addition').selectedIndex].value,
	minsqft: document.getElementById('minsqft').options[document.getElementById('minsqft').selectedIndex].value,
	view: document.getElementById('view').options[document.getElementById('view').selectedIndex].value,
	bankowned: termData,
	listingid: document.getElementById('listingid').value
	}});
}
