/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
Ext.onReady(function() { // create the Data Store
	var store = new Ext.data.Store({ // load using HTTP
		proxy: new Ext.data.HttpProxy({
			url: xcart_web_dir + '/venues-ajax.php',
			method: 'GET'
		}),
		baseParams: {
			task: "LISTING",
      cat: 1,
      state: "GETALL",
			request: "customer"
                         
		},
		// this parameter is passed for any HTTP request
		// the return will be JSON, so lets set up a reader
		reader: new Ext.data.JsonReader({ // records will have an "Item" tag
			root: 'venues',
			id: 'venueid',
			totalProperty: 'results'
		},
		[ // set up the fields mapping into the xml doc
		// The first needs mapping, the others are very basic
		{
			name: 'Title',
			mapping: 'title'
		},
		{
			name: 'venueid',
			mapping: 'venueid'
		},
		{
			name: 'Price',
			mapping: 'price'
		},
		{
			name: 'Teacher',
			mapping: 'teacher'
		},
		{
			name: 'Start',
			mapping: 'start'
		},
		{
			name: 'Venue',
			mapping: 'vname'
		},
		{
			name: 'Phone',
			mapping: 'phone'
		},
		{
			name: 'State',
			mapping: 'state'
		},
		{
			name: 'Address',
			mapping: 'address'
		},
		{
			name: 'City',
			mapping: 'city'
		},
		{
			name: 'Zipcode',
			mapping: 'zipcode'
		}])
	});
        
       /* alternative to above. but need GET so use above
        var store = new Ext.data.JsonStore({ 
	url: xcart_web_dir + '/products-ajax.php',
	root: 'products',
	baseParams: [{task: "LISTING"}, {cat: 1},{state: ""}],
	fields: [
  {	name: 'Hostsite',	mapping: 'p_data.company'},
	{	name: 'Title', 	mapping: 'product'},
	{	name: 'productid',mapping: 'productid'},
	{	name: 'Price',	mapping: 'price'},
	{	name: 'Teacher',	mapping: 'extra_fields.teacher'},
	{	name: 'Start',	mapping: 'extra_fields.start'},
	{	name: 'State',	mapping: 'p_data.b_state'},
	{	name: 'Avail',	mapping: 'avail'},
	{	name: 'Address',mapping: 'p_data.b_address'},
	{	name: 'City',	mapping: 'p_data.b_city'},
  {	name: 'Zipcode',	mapping: 'p_data.b_zipcode'}
	]
});
       */ 
        //Define paging toolbar
	var pagingBar = new Ext.PagingToolbar({
		pageSize: 15,
		store: store,
		displayInfo: true,
		displayMsg: 'Displaying classes {0} - {1} of {2}',
		emptyMsg: "No classes to display"
	}); // create the grid
	var grid = new Ext.grid.GridPanel({
		store: store,
		columns: [
		{
			header: "City/Town",
			width: 80,
			dataIndex: 'City',
			sortable: true
		},
		{
			header: "Venue",
			width: 160,
			dataIndex: 'Venue',
			sortable: true
		},
		{
			header: "Phone",
			width: 100,
			dataIndex: 'Phone',
			sortable: true
		}
		
		],
		sm: new Ext.grid.RowSelectionModel({
			singleSelect: true
		}),
		viewConfig: {
			forceFit: true,
			emptyText: '<span style=\'font-size:14px;\'>I\'m sorry, currently there are no host sites offering classes in your area. Please check back soon as we are adding new host sites regularly.<br>Also, we encourage you to send us a quick email to:  pianoguy@scotthouston.com to let us know what city you would like to see classes offered.<br><br>In the mean time if you would like to find out about other home study materials available from Scott that will allow you to learn how to play the piano or organ at your own pace at home, please <a href=\'http://www.scotthouston.com/store/home.php\' style=\'font-weight:bold;text-decoration:underline;\'>click here</a>. </span>',
			deferEmptyText:true
		},
		height: 370,
		split: true,
		region: 'center',
		// paging bar on the bottom
		bbar: pagingBar,
		loadMask:true
	});

        // define a template to use for the detail view
	var bookTplMarkup = ['Title: {Title}<br/>', 'Teacher: {Teacher}<br/>', 'Price: ${Price}<br/>', 'Address: {Address}<br/>', 'City: {City}<br/>', 'State: {State}<br/>', 'Zipcode: {Zipcode}<br/>', 'Description: This is the {[values.Title.substr(6,1)]}', '<tpl if="values.Title == \'Class 1\'">', 'st', '</tpl>', '<tpl if="values.Title == \'Class 2\'">', 'nd', '</tpl>', '<tpl if="values.Title != \'Class 1\' && values.Title != \'Class 2\'">', 'rd', '</tpl>', ' eight week session of the \'Play Piano In A Flash\' classes<br/><br/>', '<input type="button" value="Register" id="cart-btn" style="margin-right:5px;"/><input type="button" value="Get me a Map" id="show-btn"/><br/><br/>','<input type="hidden" id="pid" value="{productid}" /><input type="hidden" id="geoLoc" value="{Address},{City},{State},{Zipcode}" /><input type="hidden" id="hostSite" value="{Hostsite}" />'];
	var bookTpl = new Ext.XTemplate(bookTplMarkup);
	var ct = new Ext.Panel({
		renderTo: 'grid-classes',
		frame: true,
		title: 'Class Locations <span style=\'font-size:9px;\'>(click on a specific line to see classes available at that Venue)</span>',
		width: 540,
		height: 450,
		layout: 'border',
		items: [grid
		/*, {
			id: 'detailPanel',
			region: 'center',
			bodyStyle: {
				background: '#ffffff',
				padding: '7px'
			},
			html: 'Please select a location to see additional details.'
		}
		*/]
	});
  grid.getSelectionModel().on('rowselect',
	function(sm, rowIdx, r) {
		/*var detailPanel = Ext.getCmp('detailPanel');
		bookTpl.overwrite(detailPanel.body, r.data);
		Ext.map.showBtn();
		showCartBtn();*/
		var el = grid.getEl();  //get underlying grid element 
		el.mask("Loading...");
		document.location.href = current_location + '/home.php?cat=1&vid='+r.data.venueid;
		
	});
	//store.load();   
	//store.load({params:{start:0, limit:15}});

	//store.setDefaultSort('City', 'ASC');
	
	var showCartBtn = function() {
		var cartButton = Ext.get('cart-btn');
		cartButton.on('click', function(){
			var pid = Ext.get('pid').dom.value;
			var cartURL= current_location + '/cart.php?mode=add&productid='+pid+'&amount=1';
			//alert (cartURL);
			document.location.href = cartURL;
		});
	};
	
	        //state selector
	var fstate = new Ext.FormPanel({
		frame: true,
		//title: 'Search for your local host site',
		title: 'Select state',
		labelAlign: 'right',
		labelWidth: 85,
		width: 340,
		waitMsgTarget: true,
		items: [
      
			new Ext.form.FieldSet({
			//title: 'Select state',
			defaultType: 'textfield',
			autoHeight: true,
			items: [
      
			new Ext.form.ComboBox({
				fieldLabel: 'State',
				hiddenName: 'state',
				store: new Ext.data.SimpleStore({
					fields: ['abbr', 'state'],
					data: Ext.exampledata.states // from states.js
				}),
				valueField: 'abbr',
				displayField: 'state',
				typeAhead: true,
				mode: 'local',
				triggerAction: 'all',
				emptyText: 'Select a state...',
				selectOnFocus: true,
				width: 190
			})]
		})]
	});
        
	fstate.items.items[0].items.items[0].on('select', function() {
             
    Ext.get('grid-classes').dom.style.visibility = 'visible';
	Ext.get('gmap-display').dom.style.display = 'none';
	Ext.get('gmap-help').dom.innerHTML = '';

    
    store.baseParams.state = this.value;
    store.load({params:{start:0, limit:15}});
    //grid.getView().refresh();  causes issues with the grid deferEmptyText:true
  });
	fstate.render('state-selector'); // end state selector
	
});
