/*
 * Copyright(c) 2007, Soft Idiom 
 * www.softidiom.com
 */

var entity = 'Property';
var entities = 'Properties';
var grid, store, types, propertyWindow, storefirstload = true;
var selected = [];
var viewID;
Ext.BLANK_IMAGE_URL = '/shared/ext-2.2/resources/images/default/s.gif';

Ext.override( Ext.ux.grid.GridFilters , {
	buildQuery : function(filters) {
		return {filters: Ext.encode(filters)};
	}
});

Ext.onReady(function(){
	window.onbeforeunload = confirmExit;
	Ext.QuickTips.init();
	var request = Ext.urlDecode(window.location.search.substring(1));
	
	Ext.ux.menu.RangeMenu.prototype.icons = {
		gt: '/shared/images/icons/greater_than.png', 
		lt: '/shared/images/icons/less_than.png',
		eq: '/shared/images/icons/equals.png'
	};
	Ext.ux.grid.filter.StringFilter.prototype.icon = '/shared/images/icons/find.png';
	var filters = new Ext.ux.grid.GridFilters({filters:[
	]});

    // create the Data Store
    store = new Ext.data.GroupingStore({
        proxy: new Ext.data.HttpProxy({
            url: '/site/get.php'
        }),
        // create reader that reads the records
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'total',
            id: 'si_reference',
            fields: [
                'si_reference','si_name','si_type','si_location','si_price','si_range','si_summary','si_area1','si_area2','si_area3','si_area4','si_area5','si_feature1','si_feature2','si_feature3','si_feature4','si_feature5','si_feature6','si_feature7','si_feature8','si_feature9','si_feature10','si_internal','si_external','si_description','si_locationtype','si_longitude','si_latitude','si_thumbnail','si_photo','si_map','si_photo1','si_photo2','si_photo3','si_photo4','si_photo5','si_photo6','si_photo7','si_photo8','si_photo9','si_photo10'            ]
        }),
        sortInfo: {field:'si_price', direction:'DESC'},
        remoteSort: true
    });
	if(request.ref) {
		store.baseParams.find_reference = request.ref;
	}
	store.on('beforeload', function() {
		if(!storefirstload) {
			var find_type = Ext.get('find_type').getValue();
			if(!find_type && find_type != 'Any' || find_type != '') {
				store.baseParams.find_type = find_type;
			}
			var find_price = Ext.get('find_price').getValue();
			if(!find_price && find_price != 'Any' || find_price != '') {
				store.baseParams.find_price = find_price;
			}
			var find_location = Ext.get('find_location').getValue();
			if(!find_location && find_location != 'Any' || find_location != '') {
				store.baseParams.find_location = find_location;
			}
			var find_reference = Ext.get('find_reference').getValue();
			if(!find_reference && find_reference != 'Any' || find_reference != '') {
				store.baseParams.find_reference = find_reference;
			}
		}
		storefirstload = false;
	});
	store.on('load', function(s,r,o) {
		var index = 0;
		for (i=0;i<=selected.length;i++) {
			index = store.indexOfId(selected[i]);
			sm.selectRow(index,true);
		}

	});

    prices = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/site/prices.php'
        }),
        // create reader that reads the records
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'total',
            id: 'si_position',
            fields: [
                'si_range'
            ]
        }),
        sortInfo: {field:'si_position', direction:'ASC'},
        remoteSort: true
    });
    prices.on('load',function(){prices.insert(0,new Ext.data.Record({si_position:-1,si_range:'Any'}))});

    types = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/site/types.php'
        }),
        // create reader that reads the records
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'total',
            id: 'si_property_type',
            fields: [
                'si_property_type'
            ]
        }),
        sortInfo: {field:'si_property_type', direction:'ASC'},
        remoteSort: true
    });
    types.on('load',function(){types.insert(0,new Ext.data.Record({si_property_type:'Any'}))});

    location_types = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: '/site/location_types.php'
        }),
        // create reader that reads the records
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'total',
            id: 'si_location_type',
            fields: [
                'si_location_type'
            ]
        }),
        sortInfo: {field:'si_location_type', direction:'ASC'},
        remoteSort: true
    });
    location_types.on('load',function(){location_types.insert(0,new Ext.data.Record({si_location_type:'Any'}))});


    //selection model
    var sm = new Ext.grid.CheckboxSelectionModel();
    sm.on('rowselect',function(sm,row,rec){
    	if(selected.indexOf(rec.data.si_reference) == -1) {
	    	selected.push(rec.data.si_reference);
	    	refreshViewingButton();
	    }
    });

    sm.on('rowdeselect',function(sm,row,rec){
    	selected.remove(rec.data.si_reference);
	    	refreshViewingButton();
    });

    // the column model
    var cm = new Ext.grid.ColumnModel([
    sm,
	{
		header: 'Summary', dataIndex: 'si_name', width: 415, 
		renderer: function(v,m,r,ri,ci,s) {
			var image = r.data.si_thumbnail || r.data.si_photo;
			var path = image.replace('Data\\images\\property\\','/cgi-bin/pf/SISite/data/images/property/');
			return "<img class='property-summary-image' src='"+path+"' width='200' alt='' align='left'/><h3 class='property-summary-name'>"+r.data.si_name+"</h3><p class='property-summary-text'>"+r.data.si_summary.replace('\r\n','</br /></br />')+"</p>";
		}
	},
	{
		header: 'Details', dataIndex: 'si_reference', width: 170,
		renderer: function(v,m,r,ri,ci,s) {
			return "<p class='property-summary-detail'>Reference: "+r.data.si_reference+"</p>"+
				"<p class='property-summary-detail'>Property Type: "+r.data.si_type+"</p>"+
				"<p class='property-summary-detail'>Location:<br />"+r.data.si_location+"</p>"+
				"<p class='property-summary-detail'>Area: "+r.data.si_locationtype+"</p>"+
				"<p class='property-summary-action'><a href='javascript:show(\""+r.data.si_reference+"\",this)'><img src='/shared/images/icons/application_form_magnify.png' alt='' />Full details...</a></p>"+
				"<p class='property-summary-action'><a href='mailto:?subject=I found this great property: www.pioneerfrance.com/property/"+r.data.si_reference+"' target='_top'><img src='/shared/images/icons/email_edit.png' alt='' />Email a friend...</a></p>";
				//"<p class='property-summary-action'><a href='viewing.html?ref="+r.data.si_reference+"' target='pioneerFrameViewing'><img src='/shared/images/icons/date.png' alt='' />Arrange a viewing...</a></p>";
		}
	},
	{
		header: 'Price', dataIndex: 'si_price', align: 'right', width: 70,
		renderer: function(v) {
			var p = Ext.util.Format.usMoney(v).replace('$','€');
			return p.split('.')[0];
		}
	}
	]);

    // by default columns are sortable
    cm.defaultSortable = true;
    var paging = new Ext.PagingToolbar({
        plugins: [
        	new Ext.ux.Andrie.pPageSize({afterText: '&nbsp;'+entities+' per page', variations: [10,15,20,25,30,35,40,45,50]}),
        	filters
        	],
        pageSize: 10,
        store: store,
        displayInfo: true,
        displayMsg: 'Showing {0} - {1} of {2} '+entities+' found',
        emptyMsg: 'No '+entities+' found'
    });
    var grid = new Ext.grid.GridPanel({
    	renderTo: 'properties_grid',
    	height:607,
        //viewConfig: {forceFit:true},
        region:'center',
        store: store,
        cm: cm,
        trackMouseOver: false,
        sm: sm,
        loadMask: true,
        enableColumnHide: false,
        enableColumnMove: false,
        enableColumnResize: false,
		plugins: filters, 
		tbar: [{
			id: 'clearSelectedButton',
			text: 'Deselect Properties',
			iconCls: 'delete',
			handler: function(){
				selected=[];
				sm.clearSelections();
			}
		},'-',{
			id: 'viewingSelectedButton',
			text: 'Select one or more properties to arrange a viewing',
			iconCls: 'viewing',
			handler: function(){
				if(selected.length > 0) {
					window.open('viewing.html?refs='+selected);
				} else {
					Ext.Msg.alert('Note', 'Please select one or more properties from the list below, then click this button to arrange a viewing.');
				}
			}
		}],
        bbar: paging
    });

    // trigger the data store load
    store.load({params:{start:0, limit:10}});

var searchForm = new Ext.form.FormPanel({
	xtype:"form",
	region:'north',
	renderTo: 'properties_filter',
	height:26,
	items:[{
	    layout:"column",
	    labelWidth: 30,
	    border: 'none',
	    items:[{
	        columnWidth:0.25,
	        layout:"form",
	        items:[{
	            xtype:"combo",
	            fieldLabel:"Type",
	            name:"find_type",
	            id:"find_type",
	            style:"font-size:11px",
	            editable: false,
	            width: 130,
	            value:'Any',
	            store: types,
				triggerAction: 'all',
				displayField: 'si_property_type',
				valueField: 'si_property_type',
				listWidth:130,
				listeners: {
					select: function() {paging.changePage(1);store.reload()}
				}
			}]
	      },{
	        columnWidth:0.26,
	        layout:"form",
	        items:[{
	            xtype:"combo",
	            fieldLabel:"Price",
	            name:"find_price",
	            id:"find_price",
	            style:"font-size:11px",
	            editable: false,
	            width:140,
	            value: 'Any',
	            store: prices,
				triggerAction: 'all',
				displayField: 'si_range',
				valueField: 'si_range',
				listWidth:150,
				listeners: {
					select: function() {paging.changePage(1);store.reload()}
				}
	          }]
	      },{
	        columnWidth:0.21,
	        layout:"form",
	        items:[{
	            xtype:"combo",
	            fieldLabel:"Area",
	            name:"find_location",
	            id:"find_location",
	            style:"font-size:11px",
	            editable: false,
	            width:100,
	            value: 'Any',
	            store: location_types,
				triggerAction: 'all',
				displayField: 'si_location_type',
				valueField: 'si_location_type',
				listeners: {
					select: function() {paging.changePage(1);store.reload()}
				}
	          }]
	      },{
	        columnWidth:0.26,
	        layout:"form",
	        labelWidth: 60,
	        items:[{
	            xtype:"textfield",
	            fieldLabel:"Reference",
	            name:"find_reference",
	            id:"find_reference",
	            style:"font-size:11px",
	            //triggerClass: 'x-form-clear-trigger',
	            width: 114,
	            value: request.ref,
				listeners: {
					 specialkey: function() {if(Ext.EventObject.getKey()==13){paging.changePage(1);store.reload()}}
				}

	          }]
	      }]
	  }]
	});

    // render it
	//var viewport = new Ext.Viewport({  
	//	layout: "border",
	//	items: [searchForm,grid]
	//});
    //form.render('form');

	function refreshGrid() {
		store.reload();
	}
	
});

function confirmExit() {
	//if there is dirty data prompt to save it
	if (formIsDirty()) {
		return 'There are unsaved changes. If you continue the changes will be lost.';
	}
}
  
function formIsDirty() {
	//return true if the grid has unsaved changes
	for (var i = 0 ;i < store.getCount(); i++) {
		var rec = store.getAt(i);
		if (rec.dirty){
			return true;
		}
	}
	return false;
}

function show(id,link) {
	viewID = id;
	var property = store.getById(id);
	if(!propertyWindow) {
		propertyWindow = new Ext.Window({
			id: 'propertyWindow',
			width: 500,
			height: 300,
			closeAction:'hide',
			maximizable: true,
			minimizable: false,
			resizable: false,
			shadow: false,
			plain: true,
			html: '<iframe id="propertyDetailsFrame" name="propertyDetailsFrame" src="/site/properties/details.php?ref='+property.data.si_reference+'" frameborder="0" width="100%" height="100%">Your browser does not support iframes - sorry</iframe>',
			tbar:[{
				text: 'Email&nbsp;a&nbsp;friend',
				iconCls: 'email',
				handler: function(){
					top.location="mailto:?subject=I found this great property: www.pioneerfrance.com/property/"+property.data.si_reference;
				}
			},'-',{
				text: 'Arrange&nbsp;a&nbsp;viewing',
				iconCls: 'viewing',
				handler: function(){
					var viewingWindow = window.open('viewing.html?refs='+viewID);
				}
			},'-',{
				text: 'How&nbsp;to&nbsp;print&nbsp;these&nbsp;details',
				iconCls: 'print',
				handler: function(){
					Ext.Msg.alert('How to Print', 'To print these property details, click the <b>Printable PDF </b> button (top left) to open them as a Adobe PDF document which you can print. To open PDF documents you will need Adobe Acrobat Reader which you can <a href="http://get.adobe.com/uk/reader/" target="_blank">download from here</a> if not already installed.');
				}
			},'-',{
				text: 'Printable&nbsp;PDF',
				iconCls: 'pdf',
				handler: function(){
					window.open('/site/pdfdoc.php?ref='+viewID);
				}
			},'-',{
				text: '<b>Close&nbsp;details&nbsp;to&nbsp;return&nbsp;to&nbsp;your&nbsp;search</b>',
				iconCls: 'close',
				handler: function(){
					propertyWindow.hide();
				}
			}]
		});
		propertyWindow.on('show',function(){
			document.body.style.overflow='hidden';
			document.body.scrollTop = 0;
			document.getElementsByTagName('html')[0].scrollTop = 0;
			document.getElementsByTagName('html')[0].style.overflow = "hidden";
		});
		propertyWindow.on('hide',function(){
			document.body.style.overflow='auto';
			document.getElementsByTagName('html')[0].style.overflow = "auto";
		});
	} else {
		document.getElementById('propertyDetailsFrame').src='/site/properties/details.php?ref='+property.data.si_reference;
	}
	var title = property.data.si_name ? 'Property Details for "'+property.data.si_name+'"' : 'Property Details';
	title+= '(reference: '+property.data.si_reference+')';
	propertyWindow.setTitle(title);
	propertyWindow.show();
	propertyWindow.maximize();
}

function print_iframe(s) {
    //s being iframe's _name_, generally distinct from the id.
    if (navigator.userAgent.indexOf("Opera")!=-1) {
       var owin=window.open(s.location);
			owin.opener.focus();    //lose its focus(): it matters
			owin.print();
			//owin.close();
			//owin=null;
    } else {
        s.focus();    //get its focus(): it matters
        s.print();
    }
}

function refreshViewingButton() {
	var viewingSelectedButton = Ext.getCmp('viewingSelectedButton');
	var clearSelectedButton = Ext.getCmp('clearSelectedButton');
	if(selected.length == 0) {
		viewingSelectedButton.setText('Select one or more properties to arrange a viewing');
		clearSelectedButton.setText('Deselect Properties');
	} else {
		viewingSelectedButton.setText('Arrange to view '+selected.length+(selected.length<2?' property':' properties'));
		clearSelectedButton.setText('Deselect '+selected.length+(selected.length<2?' property':' properties'));
	}
}