var currentOutagesDataStore;
var municipalityNameDataStore;
var regionDataStore;
var mmStore;

var regionOutageTable;
var currentOutagesTable;
var regionTableColumnModel;
var showRegionTableLink;
var selectOutageTypeControl;


var loadingIndicator;
var datastoreLoadingStateMap;
var muniNameCombo;
var regionNameCombo;
var timePeriodCombo;
var tabbedPanel; // tabpanel
// and tabs inside tabpanel (next 3 panels)
var restoredTitlePanel
var plannedTitlePanel
var currentTitlePanel
var previousTab

var contentWithMediaMessages;
var contentNoMediaMessages;
var regionMuniTimeComboPanel;
var glossaryAnchor;

var TABLE_WIDTH = 750;
var LABEL_WIDTH_L = 400;
var LABEL_WIDTH_R = 300;
var LABEL_WIDTH = 350;
var linkToOutageMap = '<div align="right"><a href="orsMapView.jsp">View Outage Map</a></div>';

var aJaxHttp = getXMLHttpObject();

function pageUnavailable(a,b,c,d){
	 window.location = contextPath + '/orsUnavailable.jsp';
}

/**
 * Called whenever a control is changed that changes the content of the outages details table
 */
function refreshCurrentOutageTable( outageType, region, regionName ){
	var numDays = timePeriodCombo.getValue();
			
	// default numDays to 14 days
	if( numDays == null || numDays == 'undefined' || numDays.length < 1 ){
	  numDays = 14;
	}
	
	// if no region passed as parameter, then default to row selected from 
	// region list
	if( region == null ){
		region = regionNameCombo.getValue();
	}
	
	if( regionName == null ){ // set a default value
	  regionName = region;
	}
		
	if( outageType == null ){  // assign a default value if none passed as parameter
		outageType = 'current';
	}
		
	var tableHeader = 'Outages for <i>' + regionName + '</i>';
	var changeRegionLink = '[ <a href="javascript:showRegionView(\'' +  outageType +'\')">Return to Region List</a> ]'
	var tabText = '';
	
	if (outageType=='current'){
		tableHeader = 'Current ' + tableHeader;
		currentOutagesTable.getColumnModel().setColumnHeader(2, "Est. Time ON");		
		// this is the label where the 'change region' link is placed
		regionMuniTimeComboPanel.getComponent( 0 ).getComponent( 3 ).body.update(changeRegionLink);
		
	}else if (outageType=='planned'){
	    numDays = 14;  // planned outages tab always defaults to the next 14 days
		tableHeader = 'Planned ' + tableHeader;
		currentOutagesTable.getColumnModel().setColumnHeader(2, "Est. Time ON");		
		// this is the label where the 'change region' link is placed
		regionMuniTimeComboPanel.getComponent( 0 ).getComponent( 3 ).body.update(changeRegionLink);
		
	}else if (outageType=='restored'){
		tableHeader = 'Restored ' + tableHeader;
		currentOutagesTable.getColumnModel().setColumnHeader(2, "Restore Time");

		if (numDays == 1){		
			tabText = '<br/>Restored power outages in the past 24 hours: <br/><br/>';
		}else{				
			tabText = '<br/>Restored power outages in the past ' + numDays + ' days: <br/><br/>';	
		}
		// this is the header (title) label - updated to reflect changes made to the 
		// time period combo box
		restoredTitlePanel.getComponent( 0 ).body.update(tabText);
		// this is the label where the 'change region' link is placed
		regionMuniTimeComboPanel.getComponent( 0 ).getComponent( 3 ).body.update(changeRegionLink);
	} 	

	timePeriodCombo.setValue( numDays );
	currentOutagesTable.setTitle(tableHeader);
	currentOutagesDataStore.load({params: {'type': outageType, 'region': region, 'numDays': numDays}}) ;
}

/**
 *  Called when selecting a menu item from the drop-down (combo) box
 */
function loadOutageTableForRegion( region ){
	loadComboBoxesForRegion( region );
	
	regionOutageTable.hide();    
	currentOutagesTable.show();		
	Ext.get('tableComponentContainer').fadeIn();
	refreshComboBoxes( tabbedPanel.getActiveTab().getItemId() );
}
 

/**
 * Called when you double click on a row in the region table
 */
function currentRegionViewRowDoubleClickHandler(grid, row, event){
	
	var record = grid.getSelectionModel().getSelected();
	
	if (typeof record != 'undefined'){
		// load the appropriate municipality names
		var region = record.get('internalName');
		loadOutageTableForRegion( region );
	}

	refreshCurrentOutageTable( 'current' );
}

/**
 * Called when you double click on a row in the RESTORED region table
 */
function restoredRegionViewRowDoubleClickHandler(grid, row, event){
	
	var record = grid.getSelectionModel().getSelected();
	
	if (typeof record != 'undefined'){
		// load the appropriate municipality names
		var region = record.get('internalName');
		loadOutageTableForRegion( region );
	}

	refreshCurrentOutageTable( 'restored' );
}

/**
 * Called when you double click on a row in the PLANNED region table
 */
function plannedRegionViewRowDoubleClickHandler(grid, row, event){
	
	var record = grid.getSelectionModel().getSelected();
	
	if (typeof record != 'undefined'){
		// load the appropriate municipality names
		var region = record.get('internalName');
		loadOutageTableForRegion( region );
	}

	refreshCurrentOutageTable( 'planned' );
}

function loadComboBoxesForRegion( region ){
//		regionNameCombo.clear();
		regionNameCombo.setValue( region );
		muniNameCombo.clearValue();
		municipalityNameDataStore.load({params:{'type': 'muniNames', 'region': region}});
}

/**
 * Called when the municipality dropdown in the details table is changed
 */
function municipalityDropDownValidationListener(combo){

	var value = combo.getValue();
	if (value == "" || value == municipalityNameDataStore.getAt(0).get('municipality')){
		currentOutagesDataStore.clearFilter(false);	
	}else{
		currentOutagesDataStore.filter('municipality', value, true);
	}
}

/**
 * Called when the region dropdown in the details table is changed
 */
function regionDropDownValidationListener(combo, record){
	var tabSelected = tabbedPanel.getActiveTab().getItemId();
	var region = combo.getValue();
	currentOutagesTable.getSelectionModel().selectRow( combo.getId() );
	
	var regionName = record.data.region;
	
	loadOutageTableForRegion( region );
	
    if( tabSelected.indexOf( 'restored' ) != -1 ){
	    refreshCurrentOutageTable( 'restored', region, regionName );
	    
    }else if( tabSelected.indexOf( 'planned' ) != -1 ){
    	refreshCurrentOutageTable( 'planned', region, regionName );
    	
    }else{
    	refreshCurrentOutageTable( 'current', region, regionName );
    }
}

function knownMunicipalityValidator(value){
	var re = new RegExp("^" + value + "$")
	var valid = municipalityNameDataStore.find('municipality', re) != -1;
	//alert('Value: ' + value + " - " + valid);
	return valid;
}


/**
 * Cell renderes
 */
function numCustomerRenderer (value){
	if (value == 0  ||  value > 4)
		return padNumberRenderer(value);
	else	
		return padNumberRenderer('< 5');
}

/** 
 * Helper function to render (add) a link to the map view from the region 
 * list view.  Links are hardcoded for the time being.
 */
function regionViewOnMapRenderer (value){
	var tabSelected = tabbedPanel.getActiveTab().getItemId();
	if( (tabSelected.indexOf( 'restored' ) != -1)  ||  (tabSelected.indexOf( 'planned' ) != -1) ) {
		return '&nbsp';
	}	
	else {
		return textWrapRenderer( ' <a href="orsMapView.jsp?region=' + convertRegion(value) +  '">View on Map</a>' );
	}
}

/** 
 * Helper function to convert the region name to query string  
 */

function  convertRegion(region) {
	switch (region)
	{
	case "Central Interior":
		return "Central";
		break;
	case "Lower Mainland / Sunshine Coast":
		return "LowerMainland";
		break;
	case "Northern":
		return "Northern";
		break;	
	case "Okanagan / Kootenay":
		return "Okanagan";
		break;	
	case "Thompson / Shuswap":
		return "Thompson";
		break;	
	case "Vancouver Island, North":
		return "IslandNorth";
		break;	
	case "Vancouver Island, South":
		return "IslandSouth";
		break;	
	default:
		return '';
	}
}	

/** 
 * Helper function to add a link to view a specific outage on the map view from
 * the outages table view.
 */
function muniViewOnMapRenderer(value, metadata, record ){ 
	// we do not need 'metadata' but it is there to be able to obtain 'record'
	return textWrapRenderer( value ) + viewOnMapWrapDynamicRenderer( record.data.gisId  );
}


function viewOnMapWrapDynamicRenderer(id){
  var htmlToReturn = '';
  var reg = regionNameCombo.getValue();
  
  if( id != null && id != 'undefined' && id.length > 0 ){
    //htmlToReturn = textWrapRenderer( ' <a href="orsMapView.jsp?outageid=' + id + '&region=' + reg + '">View on Map</a>' );
    htmlToReturn = textWrapRenderer( ' <a href="orsMapView.jsp?outageid=' + id + '">View on Map</a>' );
  }
  
  return htmlToReturn;
}

function textWrapRenderer(s){
	return '<div style="white-space: normal">' + s + '</div>';
}

function causesRenderer (value){

	if (value.indexOf('*')==0){
		return textWrapRenderer('<b>Planned Outage</b><br><a href="javascript:popUpWindow(\'popup/glossary_pop.htm#plannedoutage\', 50, 50, 550, 400);">' + Ext.util.Format.substr(value,1, value.length) + '</a>');	
	}else{
		glossaryAnchor = value.toLowerCase().split(' ').join('');
		return textWrapRenderer('<a href="javascript:popUpWindow(\'popup/glossary_pop.htm#'+ glossaryAnchor +'\', 50, 50, 550, 400);">' + value + '</a>');
	}
}

function padNumberRenderer(s){
	return '<span style="padding-right: 3ex">' + s + '</span>';
}

/**
 * Switches from outage details table to region view
 */
function showRegionView( tabName ){
	currentOutagesTable.hide();			
	//restoredTitlePanel.getComponent( 0 ).body.update( '<h2>Restored Outages (past 14 days)</h2> <p class="smalltext">Last Updated: N/A');
	timePeriodCombo.setValue( 14 );
	regionOutageTable.show();	
	Ext.get('tableComponentContainer').fadeIn();
   	currentRegionDataStore.reload();
    refreshDataStores();
}


/**
 * Helper function to get the value of a group of radio buttons
 */ 
function getRadioValue(name) {
  
    var radios = document.getElementsByTagName('input');

    for (var i=0; i<radios.length; i++) {
	    var input = radios[ i ]; 
	    
        if (input.type == 'radio' && input.name == name && input.checked) {        
            return input.value;
        }
    }
    return null;
}

/**
 * Helper functions called by the data stores. Shows the loading indicator
 * as long as at least one store is loading!
 */ 

function currentOutagesOnLoadHandler(ds){
	municipalityDropDownValidationListener(muniNameCombo);
	currentOutagesTable.getView().refresh(true);
}

function mediaMessageChangeHandler(ds){
	//mediaMessageBox.setVisible(ds.getCount() > 0);
	contentWithMediaMessages.setVisible(ds.getCount() > 0);
	contentNoMediaMessages.setVisible(ds.getCount() == 0);
} 

function loadingStarted(storename){
  	loadingIndicator.show();
	datastoreLoadingStateMap[storename]=true;
}

function loadingEnded(storename){
	datastoreLoadingStateMap[storename]=false;
	for (var i in datastoreLoadingStateMap)
		if (datastoreLoadingStateMap[i] == true)
			return;
  	loadingIndicator.hide();
  	
	if (aJaxHttp != null) {
		var timestamp = new Date();
		var url = contextPath + "/tableOutageData?time=true";
		aJaxHttp.open('POST',url,true);
		aJaxHttp.onreadystatechange = function() {checkState();};
		aJaxHttp.send(null);
	}
}

function getXMLHttpObject() {
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
	}
	return xmlHttp;
}
	
function checkState() {
	if (aJaxHttp.readyState == 4) {
		var resp = aJaxHttp.responseText;
		var cacheUpdatedTime = resp;
		
		var tabSelected = tabbedPanel.getActiveTab().getItemId();
		var numDays = timePeriodCombo.getValue();
		var tabText = "";
		
		if( tabSelected == 'restored' || tabSelected == 'restoredTitlePanel' ){
			if (numDays == 1){		
				tabText = '<br/>Restored power outages in the past 24 hours: <br/><br/>';
			}else{
				tabText = '<br/>Restored power outages in the past ' + numDays + ' days: <br/><br/>';	
			}
			restoredTitlePanel.getComponent( 0 ).body.update(tabText);
		}else if( tabSelected == 'planned' || tabSelected == 'plannedTitlePanel' ){			
			tabText = '<br/>Planned maintenance outages in the next 14 days: <br/><br/>';
			plannedTitlePanel.getComponent( 0 ).body.update(tabText);
		}else{				
			tabText = '<br/>Currently reported power outages: <br/><br/>';
			currentTitlePanel.getComponent( 0 ).body.update(tabText);
		}
		Ext.get('LastUpdate').update('Last Updated: ' + cacheUpdatedTime );
	}
}

/**
 * Refreshes outage detail view and media messages
 */ 
function refreshDataStores(){	
	var tabSelected = tabbedPanel.getActiveTab().getItemId();
	
	if (currentOutagesTable.isVisible()){
/*		if( tabSelected == 'restored' ){	  
			currentOutagesDataStore.reload();
		}else if( tabSelected == 'planned' ){
			currentOutagesDataStore.reload();
		}else{
			currentOutagesDataStore.reload();
		}
*/														
	}else{		
	    regionOutageTable.removeListener( 'rowclick', restoredRegionViewRowDoubleClickHandler );
	    regionOutageTable.removeListener( 'rowclick', plannedRegionViewRowDoubleClickHandler );
	    regionOutageTable.removeListener( 'rowclick', currentRegionViewRowDoubleClickHandler );	    
	    
		if( tabSelected == 'restored' || tabSelected == 'restoredTitlePanel' ){
		    regionOutageTable.addListener('rowclick', restoredRegionViewRowDoubleClickHandler );	  
			regionOutageTable.reconfigure( restoredRegionDataStore, regionTableColumnModel );
			regionOutageTable.getColumnModel().setColumnHeader(1, "# Restored Outages");
			restoredRegionDataStore.reload();
			
		}else if( tabSelected == 'planned' || tabSelected == 'plannedTitlePanel' ){
		    regionOutageTable.addListener('rowclick', plannedRegionViewRowDoubleClickHandler);
			regionOutageTable.reconfigure( plannedRegionDataStore, regionTableColumnModel );
			regionOutageTable.getColumnModel().setColumnHeader(1, "# Planned Outages");
			plannedRegionDataStore.reload();
			
		}else{		
		    regionOutageTable.addListener('rowclick', currentRegionViewRowDoubleClickHandler);
			regionOutageTable.reconfigure( currentRegionDataStore, regionTableColumnModel );
			regionOutageTable.getColumnModel().setColumnHeader(1, "# Outages");
			currentRegionDataStore.reload();
		}
	}
	refreshComboBoxes( tabSelected );
		
	mmStore.reload();
}

/**
 * Refreshes outage detail view and media messages
 */ 
function refreshDataStoresTask(){
	var tabSelected = tabbedPanel.getActiveTab().getItemId();
	
	if (currentOutagesTable.isVisible()){
		if( tabSelected == 'restored' ){	  
			currentOutagesDataStore.reload();
		}else if( tabSelected == 'planned' ){
			currentOutagesDataStore.reload();
		}else{
			currentOutagesDataStore.reload();
		}
													
	}else{		
	    regionOutageTable.removeListener( 'rowclick', restoredRegionViewRowDoubleClickHandler );
	    regionOutageTable.removeListener( 'rowclick', plannedRegionViewRowDoubleClickHandler );
	    regionOutageTable.removeListener( 'rowclick', currentRegionViewRowDoubleClickHandler );	    
	    
		if( tabSelected == 'restored' || tabSelected == 'restoredTitlePanel' ){
		    regionOutageTable.addListener('rowclick', restoredRegionViewRowDoubleClickHandler );	  
			regionOutageTable.reconfigure( restoredRegionDataStore, regionTableColumnModel );
			regionOutageTable.getColumnModel().setColumnHeader(1, "# Restored Outages");
			restoredRegionDataStore.reload();
			
		}else if( tabSelected == 'planned' || tabSelected == 'plannedTitlePanel' ){
		    regionOutageTable.addListener('rowclick', plannedRegionViewRowDoubleClickHandler);
			regionOutageTable.reconfigure( plannedRegionDataStore, regionTableColumnModel );
			regionOutageTable.getColumnModel().setColumnHeader(1, "# Planned Outages");
			plannedRegionDataStore.reload();
			
		}else{		
		    regionOutageTable.addListener('rowclick', currentRegionViewRowDoubleClickHandler);
			regionOutageTable.reconfigure( currentRegionDataStore, regionTableColumnModel );
			regionOutageTable.getColumnModel().setColumnHeader(1, "# Outages");
			currentRegionDataStore.reload();
		}
	}
	refreshComboBoxes( tabSelected );
		
	mmStore.reload();
}

//------------------------------------------------------------
//--- Determines if we should show the time period         ---
//--- combo box or not                                     ---
//------------------------------------------------------------

function refreshComboBoxes( tabSelected ){
	// show this panel is current outages table is visible.
	// hide if in region list view
	if (currentOutagesTable.isVisible()){
	    regionMuniTimeComboPanel.show();

		// we only show the time period combo box if the restored tab is active	    		
		if( tabSelected.indexOf( 'restored' ) != -1 ){
	        regionMuniTimeComboPanel.findById('timePeriodCombo').show();
	        regionMuniTimeComboPanel.findById('timePeriodLabel').show();
	        		  
        }else{
	        regionMuniTimeComboPanel.findById('timePeriodCombo').hide();
	        regionMuniTimeComboPanel.findById('timePeriodLabel').hide();	
        }
	}else{ // hide if in region list view
	    regionMuniTimeComboPanel.hide();
	}
}

//------------------------------------------------------------
//---    Figure out if user is logged in or not            ---
//------------------------------------------------------------
//PRD https://wwwa1.bchydro.com/emcweb/LoginServiceStatusExternal.do?callback={callback}
	var checkUserLogin = function(){
	  	$().json('http://w3tex.bchydro.com:8793/emcweb/LoginServiceStatusExternal.do?callback={callback}', 
	  			 function(json) {
	  			 	var jsonResponse = eval(json);
	
					if(jsonResponse.user.appOnline == 'true'){
			
					     if (jsonResponse.user.loggedIn == 'true')
							displayLoginMsg(false);
					     else
					       displayLoginMsg(true);
					}
				});
	};

function displayLoginMsg( displayable ){
  var htmlToDisplay = '';
  
  if( displayable ){
	//PRD  
    //htmlToDisplay = '<a href="https://wwwa1.bchydro.com/emcweb/LoginPage.do">Log in</a> to Your Account to view your outages';
    //TEST
    htmlToDisplay = '<a href="http://w3tex.bchydro.com:8793/emcweb/LoginPage.do">Log in</a> to Your Account to view your outages';
  }else{
    htmlToDisplay = '';
  }

  Ext.get('loggedInMessage').innerHtml = htmlToDisplay;
}

/**
 * Page Initialization
 */

Ext.onReady(function() {
	/* ---------------------------------------
	 *   Static Dom Element initializations  
	 * ---------------------------------------*/
	contentWithMediaMessages = Ext.get('pageWithMediaMessages');
	contentNoMediaMessages = Ext.get('pageNoMediaMessages');
	//If Ext cannot get the DIV, that means the page cannot be loaded --> redirect to Unavailable page
	if (contentWithMediaMessages == null){
		window.location = contextPath + '/orsUnavailable.jsp';
	}
	if (contentNoMediaMessages == null) {
		window.location = contextPath + '/orsUnavailable.jsp';
	}	
	contentWithMediaMessages.setVisibilityMode(Ext.Element.DISPLAY);
	contentNoMediaMessages.setVisibilityMode(Ext.Element.DISPLAY);


  	loadingIndicator = Ext.get('loadingIndicator');
   	loadingIndicator.setVisibilityMode(Ext.Element.DISPLAY);
  	loadingIndicator.hide();

	
	datastoreLoadingStateMap = new Array();
	datastoreLoadingStateMap["regions"]=false;
	datastoreLoadingStateMap["mediamsg"]=false;
	datastoreLoadingStateMap["outages"]=false;
	

	municipalityNameDataStore = new Ext.data.JsonStore({
    	url: contextPath + '/tableOutageData',
		method: 'POST',
	    root: 'municipalities',
    	fields: ['municipality']
	});

	currentRegionDataStore = new Ext.data.JsonStore({
    	url: contextPath + '/tableOutageData',
		method: 'POST',
	    root: 'regions',
    	fields: ['internalName', 'region', 'numOutages', 'numCustOut'],
    	baseParams:{'type': 'regionList', 'tab': 'current' }
	});


	restoredRegionDataStore = new Ext.data.JsonStore({
    	url: contextPath + '/tableOutageData',
		method: 'POST',
	    root: 'regions',
    	fields: ['internalName', 'region', 'numOutages', 'numCustOut'],
    	baseParams:{'type': 'regionList', 'tab': 'restored'}
	});


	plannedRegionDataStore = new Ext.data.JsonStore({
    	url: contextPath + '/tableOutageData',
		method: 'POST',
	    root: 'regions',
    	fields: ['internalName', 'region', 'numOutages', 'numCustOut'],
    	baseParams:{'type': 'regionList', 'tab': 'planned' }
	});

		
	//  The "Loading" Indicator  
	currentRegionDataStore.addListener('beforeload', function(){loadingStarted('regions');});
	currentRegionDataStore.addListener('load', function(){loadingEnded('regions');});
	//currentRegionDataStore.addListener('loadexception', pageUnavailable);
		
	
	/**
	 * The Region Table component
	 */
  	regionTableColumnModel = new Ext.grid.ColumnModel([
		{id:"region", header: "Region",  sortable: true, dataIndex: 'region'},
		{header: "# Outages",  sortable: true, dataIndex: 'numOutages', align: 'right', renderer: padNumberRenderer},
		{header: "# Customers Out",  sortable: true, dataIndex: 'numCustOut', align: 'right', renderer: numCustomerRenderer},
		{header: "", width: 40, sortable: false, dataIndex: 'region', align: 'left', renderer: regionViewOnMapRenderer}
	]);



	regionOutageTable = new Ext.grid.GridPanel({
	    el: 'regionTable',
	    ds: currentRegionDataStore,
	    cm: regionTableColumnModel,
	    viewConfig: {forceFit:true, autoFill: true}, // used to have forceFit
	    autoExpandColumn: 'region',
    	sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
	    width:TABLE_WIDTH,
	    height: 350,
   	    stripeRows: true,
   	    border: false,
	    enableHdMenu: false,
	    header: false,
	    plain: true,
	    frame: false
	    //title: 'Outages Grouped By Region (click on a row to show details)'
		// ctCls: 'orsTableMinimize'
	});
	regionOutageTable.addListener('rowclick', currentRegionViewRowDoubleClickHandler);
	regionOutageTable.render();
	regionOutageTable.getView().refresh(true);


	/**
	 * The Combo Box Control for Region Names
	 */ 
	timePeriodCombo = new Ext.form.ComboBox({
	    id: 'timePeriodCombo',
	    fieldLabel: 'Time Period',
	    listWidth: 150,
	    minListWidth: 150,
    	store: [ [1, 'Past 24 hours'] ,[3, 'Past 3 days'] ,[14, 'Past 14 days'] ],
    	displayField:'name',
       	mode: 'local',
    	editable:false,
    	forceSelection:true,
    	selectOnFocus:true, 
    	triggerAction: 'all',
    	typeAhead: true
	});
	
	timePeriodCombo.addListener('select', function(){refreshCurrentOutageTable('restored');});

	/**
	 * The Combo Box Control for Region Names
	 */
	regionNameCombo = new Ext.form.ComboBox({
	    fieldLabel: 'Region',
	    emptyText:'- Show All Regions -',
	    listWidth: 300,
	    minListWidth: 250,
    	store: currentRegionDataStore,
    	displayField:'region',
    	valueField: 'internalName',
       	mode: 'local',
    	editable:false,
    	forceSelection:true,
    	selectOnFocus:true, 
    	triggerAction: 'all',
    	typeAhead: true,
    	validator: knownMunicipalityValidator
	});
	
	// change tho "valid" if you need the type ahead
	regionNameCombo.addListener('select', regionDropDownValidationListener );
	

	/**
	 * The Combo Box Control for Municipality Names
	 */
	
	muniNameCombo = new Ext.form.ComboBox({
    	store: municipalityNameDataStore,
    	displayField:'municipality',
       	mode: 'local',
    	emptyText:'- Show All Municipalities -',
    	editable:false,
    	forceSelection:true,
    	selectOnFocus:true, 
    	triggerAction: 'all',
    	typeAhead: true,
    	validator: knownMunicipalityValidator
	});
	// change tho "valid" if you need the type ahead
	muniNameCombo.addListener('select', municipalityDropDownValidationListener);

	
	/**
	 * The Outage Details Table
 	 */
	currentOutagesDataStore = new Ext.data.JsonStore({
    	url: contextPath + '/tableOutageData',
		method: 'POST',
	    root: 'outages',
    	fields: ['id', 
    			 'gisId',
    			 'municipality', 
    			 {name: 'dateOff', type: 'date', dateformat: 'Y/m/d H:i' },
    			 {name: 'etr' ,    type: 'date', dateformat: 'Y/m/d H:i' },
    			 'area', 
    			 'numCustomers', 
    			 'cause', 
    			 {name: 'lastUpdated', type: 'date', dateformat: 'Y/m/d H:i' }
    			 ]
	});
	
	currentOutagesDataStore.setDefaultSort('municipality', 'asc');
	// The "Loading" Indicator  
	currentOutagesDataStore.addListener('beforeload', function(){loadingStarted('outages');});
	currentOutagesDataStore.addListener('load', function(){loadingEnded('outages');});
	currentOutagesDataStore.addListener('load', currentOutagesOnLoadHandler);
	//currentOutagesDataStore.addListener('loadexception', pageUnavailable);

  	var currentOutagesColumnModel = new Ext.grid.ColumnModel([
		{id:"municipality",  header: "Municipality",  sortable: true, dataIndex: 'municipality', renderer: textWrapRenderer},
		{header: "Date Off", sortable: true, dataIndex: 'dateOff', align:'center', renderer: Ext.util.Format.dateRenderer('M d<br>H:i')},
		{header: "Est. Time On", sortable: true, dataIndex: 'etr' , align:'center', renderer: Ext.util.Format.dateRenderer('M d<br>H:i')},
		{header: "Area", sortable: true, dataIndex: 'area', id:'area', renderer: muniViewOnMapRenderer },
		{header: "# Out", width:60, sortable: true, align:'center', dataIndex: 'numCustomers', renderer: numCustomerRenderer},
		{header: "Cause", sortable: true, dataIndex: 'cause', renderer: causesRenderer},
		{header: "Last Updated", sortable: true, dataIndex: 'lastUpdated', align:'center', renderer: Ext.util.Format.dateRenderer('M d<br>H:i')}
	]);
	

	
	currentOutagesTable = new Ext.grid.GridPanel({
	    el: 'outagesTable',
	    ds: currentOutagesDataStore,
	    cm: currentOutagesColumnModel,
	    viewConfig: {forceFit: true, autoFill: true},
	    autoExpandColumn: 'area',
    	sm: new Ext.grid.RowSelectionModel({singleSelect:false}),
	    width: TABLE_WIDTH,
	    height: 400,
	    enableHdMenu: false,
	    plain: true,
	    stripeRows: true,
	    border: false,
        header: true
	});
	
	currentOutagesTable.hide();
	currentOutagesTable.render();
	currentOutagesTable.getView().refresh(true);
		
	//------------------------------------------------------------
    //---          Initialize the media messages               ---
    //------------------------------------------------------------
      
   
   	var mmTemplate = new Ext.XTemplate(
    	'<tpl for=".">' +
	        '<div class="mmsg">' +
			'<div class="mmdate">{date}</div>' +
			'<div class="mmarea">{area}</div>' +
			'<div class="mmtext">{message}</div>' +
			'</div>' +
	    '</tpl>' );
  
  
	mmStore = new Ext.data.JsonStore({
    	url: contextPath + '/mediaMessages',
	    root: 'mediaMessages',
    	fields: ['date', 'area', 'message', 'url']
	});
	
	// The "Loading" Indicator  
	mmStore.addListener('beforeload', function(){loadingStarted('mediamsg');});
	mmStore.addListener('load', function(){loadingEnded('mediamsg');});
	mmStore.addListener('load', mediaMessageChangeHandler);
//	mmStore.load();
      
	    
  	var mmView = new Ext.DataView({
  		applyTo: 'mediaMessages',
        store: mmStore,
        tpl: mmTemplate,
        itemSelector: 'div.mmsg',
        loadingText: 'Loading Outage Messages',
        emptyText: '<div class="mmarea">No Messages to Report</div>'
    })
  
  	mmView.render();

//	restoredPeriodControl.hide();
    
  
  	//------------------------------------------------------------
    //---    Figure out if user is logged in or not            ---
    //------------------------------------------------------------   
    checkUserLogin();

  	//------------------------------------------------------------
    //---                Periodic Updater Task                 ---
    //------------------------------------------------------------   
	var task = {
	    run: refreshDataStoresTask,
	    interval: 1000 * 60 * 10 //10 minutes
	}
	Ext.TaskMgr.start(task);

  	//------------------------------------------------------------
    //---    			Panel Definitions             		   ---
    //------------------------------------------------------------   
    
    // Current Outages Region List View
    currentTitlePanel = new Ext.Panel({
        id: 'currentTitlePanel',
 	    title: 'Current Outages',
 	    listeners:{ activate : function(){refreshDataStores(); refreshCurrentOutageTable( 'current' ); } },
    	header: false,
    	plain: true,
    	layout: 'column',
    	width: 750,
    	frame: false,
    	hideBorders: true,
    	items:  [{
    				html: '<br/>Currently reported power outages: <br/><br/>',
    				type: 'Label',
    				width: LABEL_WIDTH_L
    			},{
    				html: '<div id="loggedInMessage" style="padding: 10px;"><!--<a href="#">Log in</a> to Your Account to view your outages--></div>',
    				type: 'Label',
    				width: LABEL_WIDTH_R
    			}]
    });

    // Restored Outages Region List View    
    restoredTitlePanel = new Ext.Panel({
    	id: 'restoredTitlePanel',
 	    title: 'Restored Outages',
 	    listeners:{ activate : function(){refreshDataStores(); refreshCurrentOutageTable( 'restored' ); } },
    	header: false,
    	plain: true,
    	layout: 'column',
    	width: 750,
    	frame: false,
    	hideBorders: true,
    	items:  [{
    				html: '<br/>Restored power outages in the past 14 days: <br/><br/>',
    				type: 'Label',
    				width: LABEL_WIDTH_L
    			},{
    				html: '<div id="loggedInMessage" style="padding: 10px;"><!--<a href="#">Log in</a> to Your Account to view your outages--></div>',
    				type: 'Label',
    				width: LABEL_WIDTH_R
    			}]
    });
    
    // Planned Outages Region List View
    plannedTitlePanel = new Ext.Panel({
    	id: 'plannedTitlePanel',
 	    title: 'Planned Outages',
 	    listeners:{ activate : function(){refreshDataStores(); refreshCurrentOutageTable( 'planned' ); } },
    	header: false,
    	plain: true,
    	layout: 'column',
    	width: 750,
    	frame: false,
    	hideBorders: true,
    	items:  [{
    				html: '<br/>Planned maintenance outages in the next 14 days: <br/><br/>',
    				type: 'Label',
    				width: LABEL_WIDTH_L
    			},{
    				html: '<div id="loggedInMessage" style="padding: 10px;"><!--<a href="#">Log in</a> to Your Account to view your outages--></div>',
    				type: 'Label',
    				width: LABEL_WIDTH_R
    			}]
    });
    
    // This panel contains the region and municipality combo boxes as well 
    // as the time period combo box.
    // The first two always get shown when selecting outage grid view (in any tab)
    // the time period combo box only gets shown if displaying outage grid in 
    // restored outages tab
    regionMuniTimeComboPanel = new Ext.FormPanel({
    	id: 'regionMuniTimeComboPanel',
    	renderTo: 'regionMuniTimeComboPanel',
    	header: false,
    	layout: 'column',
    	border: false,
    	width: 750,
    	frame: false,
    	hideBorders: true,
		defaults:{autoHeight: true, 
				  labelWidth: 150, bodyStyle:'padding:5px',
		  		  hideBorders: true },
    	items: [{
   		                layout:'form',
   		                width: LABEL_WIDTH,
   		                defaults: { frame: false, hideBorders: true },
   		                items: [{
			                    	html: 'Region:',
			                    	type: 'Label'
			                    },{
			                    	type: 'ComboBox',
			                    	fieldLabel: 'Region',
			                    	width: 250,		
			                    	height: 22,	                    	
			                    	items: [regionNameCombo]
		                    	},{
			                    	html: '<br/>',
			                    	type: 'Label'
		                    	},{
			                    	html: '<br/>',
			                    	type: 'Label'
			                    }]
				    },{
   		                layout:'form',
   		                width: LABEL_WIDTH,
   		                items: [{
			                    	html: 'Municipality:',
			                    	type: 'Label'
			                    },{
			                    	fieldLabel: 'Muni',
			                    	type: 'ComboBox',
			                    	width: 200,
			                    	height: 22,
			                    	items: [muniNameCombo]
			                    },{
			                    	html: 'Time Period:',
			                    	type: 'Label',
			                    	id: 'timePeriodLabel'
			                    },{
			                    	fieldLabel: 'timePeriodCombo',
			                    	type: 'ComboBox',
			                    	width: 200,
			                    	height: 22,
			                    	items: [timePeriodCombo]
			                    }]
				    }]
    });
    
    
  	//------------------------------------------------------------
    //---                Initialize Tab Panel                  ---
    //------------------------------------------------------------   
    tabbedPanel = new Ext.TabPanel({
            renderTo: 'tabs',
            width: TABLE_WIDTH,
            plain:true,
            header: false,
            border: false,
            minTabWidth: 150,
            tabWidth: 175,
            deferredRender: false,
            defaults:{autoHeight: true, hideBorders: true},
            frame: false,
            
            listeners: {render: function(tabPanel){
					
					tabPanel.strip.on('click',function(e){
						var t = this.findTargets(e);
						//console.log (['stripTab click',this.activeTab, t.item,e,'---',t.item == this.activeTab]);
						if(t && !t.close && t.item && t.item == this.activeTab){
							//console.log (['yo', this.activeTab.id, previousTab ]);
							if (this.activeTab.id == previousTab) {
								if( this.activeTab.id.indexOf( 'restored' ) != -1 ){
									showRegionView( 'restored' );
								}else if( this.activeTab.id.indexOf( 'planned' ) != -1 ){
									showRegionView( 'planned' );							    	
								}else{
									showRegionView( 'current' );
								}	
							}
							previousTab = this.activeTab.id;						
						}
					},tabPanel);
				},
			beforetabchange:function(tp,newTab){
			
				if (this.activeTab) {
					previousTab = this.activeTab.id
				}
			}	
			
		},

		items: [ currentTitlePanel, restoredTitlePanel, plannedTitlePanel ]
        });        
        
    tabbedPanel.activate( tabToActivateOnLoad );
    tabbedPanel.show();
});
