Ext.namespace('Ext.ux');

	function addBookmark() {
		var url = 'http://mysurround.sg/'; 
		var title = 'Surround Networks (MySurround.sg)'; 
		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url, '');
		} else if (window.external) { // IE Favorite
			window.external.AddFavorite(url, title);
		} else { 
    		alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
		}
	}
	
	function findIndex(array, value)
	{
		for(var i=0; i<array.length; i++)
		{
			if(array[i]==value)
				return i;
		}
		return -1;
	}
	
	function displayResult(activateNewTab, bRTMessages) 
	{
		var accordionContainer = Ext.getCmp('west-panel');
		var k = surroundData.length-1;
		
		var panel = generateWestPanel(k, bRTMessages);
		accordionContainer.add(panel);
		accordionContainer.doLayout(false, true);
		
		// Open the accordion for the result
		if (activateNewTab) {
			accordionContainer.getLayout().setActiveItem(k);
			// Another way to expand the accordion tab: 
			// panel.expand(true);
			// This property is read-only: accordionContainer.layout.activeItem = panel;			
		}
		
		// Open the west panel, if not yet opened
		if (accordionContainer.collapsed) {
			accordionContainer.expand(true);
			// viewport.layout.west.slideOut();
		} 
		
		addMarker(k);		
	}
	
	function pollRTMessages() {
		//alert('Polling...');
		Ext.Ajax.request({
			url: 'query.jsp',
			// method: 'GET',
			params: {'q':'messages', 'srid':srid},
			success: function(response, opts) {
				//alert(response.responseText);
				
				try {
					var queryResult = Ext.decode(response.responseText);
					// alert(queryResult);

					var rtTabNdx = findIndex(surroundDataNames, 'Real-Time Messages');
					if (rtTabNdx) {
						surroundData[rtTabNdx] = queryResult;
						
						// refresh corresponding tab in west-panel					
						if (rtListView) {
							rtStore.loadData(queryResult, false);
							
							if (rtListView.isVisible()) {					
								rtListView.refresh();		
							}				
						}
																	
						// Add new markers to the map
						addMarker(rtTabNdx);
					}
				} catch (e) {
					if (rtTimer >= 0) {
						clearInterval(rtTimer);
						rtTimer = -1;
						
						if (confirm('Your session has expired. Would you like to re-connect?')) {
							setMyLoc();
						}
					}
				}
			}
		})
	}
	
	function query(q, label, activateNewTab, checkedSelectorsNdx) 
	{	
		if (!label) {
			return;  // ignore null or undefined label
		}
		
		Ext.Ajax.request({
			url: 'query.jsp',
			// method: 'GET',
			params: {'q':q, 'srid':srid},
			success: function(response, opts) {
				//alert(response.responseText);
				
				try {
					surroundDataNames.push(label);
					
					var queryResult = Ext.decode(response.responseText);
					//alert(queryResult);

					surroundData.push(queryResult);
					
					// Special case for real-time messages			
					if (q == 'messages') {
						displayResult(activateNewTab, true);
						
						rtTimer = setInterval('pollRTMessages()', 5000);
						// alert('Timer id: ' + rtTimer);
					} else {
						displayResult(activateNewTab);
					}
					
					// For chaining (sequencing) multiple queries
					if (checkedSelectorsNdx != undefined) {
						checkedSelectorsNdx++;
						reload(checkedSelectorsNdx);
					}
				} catch (e) {
					// session expired
					alert('Your session has expired! We will attempt to re-connect now.');
					setMyLoc();
				}
			}
		})
	}
	
	function generateWestPanel(k, bRTMessages)
	{
		var store = new Ext.data.ArrayStore(
		{
			idIndex: 0,
			fields: surroundDataFields,
			data: surroundData[k]
		});
		store.autoDestroy = true;
		
		//store.load() is not needed in this case because this is just using array;if using proxy, load() is needed

		var listView = new Ext.ListView(
		{
			store: store,
			columns: 
			[
				{
					header:'',
					id:'id',
					width:'230px',
					dataIndex:'title',
					xtype: 'templatecolumn',				
					tpl: '<div style="white-space:normal"><b>{title}</b><br>{description}</div>'
				}
			],
			hideHeaders: true,
			multiSelect: false,
			singleSelect: true,
			reserveScrollOffset: false					
		});

		listView.on('selectionchange', function(view, selections)
		{
			if (selections[0]) {
				var selectedIndex = selections[0].viewIndex;
				var items = view.store.data.items;
				var selectedItem = items[selectedIndex];
				var selectedItemId = selectedItem.id;
				
				// if selectedItemId='0', this is "No result found" line
				if (selectedItemId != '0') {
					selectorWin.collapse(true); 
					openInfoWindow(selectedItemId);
				}
			}
		});

		var iconClsStr = '';
		if (surroundData[k][0]) {
			iconClsStr = 'accordion-'+surroundData[k][0][5]+'-icon';
		}
		
		var panel = new Ext.Panel(
		{
			title: surroundDataNames[k],
			id: 'accordionPanel'+surroundDataNames[k],
			border: false,
			layout: 'fit',
			items: listView,
			iconCls: iconClsStr
		});
		
		if (bRTMessages) {
			rtStore = store;
			rtListView = listView;
		}
		
		return panel;
	}
	
	function generateListPanel()
	{
		var listViewPanel = new Array();
		
		for(var k=0; k<surroundData.length; k++)
		{
			var panel = generateWestPanel(k);
			listViewPanel[k] = panel;			
		}
		return listViewPanel;
	}
		
	function reset() 
	{
		if (rtTimer >= 0) {
			clearInterval(rtTimer);
			rtTimer = -1;
		}
		
		rtStore = null;
		rtListView = null;
		
		// backup surroundDataNames for reload() function below
		prevSurroundDataNames = surroundDataNames;
		
		surroundData.length = 0;
		surroundDataNames = [];   // create new object, instead of clearing, so that prevSurroundDataNames is valid
		gMarkers = new Object();
		gMarkerHtmls = new Object();
		
		clearMapOverlay();
		var accordionContainer = Ext.getCmp('west-panel');
		accordionContainer.removeAll();
	}
	
	function reload(i) 
	{	
		if (i == undefined) {
			i = 0;
		}
		
		if (i < checkedSelectors.length) {
		//for (var i=0; i<checkedSelectors.length; i++) {
			var cbName = checkedSelectors[i];
			
			// Special case for search box
			if (cbName == 'search-checkbox') {
				query(searchQuery, 'Search: ' + searchQuery, false, i);
				return;
			}
					
			var name = prevSurroundDataNames[i];
			var queryStr = defaultQueries[cbName];
			if (queryStr) 
			{
				query(queryStr, name, false, i);
			} 
			else 
			{
				alert('This checkbox is not yet functional!');
			}
		//}
		}
	}

SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        Ext.ux.form.SearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        });
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    width:180,
    hasSearch : false,
    paramName : 'query',

    onTrigger1Click : function(){
        if(this.hasSearch){
            this.el.dom.value = '';            
            this.triggers[0].hide();
            this.hasSearch = false;
            searchCB.setValue(false); 
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
        
        if (searchQuery != null) {
        	// Clear old search result first
        	searchCB.setValue(false);
        }
        
        searchQuery = v;
        
        this.hasSearch = true;
        this.triggers[0].show();
		searchCB.setValue(true);        
    }
});

Ext.onReady
(
	function()
	{				
		detailWinTabs = new Ext.ux.VerticalTabPanel(
		{
			activeTab: 0,
			tabPosition:'left',  //choose 'left' or 'right' for vertical tabs; 'top' or 'bottom' for horizontal tabs
			tabWidth:130,
			tabCls:'detail-win-tabs',
			defaults:{autoScroll: true},
			items:
			[
			]
		})
		
		detailWin = new Ext.Window(
		{
		    modal:true,
		    maximizable:true,
		    minimizable:false,
			width:680,
		    layout:'fit',
		    closeAction:'hide',
		    height:480,
		    title:'Detail Information',
		    items:
			[
				detailWinTabs
			]
		});
						
		var checkBoxListeners = 
		{
			check: function(checkBox, checked)
			{
				if (!isMyLocSet) {
					Ext.Msg.alert('Information', 'Please first enter your location, or click the &quot;Auto Locate&quot; button, to start.');
					checkBox.reset(); // undo
					return;
				}								
				
				var checkBoxId = checkBox.getName();
				
				if(checked) //need to add panel
				{
					checkedSelectors.push(checkBoxId);
					
					// Special case for search box
					if (checkBoxId == 'search-checkbox') {
						query(searchQuery, 'Search: ' + searchQuery, true);
						return;
					}
					
					var queryStr = defaultQueries[checkBoxId];
					// alert(queryStr);
					if (queryStr) 
					{
						query(queryStr, checkBox.boxLabel, true);
					} 
					else 
					{
						alert('This checkbox is not yet functional!');
					}
										
				}
				else //need to remove the panel
				{
					var cbidx = findIndex(checkedSelectors, checkBoxId);
					// alert(cbidx);
					if (cbidx >= 0) {
						checkedSelectors.splice(cbidx,1);
					}
					
					var name = checkBox.boxLabel;
					
					// Special case for search box
					if (checkBoxId == 'search-checkbox') {
						name = 'Search: ' + searchQuery;
					}
					
					// Special case for real-time messages
					if (checkBoxId == 'cb-service-message') {
						if (rtTimer >= 0) {
							clearInterval(rtTimer);
							rtTimer = -1;
						}
						rtStore = null;
						rtListView = null;
					}
					
					var idx = findIndex(surroundDataNames, name);
					
					if (idx >= 0) {				
						var currentData = surroundData[idx];
						
						surroundData.splice(idx,1);
						surroundDataNames.splice(idx,1);
						
						var accordionContainer = Ext.getCmp('west-panel');
						accordionContainer.remove('accordionPanel'+name);
						accordionContainer.doLayout();
						
						for(var j=0; j<currentData.length; j++)
						{
							var point = currentData[j];
							var pointId = point[0];
							
							if (pointId != '0') {  // point id '0' is for "No results found".
								var gMarker = gMarkers[pointId];
								removeMarker(gMarker);
								delete gMarkers[pointId];
								delete gMarkerHtmls[pointId];
							}
						}
					}
				}
				
				
			}
		};
		
		searchCB = new Ext.form.Checkbox({
					xtype: 'checkbox',
	                fieldLabel: ' ',
	                boxLabel: '      ',
	                name: 'search-checkbox',
	                checked: searchCBChecked,
	                listeners: checkBoxListeners
	            });
					            
		searchBox = new SearchField({
	                //store: ds,
	                value: searchQuery,
	                width:200
	            });
					            
		selectorWin = new Ext.Window({
				id: 'selectionPanel',
                applyTo:'selector-win',
                layout:'fit',
				x: Ext.get('mybody').getWidth()-300,
				y: 130,
                width:300,
                height: 265, // 250,
                closeAction:'hide',
                plain: true,
				collapsible: true,
				collapsed: true,  // start with the selection window rolled up
				expandOnShow: false,			
				closable: false,
				resizable: false,
				//disabled: true,
				//border: false,
				//bodyBorder: false,
				//hideBorders: true,
				//draggable: false,
				plain: true,
                items: new Ext.TabPanel // new Ext.Panel
				(
					{
					    //title: 'Accordion Layout',
					    //layout:'accordion',
						//layout: 
						//{
						//	type: 'accordion',
						//	animate: true							
						//},
						activeTab: selectorActiveTab,
						frame: true,
					    defaults: {
					        // applied to each contained panel

					        bodyStyle: 'padding:15px'
					    },
					    layoutConfig: {
					        // layout-specific configs go here
					        //titleCollapse: false,
					        animate: true
					        //activeOnTop: true,							
					    },
					    items: [{
							title: 'Live Services',
							items:
							[
								new Ext.form.CheckboxGroup({
						            xtype: 'checkboxgroup',
						            id: 'cbg-service',
						            fieldLabel: '',						            
						            columns: 1,
									vertical: true,
						            items: 
									[
						                new Ext.form.Checkbox({boxLabel: 'Promotions', name: 'cb-service-promotion', listeners: checkBoxListeners, checked:true}),
						                new Ext.form.Checkbox({boxLabel: 'Announcements', name: 'cb-service-announce', listeners: checkBoxListeners, checked:true}),
										new Ext.form.Checkbox({boxLabel: 'Next-Bus Arrivals', name: 'cb-service-nextbus', listeners: checkBoxListeners, checked:true}),      
										new Ext.form.Checkbox({boxLabel: 'Floor Plan Maps', name: 'cb-service-map', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Real-Time Messages', name: 'cb-service-message', listeners: checkBoxListeners, disabled:false}),
						                new Ext.form.Checkbox({boxLabel: 'Blogs / Websites', name: 'cb-service-blog', listeners: checkBoxListeners, disabled:false})
									]
						        })
							]
					    },{
							title: 'Points of Interest',
							items:
					        [
								new Ext.form.CheckboxGroup({
						            xtype: 'checkboxgroup',
						            id: 'cbg-poi',
						            fieldLabel: '',				            
						            columns: 2,
									vertical: true,
						            items: 
									[
						                new Ext.form.Checkbox({boxLabel: 'Restaurants', name: 'cb-poi-restaurant', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Shops', name: 'cb-poi-shop', checked: false, listeners: checkBoxListeners, disabled:false}),
						                new Ext.form.Checkbox({boxLabel: 'Shopping Malls', name: 'cb-poi-mall', checked: false, listeners: checkBoxListeners, disabled:false}),
						                new Ext.form.Checkbox({boxLabel: 'Hotels', name: 'cb-poi-hotel', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Banks', name: 'cb-poi-bank', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Churches', name: 'cb-poi-church', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Hospitals / Clinics', name: 'cb-poi-hospital', listeners: checkBoxListeners}),
										new Ext.form.Checkbox({boxLabel: 'Bus Stops', name: 'cb-poi-busstop', listeners: checkBoxListeners}),
										new Ext.form.Checkbox({boxLabel: 'MRT Stations', name: 'cb-poi-subway', listeners: checkBoxListeners}),
										new Ext.form.Checkbox({boxLabel: 'Taxi Stands', name: 'cb-poi-taxistand', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Car Parks', name: 'cb-poi-parking', listeners: checkBoxListeners}),
										new Ext.form.Checkbox({boxLabel: 'Tourist Attractions', name: 'cb-poi-touristattraction', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Wi-Fi Hotspots', name: 'cb-poi-wifi', listeners: checkBoxListeners}),
						                new Ext.form.Checkbox({boxLabel: 'Museums', name: 'cb-poi-museum', listeners: checkBoxListeners})
						            ]
						        })
							]
					    },{
					        title: 'More...',
							border: false,
							items:
							[
								{
									layout: 'hbox',
									border: false,
									items:
									[								
										searchCB,
										searchBox
									]
								},
								{
									border: false,
									preventBodyReset: false,
									contentEl: 'connectmore'
								}
							]							
					    }]
					}
				)
            });
		selectorWin.show(true);

		var radiusStore = new Ext.data.ArrayStore({
			fields: ['radius', 'displayText'],
			data : [['0.25', '0.25 km'], 
				['0.5', '0.5 km'], 
				['0.8', '0.8 km'], 
				['1.2', '1.2 km'], 
				['1.5', '1.5 km']]
		});
		
		//signInButton = new Ext.Button({
		//		text: 'Sign In',
		//		listeners: {'click': showSignin}
		//	});
		var signInMenu = new Ext.menu.Menu({
		        id: 'signInMenu',
		        style: {
		            overflow: 'visible'     // For the Combo popup
		        },
		        items: [
		        	{
		        		text: 'As Business Owner',
		        		listeners: {'click': function() {
		        			window.open('/admin');
		        		}}
		        	},
		        	{
		        		text: 'As User / Reviewer',
		        		listeners: {'click': showSignin}
		        	}
				]});
				
		signInButton = new Ext.Button({
            text:'Sign In',
            menu: signInMenu
		});
		
		signOutButton = new Ext.Button({
				text: 'Sign Out',
				listeners: {'click': signout}
			});
		
		if (isSignedIn) {
			signInButton.setVisible(false);
			signOutButton.setVisible(true);
		} else {
			signInButton.setVisible(true);
			signOutButton.setVisible(false);
		}
		
	    viewport = new Ext.Viewport
		(
			{
		        renderTo: Ext.getBody(),
		        layout: 'border',
		        items: 
				[	
					// Start of Header section			
					{
						layout: 'border',
						region: 'north',
						height:80,
						items:
						[
							new Ext.BoxComponent({ 
								region: 'west',
								el: 'logo_name',
								split: false,
								width: 275, // 237 --> 275,  269 --> 307
								style: 'border:0px'
							}),
							{
								region: 'center',
								layout: 'border',
								bodyStyle: 'border:0px',
								items: 
								[
								
									new Ext.Toolbar({
										region:'north',
										height:25,
										style:'border-left: 1px solid #A9BFD3;',
										items:
										[	
											'',								
											new Ext.Button({
												text: 'Bookmark This Site!',
												listeners: {'click': addBookmark}
											}),
											{
												xtype: 'tbfill'
											},
											{
												xtype: 'tbtext', 
												text: 'Connecting Radius: '
											},
											new Ext.form.ComboBox({										
												emptyText: 'Select...',
												store: radiusStore,
												displayField: 'displayText',
												valueField: 'radius',
												value: '0.8',
												editable: false,
												fieldLabel: '',
												hideLabel: true,
												mode:'local',
												forceSelection: true,
												triggerAction:'all',
												selectOnFocus:true,
												width:88,
												listeners: {'select': changeRadius}
											}),											
											{
												xtype:'tbspacer',
												width:5
											},
											{
												xtype:'tbseparator'
											},
											new Ext.Button({
												text: 'Help',
												listeners: {'click': showHelp}
											}),
											{
												xtype:'tbspacer',
												width:5
											},
											{
												xtype:'tbseparator'
											},
											new Ext.Button({
												text: 'On Mobile (Smart Phones)',
												listeners: {'click': showMobile}
											}),
											{
												xtype:'tbspacer',
												width:5
											},
											{
												xtype:'tbseparator'
											},
											signInButton,
											signOutButton
										]
									}),
								
									new Ext.BoxComponent({ // raw
										region:'center',
										id:'mylocationregion',
										height:55,
										style:'text-align:left; vertical-align:middle; padding-right:10px; font-family:Georgia; font-size:22px; color:#01669B',
										el: 'mylocation'
										//autoEl:
										//{
										//	tag: 'div',
										//	html: '<b>Surround Connect</b>'
										//}
									})
									
								]
							}
						]
					},
					// End of Header section
					// Start of Map section
					{
				        region: 'center',
				        xtype: 'panel',
				        layout: 'fit',				        
				        html: '<div id="map" style="width:100%; height:100%"></div>'
						//html: '<button onClick="alert(window.outerWidth)">Click</button>'
						//html: '<button onClick="alert(Ext.get(\'mybody\').getWidth())">Click</button>'
						
					},					
					{
						region: 'west',
						id: 'west-panel', // see Ext.getCmp() below
						title: 'Results',
						split: true,
						width: 250,
						minSize: 175,
						maxSize: 400,
						collapsible: true,
						collapsed: true,
						autoHide: true,
						margins: '0 0 0 5',
						layout: 
						{
							type: 'accordion',
							animate: true							
						},
						items: generateListPanel(),
						listeners: {
							beforecollapse : function (panel, animate)
								{
									if (map)
									{
										//setTimeout('map.panBy(new GSize(235, 0))', 1000);									
									}
								} ,
							beforeexpand : function (panel, animate)
								{
									if (map)
									{
										//setTimeout('map.panBy(new GSize(-235, 0))', 1000);
									}
								} 
						}
					}
				]
			}
	    )
		
		function showMobile(button, event) {
			mobileWin.show();
		}	
		
		function showHelp(button, event) {
			helpWin.show();
		}
		
		function showSignin(button, event) {
			signinWin.show();
		}
		
		welcomeWin = new Ext.Window({
            applyTo:'welcome-win',
            layout:'fit',
            width:370,
            height:125,
            closeAction:'hide',
            plain: true,
            contentEl:'welcome-content',
			bodyStyle:'font-size:16px; text-align:center; color:#003366; padding:8px'
        });
		
		mobileWin = new Ext.Window({
            applyTo:'mobile-win',
            layout:'fit',
            width:420,
            height:180,
            closeAction:'hide',
            plain: false,
            contentEl:'mobile-content',
			bodyStyle:'font-size:14px; text-align:center; color:#003366; padding:8px'
        });
        
        helpWin = new Ext.Window({
            applyTo:'help-win',
            layout:'fit',
            width:550,
            height:490,
            closeAction:'hide',
            plain: false,
            contentEl:'help-content',
			bodyStyle:'font-size:14px; text-align:left; color:#003366; padding:8px'
        });
        
        signinWin = new Ext.Window({
            modal:true,
            applyTo:'signin-win',	
            layout:'fit',
            width:420,
            height:280,
            closeAction:'hide',
            plain: true,
            contentEl:'signin-content',
			bodyStyle:'font-size:14px; text-align:left; color:#336699; padding:8px 15px 15px 15px'
        });
        
		initializeGMap();
		
		onSNReady();
	}	
);
