
// do not remove, else ssl warnings shall follow

        // important! disabling shims for firefox fixes the firefox missing cursor bug
        Ext.onReady(function() {
                if (Ext.isGecko)
                {
                        Ext.useShims = false;
                }

				if ( Ext.get('status') && typeof( service_id ) != 'undefined' )
				{
					showStatusSelect( service_id );
				}

        });

        var source_container_id;
        var popup;
        var window_width = 480;
        var cache_original_id;
        var cache_current_id;
        var cache_type;

        var current_service_id;

        /* show the lookup grid - some of these params are not needed most likely */
        function showLookup( type, el )
        {
                        // set up our grid
                        var cm = getLookupColumnModel( type );
                        cm.defaultSortable = true;

                        if ( type == 'physician' || type == 'Physician' )
                        {
                                var fields = [ 'id', 'full_name', 'full_address', 'city', 'state', 'email', 'organization', 'specialty', 'Zip' ]; //{ name: 'distance', mapping: 'Zip.miles' } ];
                                var defaultSort = 'Zip';
                        }
                        else
                        {
                                var fields = [ 'id', 'full_name', 'full_address', 'city', 'state', 'email', 'organization', 'specialty' ];
                                var defaultSort = 'full_name';
                        }

                        var store = new Ext.data.Store({
                                remoteSort: true,
                        proxy: new Ext.data.HttpProxy({
                            url: root + '/addressbook/lookup'
                        }),
                        reader: new Ext.data.JsonReader({
                                        root: 'data',
                                        totalProperty: 'totalCount',
                                        fields: fields
                                }),
                                baseParams: { type: type },
                                sortInfo: { field: defaultSort, dir: 'ASC' }
                    	});

                        var grid = new Ext.imebase.GridPanel({
                                id: 'list-grid',
                                border: false,
								csv: false,
                                autoExpandColumn: 'practice',
                                cm: cm,
                        		store : store
                    });

                        grid.on('rowdblclick', function(one, two ) {
								/* get the id of our selected row */
                                var id = grid.getSelectionModel().getSelected().data.id;
                                var store = grid.getStore();

								/* find the data in the grid's data store for that id */
                                var selected = store.getAt( store.find('id', id) );

								var parent = Ext.get(el).up( 'table' );
																
								/* find all our inputs to replace their content */
                                var inputs = parent.query( 'input, textarea' );


								/* loop throug inputs and replace values with the lookup values */
                                for ( var i = 0; i < inputs.length; i++ )
                                {
                                	
                                		var name = inputs[i].name;
                                		multiple = false;
                                		if (name.indexOf('[') > 0 ) {
	                                    	var pos = name.indexOf('[') + 1;
	                                    	name = name.substring(pos, name.length - 1);
	                                    	multiple = true;
                                		}
                                		
                                		if ( multiple && inputs[i].name.indexOf( selected.json.entity_type ) < 0 ) {
                                			continue;	
                                		}
	
										/* don't update hidden fields */
										if ( inputs[i].type != 'hidden' && inputs[i].type != 'checkbox' && inputs[i].type != 'submit' && inputs[i].type != 'button' )
										{	                                        
	                                        if ( typeof selected.json[name] != 'undefined' )
	                                        {
	                                                inputs[i].value = selected.json[name];
	                                        }
	                                        else
	                                        {
	                                                inputs[i].value = '';
	                                        }
									}
                                }

								/* now update our select options */
                                var selects = parent.query( 'select' );
                                for ( var i = 0; i < selects.length; i++ )
                                {
                                	
                                	    var name = selects[i].name;
                                		multiple = false;
                                		if (name.indexOf('[') > 0 ) {
	                                    	var pos = name.indexOf('[') + 1;
	                                    	name = name.substring(pos, name.length - 1);
	                                    	multiple = true;
                                		}
                                		
                                		if ( multiple && selects[i].name.indexOf( selected.json.entity_type ) < 0 ) {
                                			continue;	
                                		}
	                                    
                                        if ( typeof selected.json[name] != 'undefined' )
                                        {
                                                for ( var j = 0; j < selects[i].options.length; j ++ )
                                                {
                                                        if ( selects[i].options[j].value == selected.json[name] )
                                                        {
                                                                selects[i].selectedIndex = j;
                                                        }
                                                }
                                        }
                                        else
                                        {
                                                selects[i].selectedIndex = 0;
                                        }
                                }
								
                                closePopup();
                                //enableSave();

                        });

                        if( popup )
                        {
                                closePopup();
                        }

                        if ( type == 'Physician' )
                        {
                                window_width = 600;
                        }

                        popup = new Ext.Window({
                                cls: 'popup',
                                items: grid,
                                layout: 'fit',
                                width: 480,
                                title: 'Select item',
                                closeAction: 'close'
                        });

                        popup.show();

                        // trigger the data store load
                   store.load( {params: { start: 0, limit: 20, sort: defaultSort, dir: 'DESC', type: type } } );

        }

        function closePopup()
        {
                popup.close();
                popup = false;
        }

        function showMsg(title, text) {
                var msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
                msgCt.alignTo(document, 't-t');
                var m = Ext.DomHelper.append(msgCt, {html:createBox(title, text)}, true);
                m.slideIn('t').pause(5).ghost("t", {remove:true});
        }

        function createBox(t, s){
                return ['<div class="msg">',
                    '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                    '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                    '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                    '</div>'].join('');
        }

        function addToAddressBook(source, type)
        {
                // we'll grab the first parent of <source> with class "service"
                // which will be our entity form
                // and push that to addToAddressBook
                // in JSONController.  There, the <type> will be used to pull out the relevant
                // data and push it into the Entity table.

				// check if we have a source form first, so that we can add the form data even if it's not saved
				if ( Ext.get(source) )
				{
	                var block = Ext.get(source).up('tr');
	                
	                // go back, until we hit the title
	                var elements = [];
	                	                
	                while ( block.prev('tr') ) {
	                	block = block.prev('tr');
	                	if ( block.query('th.title').length > 0 ) {
	                		break;
	                	}
	                	
	                	newels = block.query( 'input, select, textarea' );
	                	for( var i=0; i < newels.length; i++ ) {
	                		elements.push( newels[i] );
	                	}
	                }
	                
					var params = {};
					for( var i = 0; i < elements.length; i++ )
					{
						// only of a certain type
						var el = elements[i];
						
						// strip out our array names
						var name = el.name;
						if ( name.indexOf('[') > 0 ) {
							pos = name.indexOf('[');
							name = name.substring(pos + 1, name.length -1 );
						}
						params[ name ] = el.value;
					}
					
					// let's not be totally stupid
					if ( params['first'] == '' && params['last'] == '' && params['organization'] == '' ) {
						showMsg("Address Book", "You must enter a name or organization");
						return;
					}

				}
				// no source element, just use the id
				else
				{
					var params = { id: id };
				}

				params['entity_type'] = type;
				
				Ext.Ajax.request({
					params: params,
					method: 'post',
			        url: root + '/addressbook/save',
                       success: function(form, action) {
                                               showMsg("Address Book", "Successfully added to address book.");
                                       },
                       failure: function() {
                                               showMsg("ERROR", "Unable to add to address book.");
                                       },
                       waitMsg: "Adding..."
               });
			
        }

        function deleteEntity( id )
        {
                Ext.Msg.confirm('Delete', 'Are you sure you want to delete this entry? This cannot be undone.', function(button) {
                        if ( button == 'yes' )
                        {
                                window.location = root + 'directory/delete/' + id;
                        }
                });
        }

        function deleteExam( exam_id )
        {
                Ext.Msg.confirm('Delete', 'Are you sure you want to delete this exam? This cannot be undone.', function(button) {
                        if ( button == 'yes' )
                        {
                                window.location = root + '/service/delete-exam/' + exam_id;
                        }
                });
        }

        function getLookupColumnModel( type )
        {
                var cm;
				type = type.toLowerCase();
				
                switch ( type )
                {
                        case 'claimant':
                                cm = new Ext.grid.ColumnModel([{
                                   header: "Name",
                                           id: 'full_name',
                                   dataIndex: 'full_name'
                                },{
                                	header: "Organization",
                                	dataIndex: 'organization',
                                	id: 'organization'	
                                },{
                                   header: "Address",
                                                id: 'full_address',
                                   dataIndex: 'full_address'
                                }]);
                        break;

                        case 'attorney':
                        case 'claimantattorney':
                        case 'respondant':
                        case 'respondantattorney':
                                cm = new Ext.grid.ColumnModel([{
                                        header: 'Organization',
                                        id: 'corporate_name',
                                        dataIndex: 'corporate_name'
                                },{
                                        header: 'Name',
                                        id: 'full_name',
                                        dataIndex: 'full_name'
                                }]);

                        break;

                        case 'physician':
                                cm = new Ext.grid.ColumnModel([{
                                        header: 'Practice',
                                        dataIndex: 'corporate_name',
                                        id: 'corporate_name',
                                        width: 200
                                },{
                                        header: 'Name',
                                        dataIndex: 'full_name',
                                        id: 'full_name',
                                        width: 150
                                },{
                                        header: 'Specialty',
                                        dataIndex: 'specialty',
                                        id: 'specialty',
                                        width: 150
                                },{
                                        header: 'City',
                                        dataIndex: 'city',
                                        id: 'city',
                                        width: 150
                                },{
                                        header: 'State',
                                        dataIndex: 'state',
                                        id: 'state',
                                        width: 100
                                },{
                                        header: 'Distance',
                                        dataIndex: 'Zip',
                                        width: 150,
                                        filter: 'select',
                                        id: 'Zip',
                                        options: [
                                                        { id: '50', display_as: '50 mi' },
                                                        { id: '100', display_as: '100 mi' },
                                                        { id: '250', display_as: '250 mi' },
                                                        { id: '500', display_as: '500 mi' },
                                                        { id: 'all', display_as: 'Show all' }
                                        ],
                                        emptyText: '50 mi',
                                        renderer: function( value )
                                        {
                                                if ( value && value.miles )
                                                {
                                                        return Math.round( value.miles );
                                                }
                                                return '-';
                                        }
                                }]);
                        break;

                        case 'requestor':
                                cm = new Ext.grid.ColumnModel([{
                                        header: 'Name',
                                        id: 'full_name',
                                        dataIndex: 'full_name'
                                },{
                                	header: "Organization",
                                	id: 'organization',
                                	dataIndex: 'organization'
                                },{
                                        header: 'Email',
                                        id: 'email',
                                        dataIndex: 'email'
                                },{
                                        header: 'Address',
                                        id: 'full_address',
                                        dataIndex: 'full_address'
                                }]);
                        break;

                        default:
                                cm = new Ext.grid.ColumnModel([{
                                   header: "Name",
                                   dataIndex: 'full_name',
                                                id: 'full_name'
                                },{
                                	header: "Organization",
                                	dataIndex: 'organization',
                                	id: 'organization'	
                                },{
                                   header: "Address",
                                                id: 'full_address',
                                   dataIndex: 'full_address'
                                }]);
                        break;
                }

                return cm;

        }

        function validateShareEmail( form )
        {
        		// ghetto hack warning
        		if ( typeof( form['Physician[email]']) != 'undefined' ) {
        			var params = {
        				email: form['Physician[email]'].value, 
                        			service_id: service_id,
                        			company_name: form['Physician[corporate_name]'].value,
                        			title: form['Physician[title]'][ form['Physician[title]'].selectedIndex ].value,
                        			first_name: form['Physician[first_name]'].value,
                        			last_name: form['Physician[last_name]'].value,
                        			work_phone: form['Physician[work_phone]'].value,
                        			address: form['Physician[address]'].value,
                        			city: form['Physician[city]'].value,
                        			state: form['Physician[state]'][ form['Physician[state]'].selectedIndex ].value,
                        			zip: form['Physician[zip]'].value
        			};
        		}
        		else
        		{
        			var params = {
        				email: form['email'].value, 
                        			service_id: service_id,
                        			company_name: form['corporate_name'].value,
                        			title: form['title'][ form['title'].selectedIndex ].value,
                        			first_name: form['first_name'].value,
                        			last_name: form['last_name'].value,
                        			work_phone: form['work_phone'].value,
                        			address: form['address'].value,
                        			city: form['city'].value,
                        			state: form['state'][ form['state'].selectedIndex ].value,
                        			zip: form['zip'].value
        			};
        		}
        
                Ext.Ajax.request({
                        url : root + 'lookup/validate-share-email' ,
                        method: 'POST',
                        params: params,
                        callback: function( o, success, response )
                        {
                                var data = Ext.util.JSON.decode(response.responseText);

                                if ( ! data.success )
                                {
                                        Ext.MessageBox.alert( 'Email address not found', 'You have selected to give ' + form['email'].value + ' access to this case, however we could not find a user with this email address. If a user signs up for <b>imebase</b> with this address, this case will automatically be shared with them.');
                                }
                        }
                });
        }

        function loadHtmlIntoElement( target_container_id, html )
        {
                // check for session death:

                if( html.length < 10 )
                {
                        window.location = root;
                }
                else
                {
                        enableSave();

                        var container = Ext.get(target_container_id);
                        container.update(html);


                        // dress up edit_box
                        if( target_container_id == 'edit_box' )
                        {
                                container.setStyle('class', 'loaded');
                        }

                        decorateFields();
                }
        }

        Ext.grid.ColumnModel.defaultRenderer = function(value) {
                if ( value == 0 || value == '' )
                {
                        return '-';
                }
                else
                {
                        return value;
                }
        }

		function showStatusSelect( service_id )
		{
			var statusForm = new Ext.form.BasicForm('status_form');
			
			var converted = new Ext.form.ComboBox({
			    typeAhead: true,
			    triggerAction: 'all',
			    transform:'status_id',
			    forceSelection:true,
				width: 250,
				disabled: Ext.getDom('status_id').disabled
			});
		

			converted.on('select', function(combo, record, index) {
				Ext.Ajax.request({
					url: root + '/service/save',
					method: 'post',
					params: {
						id: service_id,
						status_id: combo.getValue()
					},
					success: function() {
						showMsg('Success', 'Status has been updated');
					}
				});
			});
		}
		
		/* have the user select a type to create a new service */
function newService()
{
	var store = new Ext.data.JsonStore({
		url: root + 'service/get-case-types',
		fields: [ 'id', 'service_type_id', 'display_as' ]
	});
	
	store.load();
	
	var win = new Ext.Window({
		title: 'Please select a case type',
		modal: true,
		width: 360,
		items: [{
			xtype: 'form',
			bodyStyle: 'padding: 10px',
			items: [{
				xtype: 'combo',
				id: 'type-combo',
				fieldLabel: 'Case type',
				name: 'case_type',
				store: store,
				displayField: 'display_as',
				valueField: 'service_type_id',
				triggerAction: 'all',
				mode: 'local',
				forceSelection: true
			}],
			buttons: [{
				text: 'Add',
				handler: function( )
				{
					var combo = Ext.getCmp('type-combo');
					if ( combo.getValue() )
					{
						document.location.href = root + 'service/createnew/' + combo.getValue();
					}
					else
					{
						Ext.MessageBox.alert( 'Select', 'Please select a case type' );
					}
				}
			},{
				text: 'Cancel',
				handler: function()
				{
					win.close();
				}
			}]
		}]
	});
	
	win.show();
}