var loginWindow = null;
var defaultSubClient = null;
var ePacketAuthorized = false;

function displayLoginWindow(tlmID) {
   var loginFields = new Ext.form.FieldSet({
	        autoHeight: true,
            title: 'ePacket Login',
	        defaultType: 'textfield',
	        items: [{
					id: 'usernameField',
					fieldLabel: 'Username',
	                name: 'username',
	                width:100
				},{
					id: 'passwordField',
	                fieldLabel: 'Password',
	                name: 'password',
	                width:100,
	                inputType: 'password'
	            }
			]
	    });
   loginForm = new Ext.FormPanel({
	        labelAlign: 'right',
	        labelWidth: 95,
	        frame:true,
	        items: loginFields,
	        onSubmit: Ext.emptyFn,
			buttons: [{
				text: 'Login',
				type: 'submit',
				tooltip: 'Login',
				handler: function(){
                    submitLogin();
                }
			}]
	    });

    if(!loginWindow){
        loginWindow = new Ext.Window({
            closeAction:'hide',
            plain: true,
            hideBorders: true,
            modal: true,
            closable: false,
			width:300,
			height:200,
			items: loginForm
        });
		loginWindow.show();
		Ext.getCmp('usernameField').focus('',10);
	    Ext.get('passwordField').addKeyListener(Ext.EventObject.ENTER, function(){submitLogin();});

    }
    
    function submitLogin() {
        loginForm.getForm().submit(
            {
			   url:'/TLM/tlm2Control?transaction=login', 
               waitMsg:'Logging in...',
               success: successfulLogin,
               failure: failedLogin
            }
         ) 
    }
	function successfulLogin(inboundObject,inboundMessage) {
		var userJSON;
		eval("userJSON = " + inboundMessage.response.responseText);
		defaultSubClient = userJSON.defaultSubClient;
		Ext.getCmp('usernameField').setValue('');
		Ext.getCmp('passwordField').setValue('');
		loginWindow.hide();
		var roles = userJSON.roles;
		for(var prop in roles) {
			var aRole =  roles[prop];
			if (aRole.name) {
				switch(aRole.name) {
					case 'EPacket': 
						ePacketAuthorized = true;
					default:
						break;
				}
			}
		}
		if (ePacketAuthorized) {
			Ext.get('workArea').dom.innerHTML = '';
			loadFolderTree(tlmID);
			return;
		} else {
			Ext.MessageBox.alert('Unauthorized','You are unauthorized to view ePacekts.',function() {
		    	var newUrl = location.href;
			    var lastChar = newUrl.substring(newUrl.length - 1, newUrl.length);
			    if (lastChar == "#") {
			        newUrl = newUrl.substring(0,newUrl.length - 1);
			    }
			    location.href = newUrl;
			});
			return;
		}
	}
	
	function failedLogin(inboundObject,inboundMessage) {
		Ext.getCmp('usernameField').setValue('');
		Ext.getCmp('passwordField').setValue('');
		loginWindow.hide();
		Ext.MessageBox.alert('Unauthorized','You are unauthorized to view ePacekts.',function() {
	    	var newUrl = location.href;
		    var lastChar = newUrl.substring(newUrl.length - 1, newUrl.length);
		    if (lastChar == "#") {
		        newUrl = newUrl.substring(0,newUrl.length - 1);
		    }
		    location.href = newUrl;			
		});
	}
}

function logout() {
    loginWindow.show();
    var newUrl = location.href.split("?")[0];
    Ext.Ajax.request({
       url: '/TLM/tlm2Control?transaction=logout',
       success: function(){},
       failure: function(){}
    });
    var lastChar = newUrl.substring(newUrl.length - 1, newUrl.length);
    if (lastChar == "#") {
        newUrl = newUrl.substring(0,newUrl.length - 1);
    }
    location.href = newUrl;
}

function showFileNamingGuide() {
    var fileNamingGuideWindow = new Ext.Window({
        title:'File Naming Guide',
        id:'fileNamingGuideWindow',
		renderTo:Ext.getBody(),
		closeAction:'destroy',
		html: '<div class=\'x-dlg-bd\'>' + 
				'Uploaded files must adhere to a strict naming convention so the computer can know how to tag the files and where to display them. File names must be 12 characters long in the main part and end with .pdf. The 12 characters are:<br/>' + 
				'<br/>' + 
				'<div>Date in MMDDYY format</div> <br/>' + 
				'<div>Document Type:<div>min (Minutes), agd (Agenda), bil (Bills)</div></div><br/>' + 
				'<div>Meeting Type:<div>cou (Council) or boa (Board), zba (Zoning), plc (Planning)</div></div><br/>' + 
				'<div>An example of a valid filename is: 092707minzba.pdf<br /> which translates to: </div>' + 
				'<div>September 27, 2007 Zoning Minutes</div>' + 
				'<br />' + 
				'<div>For convenience, many files can be contained within a zip file. The zipped pdf files cannot be in any subdirectories. The zipped pdf files must follow the above naming convention. There is no naming convention for the zip file itself.</div>' + 
				'</div>',
		animateTarget:Ext.getBody(),
		animCollapse:true,
        plain: false,
        hideBorders: false,
		autoScroll:true,
		constrainHeader:true,
		width:600,
		height:400,
		buttonAlign: 'center',
        buttons: [{
            text: 'Close',
            handler: function(){
                        fileNamingGuideWindow.destroy();
                    }
            }

        ],
	    listeners: 
	          { hide: { fn:function()
	                {
                        fileNamingGuideWindow.destroy();
	                }
	          	}  
			  }
    });
    fileNamingGuideWindow.show();
}

function showHelpLine2() {
	Ext.MessageBox.alert('***DEBUG>','Show Help Step 1');
}

function showHelpLine3() {
	Ext.MessageBox.alert('***DEBUG>','Show Help Step 2');
}

function showHelpLine4() {
	Ext.MessageBox.alert('***DEBUG>','Show Help Step 3');
}

function showHelpLine5() {
	Ext.MessageBox.alert('***DEBUG>','Show Help Step 4');
}

function uploadFile() {
	var form = new Ext.form.BasicForm(Ext.get('uploadFileForm'),{
		fileUpload: true,
		method:'POST',
		enctype:'multipart/form-data'
	});
	form.submit({
		url:'/TLM/uploadservlet', 
		waitMsg:'Uploading Files...',
		success:uploadFileSuccess,
		failure:uploadFileFailure,
		timeout:10000,
		params:{application:'MOD',subClient:defaultSubClient}
	});
}

function uploadFileSuccess(inboundForm,inboundMessage) {
	inboundForm.reset();
	Ext.getDom('uploadField').value = '';
	var inboundJSON;
	eval("inboundJSON = " + inboundMessage.response.responseText);
	if (inboundJSON.success) {
		Ext.MessageBox.alert('Upload Success', 'File Uploaded Successfully.');
	} else {
		Ext.MessageBox.alert('Upload Error', 'There was a problem uploading the file. Please try again. If you continue to get this message, please contact the system administrator.',null);			
	}
}
function uploadFileFailure(inboundForm,inboundMessage) {
	inboundForm.reset();
	Ext.getDom('uploadField').value = '';
	var inboundJSON;
	eval("inboundJSON = " + inboundMessage.response.responseText);
		Ext.MessageBox.alert('Upload Error', 'There was a problem uploading the file. Please try again. If you continue to get this message, please contact the system administrator.',null);
}


function indexFiles() {
	Ext.MessageBox.alert('***DEBUG>','Index Files');
}

function viewFiles() {
    var fm = Ext.form, Ed = Ext.grid.GridEditor;
	var mediaRecord = Ext.data.Record.create([
		   {name: 'mediaId', 						type: 'int'},
		   {name: 'name', 							type: 'string'},
		   {name: 'description', 					type: 'string'},
//		   {name: 'mediaDateConverted', 			mapping: 'mediaDate', type: 'date'},
		   {name: 'mediaDate', 						type: 'string'},
		   {name: 'documentType', 					type: 'string'},
		   {name: 'meetingType', 					type: 'string'},
		   {name: 'url',                            type: 'string'}
	 ]);
	var mediaReader = new Ext.data.JsonReader({
		root: "tlm2JSON.mediaArray",
		id  : "mediaId"
	}, mediaRecord);

    var mediaStore = new Ext.data.Store({
		url:'/TLM/tlm2Control?transaction=getMODRecordsBySubClient', 
		reader:mediaReader
    });

    var mediaColumns = new Ext.grid.ColumnModel([
		{
           header: "Name",
           dataIndex: 'name',
           width: 176,
           align: 'center',
		   editor: new Ed(new fm.TextField({
               allowBlank: false
           }))
		   
        },{
           header: "Description",
           dataIndex: 'description',
           width: 176,
           align: 'center',
		   editor: new Ed(new fm.TextField({
               allowBlank: false
           }))
        },{
           header: "Date",
           dataIndex: 'mediaDateConverted',
           width: 90,
           align: 'center',
		   renderer: formatDate,
		   editor: new Ed(new fm.DateField({
				format: 'd-M-Y'
		   }))
        },{
           header: "Document Type",
           dataIndex: 'documentType',
           width: 120,
           align: 'center'
/* put a real combobox in here when needed
           ,editor: new Ed(new Ext.form.ComboBox({
               typeAhead: true,
               triggerAction: 'all',
               transform:'documentTypeBox',
               lazyRender:true
            }))
*/
		 },{
           header: "Meeting Type",
           dataIndex: 'meetingType',
           width: 120,
           align: 'center'
/* put a real combobox in here when needed
           ,editor: new Ed(new Ext.form.ComboBox({
               typeAhead: true,
               triggerAction: 'all',
               transform:'meetingTypeBox',
               lazyRender:true
            }))
*/
        },{
           header: "View",
           dataIndex: 'url',
           width: 45,
		   renderer : formatUrl,
           align: 'center'
        }
    ]);
	
    function formatDate(value){
        return value ? value.dateFormat('d-M-Y') : '';
    };	
	function formatUrl(value) {
		var aTitle = 'Viewer';
		var aParameter = 'resizable=yes,scrollbars=no,toolbar=no,menubar=no,width=840,height=615';
	    var returnValue = value ? '<a href="#" onclick="window.open(\'/'+value+'\',\''+aTitle+'\',\''+aParameter+'\');">[x]</a>'  : '';
		//returnValue = '<img src="/pdc/images/pdf-tiny.png" alt="*"></img>';
		return returnValue;
	}
	
   mediaColumns.defaultSortable = true;
   var mediaRowView = new Ext.grid.GridView({
        getRowClass : function(record, index){
		   var documentType = record.get('documentType');
		   var meetingType = record.get('meetingType');
		   var cssClass = '';
		   if (documentType == 'Unknown' || meetingType == 'Unknown') {
           		var cssClass = ' rowRed ';
		   }
		   return cssClass;
        }
   });

    var mediaDetailGrid = new Ext.grid.EditorGridPanel({
		view: mediaRowView,												 
        ds: mediaStore,
        cm: mediaColumns,
        enableColLock:false
    });
    var mediaDetailGridWindow = new Ext.Window({
        title:'File View',
        id:'mediaDetailGridWindow',
		renderTo:Ext.getBody(),
		closeAction:'destroy',
		items:[mediaDetailGrid],
		animateTarget:Ext.getBody(),
		animCollapse:true,
        plain: false,
        hideBorders: false,
		autoScroll:true,
		constrainHeader:true,
		layout:'fit',
		width:800,
		height:400,
		buttonAlign: 'center',
        buttons: [{
            text: 'Close',
            handler: function(){
                        mediaDetailGridWindow.destroy();
                    }
            }

        ],
	    listeners: 
	          { hide: { fn:function()
	                {
                        mediaDetailGridWindow.destroy();
	                }
	          	}  
			  }
    });
    mediaDetailGridWindow.show();
	mediaStore.load();
}
