var protocol = document.location.protocol+"//";	
var domain = document.domain;
var tenant_save_mode = 'insert';

String.prototype.format = function() {
    var formatted = this;
    for(arg in arguments) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

// detecting if it's a mobile device
var mobile = function(){
	return {
		detect:function(){
			var uagent = navigator.userAgent.toLowerCase(); 
			var list = this.mobiles;
			var ismobile = false;
			for(var d=0;d<list.length;d+=1){
				if(uagent.indexOf(list[d])!=-1){
					ismobile = true;
				}
			}
			return ismobile;
		},
		mobiles:[
			"midp","240x320","blackberry","netfront","nokia","panasonic",
			"portalmmm","sharp","sie-","sonyericsson","symbian",
			"windows ce","benq","mda","mot-","opera mini",
			"philips","pocket pc","sagem","samsung","sda",
			"sgh-","vodafone","xda","palm","iphone",
			"ipod","android", "playbook"
		]
	};
}();

// <br /> to \n change
function br2nl(myString){
	var replacement = '\n';
	var myNewString = myString.replace(/\<br \/\>/g, replacement);
	return myNewString;
}

// \n to <br /> change
function nl2br(myString){
	var replacement = '<br />';
	var myNewString = myString.replace(/\n/g, replacement);
	return myNewString;
}

//Only matches numbers and gets rid of everything else, also inserts - in proper places
//This is primarily for display purposes only
function phone_format(myString){
	
	var myString = myString.replace(/[^0-9]/g, '');
	
	if(parseInt(myString.length) == 10)
	{
		myString = myString.substring(0,3)+'-'+myString.substr(3,3)+'-'+myString.substr(6,4);
	}
	
	return myString;
}

//Function to be called when IFrame is completed for evaluation
function uploadDone()
{
	$('#spinner_uploading').hide(150);
	
	var myIFrame = document.getElementById('upload_target');
	var content = myIFrame.contentWindow.document.body.innerHTML;
	var url = $("form#form_attachment").attr('action');
	
	if(jQuery.trim(content) == 'success')
	{
		$('span#attachment_nothing').hide();
		
		if(jQuery.trim($('input[type="hidden"][id="attach_to_user"]').val()) !== '')
		{
			var user_id = $('input[type="hidden"][id="attach_to_user"]').val();
			
			$.get(url+'/ajax/'+user_id+'/user', function(view_data){
				$("div#maintenance_upload_view_container").prepend(view_data);
			});
		}
		
		else if(jQuery.trim($('input[type="hidden"][id="attach_to_building"]').val()) !== '')
		{
			var building_id = $('input[type="hidden"][id="attach_to_building"]').val();
			
			$.get(url+'/ajax/'+building_id+'/building', function(view_data){
				$("div#maintenance_upload_view_container").prepend(view_data);
			});
		}
		
		else
		{
			var maintenance_id = $('input[type="hidden"][id="idmaintenance"]').val();
			
			$.get(url+'/ajax/'+maintenance_id, function(view_data){
				$("div#maintenance_upload_view_container").prepend(view_data);
			});
		}
		
		$('input[type="checkbox"][name="add_resident"]').attr("checked", false);
		document.getElementById('uploadattachment').style.display='none';
		$('#mask').fadeOut();
		
		$('input[name="attachment_name"]').val('');
		$('input[name="userfile"]').val('');
		$('input[name="filename"]').val('');
	}
	
	else
	{
		$('input#upload_attachment_button').show();
		$('#upload_complete').html(content).show().delay(2000).slideUp('slow');
	}
	
	$('input#upload_attachment_button').show();
	$('iframe#upload_target').removeAttr('onload');
}

function checkdateformat(userinput)
{
	var dateformat = /^\d{2,2}(\-|\/|\.)\d{2,2}\1\d{4}$/
	return dateformat.test(userinput) //returns true or false depending on userinput
}

$().ready(function () {
	
	//Initialize dialog by dialog
	function initialize_vendor(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div'+init_dialog+' a.selected').removeClass('selected');
			
			if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div'+init_dialog+' a[id="'+pieces[i]+'"]:first').addClass('selected');
				}
			}
		}
	}
	
	function initialize_inventorygroup(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div'+init_dialog+' a.selected').removeClass('selected');
			
			if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div'+init_dialog+' a[id="'+pieces[i]+'"]:first').addClass('selected');
				}
			}
		}
	}
	
	function initialize_building_multi(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var type = $('a[dialog="'+init_dialog+'"]:first').attr('rel');
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div'+init_dialog+' a.selected').removeClass('selected');
			
			if(option == 'ALL')
			{
				$('div'+init_dialog+' a[class="listitem"][rel="'+type+'"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div'+init_dialog+' a[id="'+pieces[i]+'"][rel="'+type+'"]:first').addClass('selected');
				}
			}
		}
	}
	
	function initialize_categories(init_dialog)
	{
		if(init_dialog != undefined)
		{
			$('div'+init_dialog+' a.back').attr('id', '').hide();
			
			if(init_dialog == '#reportfiltercategory_multi')
			{
				$('div#parent_category_display').show();
				$('div#child_category_display').hide();
				
				var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
				
				//Do a check to see how many options are selected
				var option_count = option.split(",");
				var child_count = parseInt($('input[name="all_child_count"]').val());
				
				if((option == 'ALL')||(option_count.length >= child_count))
				{
					$('div#reportfiltercategory_multi div#parent_category_display a').addClass('selected');
				}
				
				else
				{
					$('div#reportfiltercategory_multi div#parent_category_display a#ALL').removeClass('selected');
					
					var selected_categories = $('a[dialog="#reportfiltercategory_multi"]').attr('option');
					
					$.post("/mobile/reports/ajax_selected_categories", {'selected_categories' : selected_categories}, function(data){
						if(data.status == 'success')
						{
							$('div#reportfiltercategory_multi div#parent_category_display a').removeClass('selected');
							
							var parent_ids = data.selected_parent_ids.split(',');
							
							for(i=0; i<parent_ids.length; i++)
							{
							   $('div#reportfiltercategory_multi div#parent_category_display a[parent_ids="'+parent_ids[i]+'"]').addClass('selected');
							}
						}
						
						else
						{
							alert(data.message);
						}
					}, 'json');
				}
			}
			
			else
			{
				var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
				var pieces = option.split(",");
				
				$('div'+init_dialog+' a.selected').removeClass('selected');
				
				if(option == 'ALL')
				{
					$('div'+init_dialog+' a[class="listitem"][rel="CATEGORY"]').addClass('selected');
				}
				
				else if(pieces.length)
				{
					for(var i=0;i<pieces.length;i++)
					{
						$('div'+init_dialog+' a[id="'+pieces[i]+'"][rel="CATEGORY"]:first').addClass('selected');
					}
				}
			}
		}
	}
	
	function initialize_child_categories(init_dialog, parent_all_selected)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			//Parent ALL category selected, select all children
			if((parent_all_selected != undefined)&&(parent_all_selected == '1'))
			{
				$('div'+init_dialog+' div#child_category_display a').addClass('selected');
			}
			
			else
			{
				$('div'+init_dialog+' div#child_category_display a.selected').removeClass('selected');
				
				if(option == 'ALL')
				{
					$('div'+init_dialog+' div#child_category_display a[class="listitem"][rel="CATEGORY"]').addClass('selected');
				}
				
				else if(pieces.length)
				{
					for(var i=0;i<pieces.length;i++)
					{
						$('div'+init_dialog+' div#child_category_listing a[id*="'+pieces[i]+'"][rel="CATEGORY"]:first').addClass('selected');
					}
				}
				
				var count_not_selected = $('div'+init_dialog+' div#child_category_listing a').not('.selected').length;
				
				if(count_not_selected > 0)
				{
					$('div'+init_dialog+' div#child_category_display a#ALL').removeClass('selected');
				}
				
				else
				{
					$('div'+init_dialog+' div#child_category_display a#ALL').addClass('selected');
				}
			}
		}
	}
	
	function initialize_employee(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div'+init_dialog+' a.selected').removeClass('selected');
			
			if(option == 'ALL')
			{
				$('div'+init_dialog+' a[class="listitem"][rel="EMPLOYEE"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div'+init_dialog+' a[id="'+pieces[i]+'"][rel="EMPLOYEE"]:first').addClass('selected');
				}
			}
		}
	}
	
	function initialize_exclude(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div'+init_dialog+' a.selected').removeClass('selected');
			
			if(option == 'NONE')
			{
				$('div'+init_dialog+' a[class="listitem"][id="NONE"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div'+init_dialog+' a[id="'+pieces[i]+'"]:first').addClass('selected');
				}
			}
		}
	}
	
	function initialize_hours_open(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div'+init_dialog+' a.selected').removeClass('selected');
			
			if(option == 'ALL')
			{
				$('div'+init_dialog+' a[class="listitem"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div'+init_dialog+' a[id="'+pieces[i]+'"]:first').addClass('selected');
				}
			}
		}
	}
	
	function initialize_index_search_filter_button(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var filter_button_text = $('h2#index_search_filter a.selector').text().toLowerCase();
			
			if(filter_button_text != undefined)
			{
				$('div#index_search_filter_button div.innercontent a').removeClass('selected');
				$('div#index_search_filter_button div.innercontent a#'+filter_button_text).addClass('selected');
			}
		}
	}
	
	function initialize_status_satisfaction(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div'+init_dialog+' a.selected').removeClass('selected');
			
			if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div'+init_dialog+' a[id="'+pieces[i]+'"]:first').addClass('selected');
				}
			}
		}
	}
	
	function initialize_building_multi_menu(init_dialog)
	{
		if(init_dialog != undefined)
		{
			$('div'+init_dialog+' a.back').attr('id', '').hide();
			$('div'+init_dialog+' a[function="save"]').attr('id', '').hide();
			$('div'+init_dialog+' div[id="filter_building_display"]').hide();
			$('div'+init_dialog+' div[id="filter_employee_display"]').hide();
			$('div'+init_dialog+' div[id="filter_regional_manager_display"]').hide();
			$('div'+init_dialog+' div[id="filter_svp_display"]').hide();
			$('div'+init_dialog+' div[id="filter_options_display"]').show();
		}
	}
	
	function initialize_interval(init_dialog)
	{
		if(init_dialog != undefined)
		{
			initialize_common_dialog(init_dialog);
		}
	}
	
	function initialize_status_requests(init_dialog)
	{
		if(init_dialog != undefined)
		{
			initialize_common_dialog(init_dialog);
		}
	}
	
	function initialize_status_residents(init_dialog)
	{
		if(init_dialog != undefined)
		{
			initialize_common_dialog(init_dialog);
		}
	}
	
	function initialize_login(init_dialog)
	{
		if(init_dialog != undefined)
		{
			initialize_common_dialog(init_dialog);
		}
	}
	
	function initialize_status_moveout(init_dialog)
	{
		if(init_dialog != undefined)
		{
			initialize_common_dialog(init_dialog);
		}
	}
	
	function initialize_common_dialog(init_dialog)
	{
		if(init_dialog != undefined)
		{
			var option = $('a[dialog="'+init_dialog+'"]:first').attr('option');
			
			$('div'+init_dialog+' a[id="'+option+'"]:first').addClass('selected');
			$('div'+init_dialog+' a[id!="'+option+'"]').removeClass('selected');
		}
	}
	//End initialize by dialog
	
	
	
	
	
	//Initialize dialog values by report on form load
	function initialize_aging_summary()
	{
		
	}
	
	function initialize_maintenance_work_log()
	{
		initialize_building_multi('#reportfilterbuilding_multi');
		initialize_employee('#reportfilteremployee');
	}
	
	function initialize_resident_activity()
	{
		
	}
	
	function initialize_resident_satisfaction()
	{
		
	}
	
	function initialize_resident_moveout()
	{
		
	}
	
	function initialize_inventory()
	{
		initialize_vendor('#reportfiltervendor');
		initialize_inventorygroup('#reportfilterinventorygroup');
	}
	
	function initialize_maintenance_category()
	{
		//initialize_building_multi('#reportfilterbuilding_multi');
		initialize_building_multi('#reportfilterbuilding_multi_menu');
		
		if($('a[dialog="#reportfiltercategory_multi"]').length > 0)
		{
			initialize_categories('#reportfiltercategory_multi');
		}
		
		else
		{
			initialize_categories('#reportfiltercategory');
		}
	}
	//End initialize dialog by report
	
    //Some reports need dialogs initialized
	var current_page = document.URL;
	
	if(current_page != undefined)
	{
		var reports_page_url = '/mobile/reports/';
		var compare = new RegExp(reports_page_url, "gi");
		compare = current_page.match(compare);
					
		//Initialize the dialog window values for reports
		if(compare != null)
		{
			var reports_list = new Array('aging_summary','maintenance_work_log','resident_activity','resident_satisfaction','resident_moveout','inventory', 'maintenance_category');
			
			$.each(reports_list, function(key, value){
				
				var compare = new RegExp(value, "gi");
				compare = current_page.match(compare);
				
				//Matched, now initialize
				if(compare != null)
				{
					var function_name = 'initialize_'+value+'();';
					eval(function_name);
					return false;
				}
			});
		}
	}
	//End some reports need dialogs initialized
	
	
	
	
	
	images_folder = '/resources/mobile/images';
    // global variable for the dialog name
    dialog = "";

    // the "stack" of size 1
    dialogstack = new Array();
    
    // animation delay
    anim_delay = 150;
    
    // items used is now kept track of globally
    // items = {};
    
    // open dialog code, doesn't use global
    var opendialog = function(whichdialog) {
		if (whichdialog === undefined) {
            return;
        }
        
        dialog = whichdialog;
		
        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        // is it a mobile device?
        var is_mobile = mobile.detect();
	    /* **** START OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */
	    if (cv_screen.is_small)
	    {	    	
	    	$(whichdialog).css({'width':winW -15, 'top':0+$(window).scrollTop(), 'left':0});
	    	
	    	$('.orangeroundedbutton').each(function()
	    	{
	    		$(this).css({'width' : '80%'})
	    	});
	    }
        /* END OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */

		if ($(whichdialog).hasClass('simple')) {
		    /* **** START OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */
		    if (cv_screen.is_small)
		    {
		    	$(whichdialog).css({'width':winW -15, 'top':0+$(window).scrollTop(), 'left':0});
                var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
                $(whichdialog).children('.innercontent').css({'height':innerh});
		    }
		    /* END OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */
		    else
		    {
	            if (is_mobile) {
	                $(whichdialog).css({'width':winW/2, 'top':winH/8+$(window).scrollTop(), 'left':winW/4});
	                
	            } else {        
	                $(whichdialog).css({'width':winW/2, 'height':3*winH/4, 'top':winH/8+$(window).scrollTop(), 'left':winW/4});
	                var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
	                $(whichdialog).children('.innercontent').css({'height':innerh});
	            }
		    }
        
        } else if ($(whichdialog).hasClass('smallsimple')) {
		    /* **** START OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */
		    if (cv_screen.is_small)
		    {
		    	$(whichdialog).css({'width':winW -15, 'top':0+$(window).scrollTop(), 'left':0});
                var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
                $(whichdialog).children('.innercontent').css({'height':innerh});
		    }
		    /* END OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */
		    else
		    {
		    	$(whichdialog).css({'width':winW/3, 'height':winH/3, 'top':winH/4   +$(window).scrollTop(), 'left':winW/3});
            	var innerh = $(whichdialog).innerHeight() - $(whichdialog).children('h3:first').outerHeight() - 29;
            	$(whichdialog).children('.innercontent').css({'height':innerh});
		    }
        } else if ($(whichdialog).hasClass('setwidth')) {
		    /* **** START OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */
		    if (cv_screen.is_small)
		    {
		    	/* ignore setwidth if mobile */
		    }
		    else
		    /* END OF CODE PUT IN TO MAKE DIALOGS WORK ON MOBILE **** */
		    {
		    	var w = $(whichdialog).attr('dialogwidth');
		    	$(whichdialog).css({'width':w, 'top':winH/6+$(window).scrollTop(), 'left':winW/4});
		    }
        }
        
        if ($(whichdialog).hasClass('bottombuttons')) {
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
        }
        
        // details of whichdialog loading
        // progress whichdialog, first time loading
        if (whichdialog == '#progressindicator') {
       
            var currarrow = $('#arrows .selected').attr('status');    
    
            if (currarrow == 'incomplete') {
            
                $('#pendingreasons').css('display','none');
                $('#savecancelbottombuttons').css('display','none');
                
                $('#completeddetails').css('display','none');
                
            } else if (currarrow == 'pending') {

                $('#pendingreasons').css('display','block');
                $('#savecancelbottombuttons').css('display','block');
                
                $('#completeddetails').css('display','none');
                
            } else if (currarrow == 'complete') {
                $('#pendingreasons').css('display','none');
                $('#savecancelbottombuttons').css('display','none');
                
                //$('#completeddetails').css('display','block');
                $('#completeddetails').css('display','none');
                $('#savecancelbottombuttons').css('display','block');
                inventorylistsize_modal();
            }
            
            formatprogressdialog();
            
            
        } else if (whichdialog == '#addinventory') {
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
            
            populateinventorylist();
            
        } else if (whichdialog == '#billablehours') {
        	var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);	
        
        } else if (whichdialog == '#apartmentlist') {
            /* don't need this without a save button
            
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
            
            */
            
        } else if (whichdialog == '#buildinglist') {
            /* don't need this because of the lack of a save button
            
            var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height())+10;
            $(whichdialog).children('.innercontent').css('height', '-='+sh);
            */
            
            populateBuildingList();
        }
        else if (whichdialog == "#editbuilding")
        {
            var c = employeesAssignedToBuilding.length;
            
    		if (c == 0)
    		{
    			$('#building_editemployees span.text').text('Select Employees');
    			$('#building_editemployees span.action').text('');
    		}
            else if (c == 1)
            {
    			$('#building_editemployees span.text').text(employeesAssignedToBuilding[0]);
    			$('#building_editemployees span.action').text('Change');
            } else
            {
                var s = c + " employees";
                $('#building_editemployees span.text').html('<span class="mult">'+s+'</span>');
                $('#building_editemployees span.action').text('Change');
            }      	
        }
        else if (whichdialog)
        {
        	$('textarea#settings_emergencymessage').val($('p#emergency_message_text').html());
        }
        
        $(whichdialog).fadeIn(anim_delay);
        
        // setting the mask height
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        
        $('#mask').css({'width':maskWidth,'height':maskHeight,'top':0, 'left':0});
        $('#mask').fadeTo(anim_delay,0.2);
        
        // ADDED 22 NOV, EDITED 25 NOV
        if (whichdialog == '#edittenant' || whichdialog == '#editemployee'
            || $(whichdialog).hasClass('textfields'))
        {
        	if (whichdialog == '#edittenant')
        	{
        		$(whichdialog).css('overflow', 'hidden');
        		$(whichdialog + ' div.innercontent').css('overflow', 'hidden');
        		$(whichdialog + ' div.innercontent').css('height', '+='+15);
        	}
        	
            $(whichdialog + ' input.roundedinput.fullwidth').each(function () {
                if ($(this).attr('padded') == 'yes') {
                    return;
                }
                var label = $(this).attr('label');
                if (label == undefined) {
                    return;
                }

                var w = parseInt($(label).width())+20;
                $(this).css('padding-left',w);
                $(this).css('width','-='+w);
                $(this).attr('padded','yes');
               // $(whichdialog).children('.innercontent').css('height', '+='+5);
            
            });
            
            $(whichdialog + ' textarea.roundedinput.fullwidth').each(function () {
                if ($(this).attr('padded') == 'yes') {
                    return;
                }
                var label = $(this).attr('label');
                if (label == undefined) {
                    return;
                }
                
                var h = parseInt($(label).height())+30;
                $(this).css('padding-top',h);
                $(this).attr('padded','yes');
            });

            $(whichdialog).css('top',winH/9+$(window).scrollTop());
        }
        
        if (whichdialog == '#editemployee') {
            if ($(whichdialog).children('.innercontent').attr('addedheight') != 'yes') {
                $(whichdialog).children('.innercontent').css('height', '+='+15);
                $(whichdialog).children('.innercontent').attr('addedheight','yes');
            }
        }
		
		//Initial selected options for reports
		if((((dialog == '#reportfilterstatus_requests')||(dialog == '#reportfilterstatus_residents')||(dialog == '#reportfilterinterval')||(dialog == '#reportfilterlogin')||(dialog == '#reportfilterstatus_moveout'))))
		{
			//Do not allow daily intervals for this report subject
			if(($('form#resident_satisfaction').length > 0)&&(dialog == '#reportfilterinterval'))
			{
				$('div#reportfilterinterval a#DAILY:first').hide();
			}
			
			else if(($('form#resident_activity').length > 0)&&(dialog == '#reportfilterinterval'))
			{
				$('div#reportfilterinterval a#DAILY:first').hide();
			}
			
			initialize_interval('#reportfilterinterval');
			
			if(dialog == '#reportfilterstatus_requests')
			{
				initialize_status_requests('#reportfilterstatus_requests');
			}
			
			else if(dialog == '#reportfilterstatus_residents')
			{
				initialize_status_residents('#reportfilterstatus_residents');
			}
			
			else if(dialog == '#reportfilterlogin')
			{
				initialize_login('#reportfilterlogin');
			}
			
			else if(dialog == '#reportfilterstatus_moveout')
			{
				initialize_status_moveout('#reportfilterstatus_moveout');
			}
		}
		
		else if(dialog == '#index_search_filter_button')
		{
			//Set selected options
			initialize_index_search_filter_button('#iindex_search_filter_button');
			//End set selected options
		}
		
		else if(dialog == '#reportfilterbuilding_multi_menu')
		{
			//Set selected options
			initialize_building_multi_menu('#reportfilterbuilding_multi_menu');
			//End set selected options
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = $(whichdialog).outerHeight() + 325 - sh;
			var oh = ih + sh + sh + 29;

			//$(whichdialog).css({'height': oh});
			
			$('#reportfilterbuilding_multi_menu .innercontent').children('#filter_building_display').css({'height': ih});
			$("#reportfilterbuilding_multi_menu .innercontent").children('#filter_employee_display').css({'height': ih});
			$("#reportfilterbuilding_multi_menu .innercontent").children('#filter_regional_manager_display').css({'height': ih});
			$("#reportfilterbuilding_multi_menu .innercontent").children('#filter_svp_display').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == '#reportfilterbuilding_multi')
		{
			//Set selected options
			initialize_building_multi('#reportfilterbuilding_multi');
			//End set selected options
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = 529;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});
			
			$('#reportfilterbuilding_multi').children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == '#reportfilteremployee')
		{
			//Set selected options
			initialize_employee('#reportfilteremployee');
			//End set selected options
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = 529;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});
			
			$('#reportfilteremployee').children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == '#reportfilterexclude')
		{
			//Set selected options
			initialize_exclude('#reportfilterexclude');
			//End set selected options
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = 329;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});
			
			$('#reportfilterexclude').children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == '#reportfilterhours_open')
		{
			//Set selected options
			initialize_hours_open('#reportfilterhours_open');
			//End set selected options
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = 329;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});
			
			$('#reportfilterhours_open').children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == '#reportfiltercategory')
		{
			//Set selected options
			initialize_categories('#reportfiltercategory');
			//End set selcted options
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = 529;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});
			
			$('#reportfiltercategory').children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == '#reportfiltercategory_multi')
		{
			//Set selected options
			initialize_categories('#reportfiltercategory_multi');
			//End set selcted options
			
			//Store currently selected options in event of cancelled action
			var current_options = $('a[dialog="#reportfiltercategory_multi"]').attr('option');
			
			$('a[dialog="#reportfiltercategory_multi"]').attr('previous_option', current_options);
			//End storing currently selected options
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = 529;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});
			
			$('#reportfiltercategory_multi').children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(((dialog == '#reportfilterstatus_satisfaction')||(dialog == '#reportfiltervendor')||(dialog == '#reportfilterinventorygroup')))
		{
			//Set selected options
			if(dialog == '#reportfiltervendor')
			{
				initialize_vendor('#reportfiltervendor');
			}
			
			else if(dialog == '#reportfilterinventorygroup')
			{
				initialize_inventorygroup('#reportfilterinventorygroup');
			}
			
			else if(dialog == '#reportfilterstatus_satisfaction')
			{
				initialize_status_satisfaction('#reportfilterstatus_satisfaction');
			}
			//End set selected options
		}
		
		else if(dialog == '#changereport')
		{
			var selected_id = $('a[dialog="#changereport"]:first').attr('selected_id');
			
			if(selected_id !== '')
			{
				$('div[id="changereport"] a.listitem').each(function()
				{	
					var id = $(this).attr('id');
					
					if(id == selected_id)
					{
						$(this).addClass('selected');
					}
					
					else
					{
						$(this).removeClass('selected');
					}
				});
			}
		}
		
		else if(dialog == '#changeadvancedreport')
		{
			var selected_id = $('a[dialog="#changeadvancedreport"]:first').attr('selected_id');
			
			if(selected_id !== '')
			{
				$('div[id="changeadvancedreport"] a.listitem').each(function()
				{	
					var id = $(this).attr('id');
					
					if(id == selected_id)
					{
						$(this).addClass('selected');
					}
					
					else
					{
						$(this).removeClass('selected');
					}
				});
			}
		}
		
		else if(dialog == '#sisense_user_guide')
		{
			var report = $('a[dialog="#changeadvancedreport"]:first').attr('selected_id');
			
			if(report !== '')
			{
				$('div#sisense_user_guide span#'+report).show();
				$('div#sisense_user_guide span[id!='+report+']').hide();
			}
			
			else
			{
				$('div#sisense_user_guide span').hide();
			}
			
			$('div#sisense_user_guide span#general').show();
		}
		
		else if(dialog == '#createnotification')
		{
			var send = $('div#createnotification div.panel_1 span.send a.selected:first').attr('id');
			var mode = $('div#createnotification a[function="save"]:first').attr('mode');
			var message = $('div#createnotification textarea[name="message"]:first').text();
			message = br2nl(message);
			
			$('div#createnotification textarea[name="message"]:first').html(message);
			
			if(mode == 'create')
			{
				$('div#createnotification h3:first').html('Create Notification');
			}
			
			else
			{
				$('div#createnotification h3:first').html('Edit Notification');
			}
			
			if(send == 'NOW')
			{
				$('div#createnotification a[function="save"]:first').text('Send Now');
				$('div#createnotification div.panel_1 span.send_by').hide();
			}
			
			else
			{
				$('div#createnotification a[function="save"]:first').text('Schedule');
				$('div#createnotification div.panel_1 span.send_by').show();
			}
			
			$('div#createnotification a[function="next"]:first').hide();
			$('div#createnotification a.back:first').removeAttr('panel').hide();
			$('div#createnotification div.panel_2:first').hide();
			$('div#createnotification div.panel_3:first').hide();
			$('div#createnotification div.panel_3 input[name="search"]:first').val('');
			$('div#createnotification div.panel_1:first').show();
			$('div#createnotification a[function="save"]:first').show().removeAttr('panel');
			$('div#createnotification a[function="close"]:first').show();
			//notification_delivery_details_text();
			
			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = $(whichdialog).outerHeight() - 29 - sh;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});

			$(".panel_1").children('.innercontent').css({'height': ih});
			$(".panel_2").children('.innercontent').css({'height': ih});
			$(".panel_3").children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == '#copycreatenotification')
		{
			var send = $('div#copycreatenotification div.panel_1 span.send a.selected:first').attr('id');
			var message = $('div#copycreatenotification textarea[name="message"]:first').text();
			message = br2nl(message);
			
			$('div#copycreatenotification textarea[name="message"]:first').html(message);
			
			if(send == 'NOW')
			{
				$('div#copycreatenotification a[function="save"]:first').text('Send Now');
				$('div#copycreatenotification div.panel_1 span.send_by').hide();
			}
			
			else
			{
				$('div#copycreatenotification a[function="save"]:first').text('Schedule');
				$('div#copycreatenotification div.panel_1 span.send_by').show();
			}
			
			$('div#copycreatenotification h3:first').html('Create Notification');
			$('div#copycreatenotification a[function="next"]:first').hide();
			$('div#copycreatenotification a.back:first').removeAttr('panel').hide();
			$('div#copycreatenotification div.panel_2:first').hide();
			$('div#copycreatenotification div.panel_3:first').hide();
			$('div#copycreatenotification div.panel_3 input[name="search"]:first').val('');
			$('div#copycreatenotification div.panel_1:first').show();
			$('div#copycreatenotification a[function="save"]:first').show().removeAttr('panel');
			$('div#copycreatenotification a[function="close"]:first').show();
			

			/* START of hack to limit dialog size */
			var sh = parseInt($(whichdialog).children('.savecancelbottombuttons').height());
			var ih = $(whichdialog).outerHeight() - 29 - sh;
			var oh = ih + sh + sh + 29;

			$(whichdialog).css({'height': oh});

			$(".panel_1").children('.innercontent').css({'height': ih});
			$(".panel_2").children('.innercontent').css({'height': ih});
			$(".panel_3").children('.innercontent').css({'height': ih});
            /* START of hack to limit dialog size */
		}
		
		else if(dialog == "#add_forwarding_address")
		{
			$('div#add_forwarding_address').show();
		}
		
		else if(dialog == '#recurring_request')
		{
			recurring_request_opendialog_callback();
		}
		
        // END EDITS 22nov
        inventorylistsize_modal();
    }
	
	//Original createnotification logic
	$('div#createnotification div.panel_2 input[name="search_buildings"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#createnotification div.panel_2 span.building_message').html('').hide();
			$('div#createnotification div.panel_2 a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#createnotification div.panel_2 a').each(function()
			{
				var id = $(this).attr('id');
				var building_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = building_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#createnotification div.panel_2 a[show="no"]').hide();
			$('div#createnotification div.panel_2 a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#createnotification div.panel_2 span.building_message').html('No buildings found').show();
				$('div#createnotification div.panel_2 a#ALL').hide();
			}
			
			else
			{
				$('div#createnotification div.panel_2 span.building_message').html('').hide();
				$('div#createnotification div.panel_2 a#ALL').show();
			}
		}
	});
	
	$('div#createnotification div.panel_3 input[name="search"]:first').keypress(function(e){
		var animate = $('div#createnotification div.panel_3 span#spinnerbox:first').attr('animate');
		var value = $(this).val();
		
		if(animate == 'off')
		{
			$('div#createnotification div.panel_3 span#spinnerbox:first').show().attr('animate', 'on');
		}
		
		if((value == '')&&(e.keyCode == 8))
		{
			$('div#createnotification div.panel_3 span#spinnerbox:first').hide().attr('animate', 'off');
		}
	});
	
	//Autocomplete for tenant search in create notification dialog
	$('div#createnotification div.panel_3 input[name="search"]:first').autocomplete({
		source: function(request, response)
		{
			var building_id = $('div#createnotification div.panel_2 a.selected:first').attr('id');
			var selected_building_ids = Array();
			
			if(building_id == 'ALL')
			{
				//Don't do anything
			}
			
			else
			{
				$('div#createnotification div.panel_2 a.selected').each(function()
				{
					var building_id = $(this).attr('id');
					selected_building_ids.push(building_id);
				});
			}
			
			$.ajax(
			{
				url: protocol+domain+'/mobile/tenant/ajax_create_notification_get_tenants',
				data: {
						'building_id' : selected_building_ids,
						'term' : request.term
					  },
				type: "POST",  // a jQuery ajax POST transmits in querystring format in utf-8
				dataType: "json",   //return data in json format
				
				success: function(data)
				{
					$('div#createnotification div.panel_3 span#spinnerbox:first').hide().attr('animate', 'off');
					
					if(data.status == 'success')
					{
						if((data.message == '')||(data.message == 'No units found'))
						{
							$('div#createnotification div.panel_3 div.innercontent div.content_listing:first').html('<span style="padding-left:10px;">'+data.message+'<span>');
							$('div#createnotification div.panel_3 a#ALL:first').hide();
						}
						
						else
						{
							$('div#createnotification div.panel_3 div.innercontent div.content_listing:first').html('').append(data.message);
							$('div#createnotification div.panel_3 a#ALL:first').show();
							
							//Set selected options
							var option = $('div#createnotification div.panel_1 input[name="tenant_ids"]:first').val();
							var pieces = option.split(",");
							
							if(pieces.length)
							{
								for(var i=0;i<pieces.length;i++)
								{
									$('div#createnotification div.panel_3 a[id="'+pieces[i]+'"]:first').addClass('selected');
								}
							}
							//End set selected options
						}
					}
				}
			});
		},
		
		minLength: 0,
		delay: 500
	});
	//End autocomplete
	
	//Tenant details delivery details text
	function notification_delivery_details_text()
	{
		var tenants = $('div#createnotification div.panel_1 input[name="tenant_ids"]:first').val();
		var priority = $('div#createnotification div.panel_1 span.priority a.selected:first').attr('id');
		var buildings = Array();
		
		/*$('div#createnotification div.panel_2 a.selected').each(function()
		{
			var building_id = $(this).attr('id');
			buildings.push(building_id);
		});*/
		
		if((buildings.length)||(tenants !== ''))
		{
			$.post("/mobile/tenant/ajax_create_notification_delivery_details", {'buildings' : buildings, 'tenants' : tenants, 'priority' : priority}, function(data)
			{
				if(data.status == 'success')
				{
					$('div#createnotification div.panel_1 span.delivery_details:first').html(data.message);
				}
				
				else
				{
					$('div#createnotification div.panel_1 span.delivery_details:first').html('');
				}
			}, 'json');
		}
	}
	//End details text
	
	//Maintenance index search filter click
	$('div#index_search_filter_button div.innercontent a.listitem').click(function(){
		$('div#index_search_filter_button div.innercontent a').removeClass('selected');
		$(this).addClass('selected');
		
		var filter_text = $(this).text();
		
		//Not enough space, reduce text
		if(filter_text == 'Request Description')
		{
			filter_text = 'Description';

		}
		//End space
		
		$('h2#index_search_filter a.selector').text(filter_text);
		
		page_offset = 0;
		reset_page = 1;
		show_more = 1;
		loadmore_busy = 0;
		loadmore();
	});
	
	//Tenant details create notification navigation
	$('div#createnotification div.panel_1 a.listitem').click(function(){
		var id = $(this).attr('id');
		var count = 0;
		
		if(id == 'BUILDING')
		{
			$('div#createnotification div.panel_2 a.selected').each(function()
			{
				var id = $(this).attr('id');
				
				if(id !== 'ALL')
				{
					count++;
				}
			});
			
			if(count > 0)
			{
				$('div#createnotification a[function="next"]:first').removeClass('disabled_create_notification');
			}
			
			else
			{
				$('div#createnotification a[function="next"]:first').addClass('disabled_create_notification');
			}
			
			$('div#createnotification h3:first').html('Step 1: Select Buildings');
			$('div#createnotification a[function="close"]:first').hide();
			$('div#createnotification a[function="save"]:first').hide();
			$('div#createnotification div.panel_1:first').hide();
			$('div#createnotification div.panel_2:first').show();
			$('div#createnotification a[function="next"]:first').show();
			$('div#createnotification a.back:first').attr('panel', '2').show();
		}
	});
	
	$('div#createnotification div.panel_2 a.listitem').click(function(){
		var id = $(this).attr('id');
		var count = 0;
		var search_heading_text = '';
		
		if(id == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#createnotification div.panel_2 a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#createnotification div.panel_2 a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div#createnotification div.panel_2 a[id="ALL"]:first').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
			
		//Change the "Select Recipients" text option in panel 1
		$('div#createnotification div.panel_2 a.selected').each(function()
		{
			var id = $(this).attr('id');
			
			if(id !== 'ALL')
			{
				++count;
				var building_name = $(this).text();
				
				if(count == 1)
				{
					search_heading_text = $(this).text();
				}
				
				else
				{
					search_heading_text = count+' buildings';
				}
			}
		});
		
		if(count > 0)
		{
			$('div#createnotification a[function="next"]:first').removeClass('disabled_create_notification');
		}
		
		else
		{
			$('div#createnotification a[function="next"]:first').addClass('disabled_create_notification');
		}
	});
	
	$('div#createnotification a[function="next"]:first').click(function(){
		var term = '';
		var selected_building_ids = Array();
		var count = 0;
		
		$('div#createnotification div.panel_2 a.selected').each(function()
		{
			var building_id = $(this).attr('id');
			selected_building_ids.push(building_id);
			count++;
		});
		
		if(count > 0)
		{
			$('div#createnotification a[function="save"]:first').text('Save');
			
			$('div#createnotification h3:first').html('Step 2: Select Units');
			
			$(this).hide();
			$('div#createnotification div.panel_3 div.innercontent div.content_listing:first').html('');
			
			$.post("/mobile/tenant/ajax_create_notification_get_tenants/", {'building_id' : selected_building_ids, 'term' : term}, function(data){
				if(data.status == 'success')
				{
					var count = 0;
					
					$('div#createnotification div.panel_3 div.innercontent div.content_listing:first').append(data.message);
					
					if($('div#createnotification div.panel_3 div.innercontent a[id="ALL"]:first').hasClass('selected'))
					{
						$('div#createnotification div.panel_3 div.content_listing a.listitem').addClass('selected');
						
						$('div#createnotification div.panel_3 div.content_listing a.selected').each(function()
						{
							count++;
						});
					}
					
					else
					{
						//Set selected options
						var option = $('div#createnotification div.panel_1 input[name="tenant_ids"]:first').val();
						var pieces = option.split(",");
						
						if(pieces.length)
						{
							for(var i=0;i<pieces.length;i++)
							{
								$('div#createnotification div.panel_3 a[id="'+pieces[i]+'"]:first').addClass('selected');
							}
						}
						//End set selected options
						
						$('div#createnotification div.panel_3 div.content_listing a.selected').each(function()
						{
							count++;
						});
					}
							
					if(count == 0)
					{
						//No one selected, save won't work
						$('div#createnotification a[function="save"]:first').attr('panel', 'disabled').addClass('disabled_create_notification').show();
					}
					
					else
					{
						//Someone selected, save will work
						$('div#createnotification a[function="save"]:first').attr('panel', '3').removeClass('disabled_create_notification').show();
					}
					
					$('div#createnotification div.panel_1:first').hide();
					$('div#createnotification div.panel_2:first').hide();
					$('div#createnotification div.panel_3:first').show();
					$('div#createnotification a.back:first').attr('panel', '3').show();
				}
				
				else
				{
					if(typeof(data.message) !== 'undefined')
					{
						alert(data.message);
					}
					
					else
					{
						alert('An error has occurred');
					}
					
					$('div#createnotification a[function="next"]:first').show();
				}
			}, 'json');
		}
		
		else
		{
			alert('Please choose a building');	
		}
	});
	
	$('div#createnotification div.panel_3 a.listitem').live('click', function(){
		var id = $(this).attr('id');
		var option = Array();
		var count = 0;
		
		if(id == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
				$('div#createnotification div.panel_3 div.content_listing a.listitem').removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
				$('div#createnotification div.panel_3 div.content_listing a.listitem').addClass('selected');
				
				$('div#createnotification div.panel_3 div.content_listing a.selected').each(function()
				{
					option[count++] = $(this).attr('id');
				});
			}
		}
		
		else
		{
			$('div#createnotification div.panel_3 a#ALL').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
			
			$('div#createnotification div.panel_3 div.content_listing a.selected').each(function()
			{
				option[count++] = $(this).attr('id');
			});
		}
		
		if(count > 0)
		{
			$('div#createnotification a[function="save"]:first').attr('panel', '3').removeClass('disabled_create_notification');
		}
		
		else
		{
			$('div#createnotification a[function="save"]:first').attr('panel', 'disabled').addClass('disabled_create_notification');
		}
		
		//Populate the hidden tenant ids field
		$('div#createnotification div.panel_1 input[name="tenant_ids"]:first').val(option);
		//End populate the tenant ids fields
	});
	
	$('div#createnotification div.panel_1 span.priority a.listitem_small').click(function(){
		
		if(!$(this).hasClass('selected'))
		{
			var id = $(this).attr('id');
		
			$(this).addClass('selected');
			$('div#createnotification div.panel_1 span.priority a[id!="'+id+'"]').removeClass('selected');
		
			//notification_delivery_details_text();
		}
	});
	
	$('div#createnotification div.panel_1 span.send a.listitem_small').click(function(){
		var id = $(this).attr('id');
		
		$(this).addClass('selected');
		$('div#createnotification div.panel_1 span.send a[id!="'+id+'"]').removeClass('selected');														
		
		if(id == 'SCHEDULE')
		{
			$('div#createnotification div.panel_1 span.send_by:first').show();
			$('div#createnotification div.savecancelbottombuttons a[function="save"]:first').text('Schedule');
		}
		
		else
		{
			$('div#createnotification div.panel_1 span.send_by:first').hide();
			$('div#createnotification div.savecancelbottombuttons a[function="save"]:first').text('Send Now');
		}
	});
	
	$('div#createnotification a.back').click(function(){
		var current_panel = $(this).attr('panel');
		
		if(current_panel == '2')
		{
			$(this).hide().removeAttr('panel');
			
			var mode = $('div#createnotification a[function="save"]:first').attr('mode');
			
			if(mode == 'create')
			{
				$('div#createnotification h3:first').html('Create Notification');
			}
			
			else
			{
				$('div#createnotification h3:first').html('Edit Notification');
			}
			
			$('div#createnotification a[function="next"]:first').hide();
			$('div#createnotification div[class="panel_2"]').hide();
			$('div#createnotification div[class="panel_3"]').hide();
			$('div#createnotification div[class="panel_1"]:first').show();
			$('div#createnotification a[function="save"]:first').show().removeAttr('panel');
			$('div#createnotification a[function="close"]:first').show();
			//notification_delivery_details_text();
		}
		
		else if(current_panel == '3')
		{
			//Viewing building list panel
			$(this).show().attr('panel', '2');
			
			$('div#createnotification h3:first').html('Step 1: Select Buildings');
			$('div#createnotification div[class="panel_3"]').hide();
			$('div#createnotification a[function="save"]:first').hide();
			$('div#createnotification div[class="panel_2"]:first').show();
			$('div#createnotification a[function="next"]:first').show();
			//notification_delivery_details_text();
		}
		
		else
		{
			alert('An error has occurred');	
		}
	});
	//End tenant details create notification navigation
	//End original create notification logic
	
	
	
	
	
	//Copy Create Notification Logic, mimicry of original create notification logic
	$('a[id="#copycreatenotification"]:first').click(function(){
		opendialog('#copycreatenotification');												   
	});
	
	$('div#copycreatenotification div.panel_2 input[name="search_buildings"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#copycreatenotification div.panel_2 span.building_message').html('').hide();
			$('div#copycreatenotification div.panel_2 a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#copycreatenotification div.panel_2 a').each(function()
			{
				
				var id = $(this).attr('id');
				var building_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = building_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#copycreatenotification div.panel_2 a[show="no"]').hide();
			$('div#copycreatenotification div.panel_2 a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#copycreatenotification div.panel_2 span.building_message').html('No buildings found').show();
				$('div#copycreatenotification div.panel_2 a#ALL').hide();
			}
			
			else
			{
				$('div#copycreatenotification div.panel_2 span.building_message').html('').hide();
				$('div#copycreatenotification div.panel_2 a#ALL').show();
			}
		}
	});
	
	$('div#copycreatenotification div.panel_3 input[name="search"]:first').keypress(function(e){
		var animate = $('div#copycreatenotification div.panel_3 span#spinnerbox:first').attr('animate');
		var value = $(this).val();
		
		if(animate == 'off')
		{
			$('div#copycreatenotification div.panel_3 span#spinnerbox:first').show().attr('animate', 'on');
		}
		
		if((value == '')&&(e.keyCode == 8))
		{
			$('div#copycreatenotification div.panel_3 span#spinnerbox:first').hide().attr('animate', 'off');
		}
	});
	
	//Autocomplete for tenant search in create notification dialog
	$('div#copycreatenotification div.panel_3 input[name="search"]:first').autocomplete({
		source: function(request, response)
		{
			var building_id = $('div#copycreatenotification div.panel_2 a.selected:first').attr('id');
			var selected_building_ids = Array();
			
			if(building_id == 'ALL')
			{
				//Don't do anything
			}
			
			else
			{
				$('div#copycreatenotification div.panel_2 a.selected').each(function()
				{
					var building_id = $(this).attr('id');
					selected_building_ids.push(building_id);
				});
			}
			
			$.ajax(
			{
				url: protocol+domain+'/mobile/tenant/ajax_create_notification_get_tenants',
				data: {
						'building_id' : selected_building_ids,
						'term' : request.term
					  },
				type: "POST",  // a jQuery ajax POST transmits in querystring format in utf-8
				dataType: "json",   //return data in json format
				
				success: function(data)
				{
					$('div#copycreatenotification div.panel_3 span#spinnerbox:first').hide().attr('animate', 'off');
					
					if(data.status == 'success')
					{
						if((data.message == '')||(data.message == 'No units found'))
						{
							$('div#copycreatenotification div.panel_3 div.innercontent div.content_listing:first').html('<span style="padding-left:10px;">'+data.message+'<span>');
							$('div#copycreatenotification div.panel_3 a#ALL:first').hide();
						}
						
						else
						{
							$('div#copycreatenotification div.panel_3 div.innercontent div.content_listing:first').html('').append(data.message);
							$('div#copycreatenotification div.panel_3 a#ALL:first').show();
							
							//Set selected options
							var option = $('div#copycreatenotification div.panel_1 input[name="tenant_ids"]:first').val();
							var pieces = option.split(",");
							
							if(pieces.length)
							{
								for(var i=0;i<pieces.length;i++)
								{
									$('div#copycreatenotification div.panel_3 a[id="'+pieces[i]+'"]:first').addClass('selected');
								}
							}
							//End set selected options
						}
					}
				}
			});
		},
		
		minLength: 0,
		delay: 500
	});
	//End autocomplete
	
	//Tenant details create notification navigation
	$('div#copycreatenotification div.panel_1 a.listitem').click(function(){
		var id = $(this).attr('id');
		var count = 0;
		
		if(id == 'BUILDING')
		{
			$('div#copycreatenotification div.panel_2 a.selected').each(function()
			{
				var id = $(this).attr('id');
				
				if(id !== 'ALL')
				{
					count++;
				}
			});
			
			if(count > 0)
			{
				$('div#copycreatenotification a[function="next"]:first').removeClass('disabled_create_notification');
			}
			
			else
			{
				$('div#copycreatenotification a[function="next"]:first').addClass('disabled_create_notification');
			}
			
			$('div#copycreatenotification h3:first').html('Step 1: Select Buildings');
			$('div#copycreatenotification a[function="close"]:first').hide();
			$('div#copycreatenotification a[function="save"]:first').hide();
			$('div#copycreatenotification div.panel_1:first').hide();
			$('div#copycreatenotification div.panel_2:first').show();
			$('div#copycreatenotification a[function="next"]:first').show();
			$('div#copycreatenotification a.back:first').attr('panel', '2').show();
		}
	});
	
	$('div#copycreatenotification div.panel_2 a.listitem').click(function(){
		var id = $(this).attr('id');
		var count = 0;
		var search_heading_text = '';
		
		if(id == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#copycreatenotification div.panel_2 a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#copycreatenotification div.panel_2 a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div#copycreatenotification div.panel_2 a[id="ALL"]:first').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
			
		//Change the "Select Recipients" text option in panel 1
		$('div#copycreatenotification div.panel_2 a.selected').each(function()
		{
			var id = $(this).attr('id');
			
			if(id !== 'ALL')
			{
				++count;
				var building_name = $(this).text();
				
				if(count == 1)
				{
					search_heading_text = $(this).text();
				}
				
				else
				{
					search_heading_text = count+' buildings';
				}
			}
		});
		
		if(count > 0)
		{
			$('div#copycreatenotification a[function="next"]:first').removeClass('disabled_create_notification');
		}
		
		else
		{
			$('div#copycreatenotification a[function="next"]:first').addClass('disabled_create_notification');
		}
	});
	
	$('div#copycreatenotification a[function="next"]:first').click(function(){
		var term = '';
		var selected_building_ids = Array();
		var count = 0;
		
		$('div#copycreatenotification div.panel_2 a.selected').each(function()
		{
			var building_id = $(this).attr('id');
			selected_building_ids.push(building_id);
			count++;
		});
		
		if(count > 0)
		{
			$('div#copycreatenotification a[function="save"]:first').text('Save');
			
			$('div#copycreatenotification h3:first').html('Step 2: Select Units');
			
			$(this).hide();
			$('div#copycreatenotification div.panel_3 div.innercontent div.content_listing:first').html('');
			
			$.post("/mobile/tenant/ajax_create_notification_get_tenants/", {'building_id' : selected_building_ids, 'term' : term}, function(data){
				if(data.status == 'success')
				{
					var count = 0;
					
					$('div#copycreatenotification div.panel_3 div.innercontent div.content_listing:first').append(data.message);
					
					if($('div#copycreatenotification div.panel_3 div.innercontent a[id="ALL"]:first').hasClass('selected'))
					{
						$('div#copycreatenotification div.panel_3 div.content_listing a.listitem').addClass('selected');
						
						$('div#copycreatenotification div.panel_3 div.content_listing a.selected').each(function()
						{
							count++;
						});
					}
					
					else
					{
						//Set selected options
						var option = $('div#copycreatenotification div.panel_1 input[name="tenant_ids"]:first').val();
						var pieces = option.split(",");
						
						if(pieces.length)
						{
							for(var i=0;i<pieces.length;i++)
							{
								$('div#copycreatenotification div.panel_3 a[id="'+pieces[i]+'"]:first').addClass('selected');
							}
						}
						//End set selected options
						
						$('div#copycreatenotification div.panel_3 div.content_listing a.selected').each(function()
						{
							count++;
						});
					}
							
					if(count == 0)
					{
						//No one selected, save won't work
						$('div#copycreatenotification a[function="save"]:first').attr('panel', 'disabled').addClass('disabled_create_notification').show();
					}
					
					else
					{
						//Someone selected, save will work
						$('div#copycreatenotification a[function="save"]:first').attr('panel', '3').removeClass('disabled_create_notification').show();
					}
					
					$('div#copycreatenotification div.panel_1:first').hide();
					$('div#copycreatenotification div.panel_2:first').hide();
					$('div#copycreatenotification div.panel_3:first').show();
					$('div#copycreatenotification a.back:first').attr('panel', '3').show();
				}
				
				else
				{
					if(typeof(data.message) !== 'undefined')
					{
						alert(data.message);
					}
					
					else
					{
						alert('An error has occurred');
					}
					
					$('div#copycreatenotification a[function="next"]:first').show();
				}
			}, 'json');
		}
		
		else
		{
			alert('Please choose a building');	
		}
	});
	
	$('div#copycreatenotification div.panel_3 a.listitem').live('click', function(){
		var id = $(this).attr('id');
		var option = Array();
		var count = 0;
		
		if(id == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
				$('div#copycreatenotification div.panel_3 div.content_listing a.listitem').removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
				$('div#copycreatenotification div.panel_3 div.content_listing a.listitem').addClass('selected');
				
				$('div#copycreatenotification div.panel_3 div.content_listing a.selected').each(function()
				{
					option[count++] = $(this).attr('id');
				});
			}
		}
		
		else
		{
			$('div#copycreatenotification div.panel_3 a#ALL').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
			
			$('div#copycreatenotification div.panel_3 div.content_listing a.selected').each(function()
			{
				option[count++] = $(this).attr('id');
			});
		}
		
		if(count > 0)
		{
			$('div#copycreatenotification a[function="save"]:first').attr('panel', '3').removeClass('disabled_create_notification');
		}
		
		else
		{
			$('div#copycreatenotification a[function="save"]:first').attr('panel', 'disabled').addClass('disabled_create_notification');
		}
		
		//Populate the hidden tenant ids field
		$('div#copycreatenotification div.panel_1 input[name="tenant_ids"]:first').val(option);
		//End populate the tenant ids fields
	});
	
	$('div#copycreatenotification div.panel_1 span.priority a.listitem_small').click(function(){
		
		if(!$(this).hasClass('selected'))
		{
			var id = $(this).attr('id');
		
			$(this).addClass('selected');
			$('div#copycreatenotification div.panel_1 span.priority a[id!="'+id+'"]').removeClass('selected');
		
			//notification_delivery_details_text();
		}
	});
	
	$('div#copycreatenotification div.panel_1 span.send a.listitem_small').click(function(){
		var id = $(this).attr('id');
		
		$(this).addClass('selected');
		$('div#copycreatenotification div.panel_1 span.send a[id!="'+id+'"]').removeClass('selected');														
		
		if(id == 'SCHEDULE')
		{
			$('div#copycreatenotification div.panel_1 span.send_by:first').show();
			$('div#copycreatenotification div.savecancelbottombuttons a[function="save"]:first').text('Schedule');
		}
		
		else
		{
			$('div#copycreatenotification div.panel_1 span.send_by:first').hide();
			$('div#copycreatenotification div.savecancelbottombuttons a[function="save"]:first').text('Send Now');
		}
	});
	
	$('div#copycreatenotification a.back').click(function(){
		var current_panel = $(this).attr('panel');
		
		if(current_panel == '2')
		{
			$(this).hide().removeAttr('panel');
			
			var mode = $('div#copycreatenotification a[function="save"]:first').attr('mode');
			
			if(mode == 'create')
			{
				$('div#copycreatenotification h3:first').html('Create Notification');
			}
			
			else
			{
				$('div#copycreatenotification h3:first').html('Edit Notification');
			}
			
			$('div#copycreatenotification a[function="next"]:first').hide();
			$('div#copycreatenotification div[class="panel_2"]').hide();
			$('div#copycreatenotification div[class="panel_3"]').hide();
			$('div#copycreatenotification div[class="panel_1"]:first').show();
			$('div#copycreatenotification a[function="save"]:first').show().removeAttr('panel');
			$('div#copycreatenotification a[function="close"]:first').show();
			//notification_delivery_details_text();
		}
		
		else if(current_panel == '3')
		{
			//Viewing building list panel
			$(this).show().attr('panel', '2');
			
			$('div#copycreatenotification h3:first').html('Step 1: Select Buildings');
			$('div#copycreatenotification div[class="panel_3"]').hide();
			$('div#copycreatenotification a[function="save"]:first').hide();
			$('div#copycreatenotification div[class="panel_2"]:first').show();
			$('div#copycreatenotification a[function="next"]:first').show();
			//notification_delivery_details_text();
		}
		
		else
		{
			alert('An error has occurred');	
		}
	});
	//End copy create notification logic
	
	
	
	
	
	//Modal window navigation, auto-selected logic, and change report link
	//Change report link
	$('div[id="changereport"] a.listitem').click(function(){
		var url = $(this).attr('rel');
		
		if((typeof(url) !== 'undefined')&&(url !== ''))
		{
			window.location = url;
		}
		
		else
		{
			alert('coming soon');	
		}
	});
	//End change report link
	
	//Modal window navigation, auto-selected logic, and change report link
	//Change report link
	$('div[id="changeadvancedreport"] a.listitem').click(function(){
		var url = $(this).attr('rel');
		
		if((typeof(url) !== 'undefined')&&(url !== ''))
		{
			window.location = url;
		}
		
		else
		{
			alert('coming soon');	
		}
	});
	//End change report link
	
	//Back button navigation
	$('div[id="reportfilterbuilding_multi_menu"] a.back:first').click(function(){
		var current_page = $(this).attr('id');
		
		switch(current_page)
		{
			case 'filter_building_display':
				$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_options_display"]').show();
			break;
			
			case 'filter_employee_display':
				$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_options_display"]').show();
			break;
			
			case 'filter_regional_manager_display':
				$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_options_display"]').show();
			break;
			
			case 'filter_svp_display':
				$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', '').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"]').hide();
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_options_display"]').show();
			break;
			
			default:
			  alert('An error has occurred');
		}
	});
	
	$('div[id="reportfiltercategory_multi"] a.back:first').click(function(){
		$(this).hide();
		$('div#child_category_display').hide();
		$('div#parent_category_display').show();
		
		if($('a[dialog="#reportfiltercategory_multi"]').length > 0)
		{
			initialize_categories('#reportfiltercategory_multi');
		}
		
		else
		{
			initialize_categories('#reportfiltercategory');
		}
		
	});
	//End back button
	
	//Filter options listener for aging summary and resident satisfaction
	$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_options_display"] a.listitem').click(function(){
		var rel = $(this).attr('rel');
		
		$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_options_display"]').slideUp('fast');
		
		if(rel == 'building')
		{
			//Set selected options
			var type = $('a[dialog="'+dialog+'"]:first').attr('rel');
			var option = $('a[dialog="'+dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"]').show();
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"] a.selected').removeClass('selected');
			
			if(option == 'ALL')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"] a[class="listitem"][rel="'+type+'"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"] a[id="'+pieces[i]+'"][rel="'+type+'"]:first').addClass('selected');
				}
			}
			//End set selected options
			
			$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', 'filter_building_display').show();
			$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', 'filter_building_display').show();
		}
		
		else if(rel == 'employee')
		{
			//Set selected options
			var type = $('a[dialog="'+dialog+'"]:first').attr('rel');
			var option = $('a[dialog="'+dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"]').show();
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"] a.selected').removeClass('selected');
			
			if(option == 'ALL')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"] a[class="listitem"][rel="'+type+'"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"] a[id="'+pieces[i]+'"][rel="'+type+'"]:first').addClass('selected');
				}
			}
			//End set selected options
			
			$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', 'filter_employee_display').show();
			$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', 'filter_employee_display').show();
		}
		
		else if(rel == 'regional_manager')
		{
			//Set selected options
			var type = $('a[dialog="'+dialog+'"]:first').attr('rel');
			var option = $('a[dialog="'+dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"]').show();
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"] a.selected').removeClass('selected');
			
			if(option == 'ALL')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"] a[class="listitem"][rel="'+type+'"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"] a[id="'+pieces[i]+'"][rel="'+type+'"]:first').addClass('selected');
				}
			}
			//End set selected options
			
			$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', 'filter_regional_manager_display').show();
			$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', 'filter_regional_manager_display').show();
		}
		
		else if(rel == 'svp')
		{
			//Set selected options
			var type = $('a[dialog="'+dialog+'"]:first').attr('rel');
			var option = $('a[dialog="'+dialog+'"]:first').attr('option');
			var pieces = option.split(",");
			
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"]').show();
			$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"] a.selected').removeClass('selected');
			
			if(option == 'ALL')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"] a[class="listitem"][rel="'+type+'"]').addClass('selected');
			}
			
			else if(pieces.length)
			{
				for(var i=0;i<pieces.length;i++)
				{
					$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"] a[id="'+pieces[i]+'"][rel="'+type+'"]:first').addClass('selected');
				}
			}
			//End set selected options
			
			$('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id', 'filter_svp_display').show();
			$('div[id="reportfilterbuilding_multi_menu"] a.back').attr('id', 'filter_svp_display').show();
		}
		
		else
		{
			alert('An error has occurred');
		}
	});
	//End options listener
	
	//Building filter click listener for aging summary and resident satisfaction
	$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_employee_display"] a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_employee_display"] a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div[id="reportfilterbuilding_multi_menu"] a[id="ALL"]').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
				$('div[id="reportfilterbuilding_multi_menu"] a[rel!="'+rel+'"]').removeClass('selected');
			}
		}
		
		return false;
	});
	//End building filter click listener
	
	//Building filter click listener for aging summary and resident satisfaction
	$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_building_display"] a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_building_display"] a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div[id="reportfilterbuilding_multi_menu"] a[id="ALL"]').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
				$('div[id="reportfilterbuilding_multi_menu"] a[rel!="'+rel+'"]').removeClass('selected');
			}
		}
		
		return false;
	});
	//End building filter click listener
	
	//Category filter click listener for aging summary and resident satisfaction
	$('div[id="reportfiltercategory"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfiltercategory a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfiltercategory a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div#reportfiltercategory a[id="ALL"]').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
		
		return false;
	});
	//End category filter click listener
	
	//Category filter click listener for aging summary, resident satisfaction, and maintenance category
	$('div[id="reportfiltercategory_multi"] a.listitem').live('click', function(){
		var parent_div = $(this).parent('div').attr('id');
		
		if(parent_div != undefined)
		{
			if(parent_div == 'parent_category_display')
			{
				if($(this).attr('id') == 'ALL')
				{
					if($(this).hasClass('selected'))
					{
						$('div#reportfiltercategory_multi div#parent_category_display a').removeClass('selected');
						
						//Remove all options
						$('a[dialog="#reportfiltercategory_multi"]').attr('option', '');
					}
					
					else
					{
						$('div#reportfiltercategory_multi div#parent_category_display a').addClass('selected');
						
						//Select all options
						var all_categories = $('input[name="all_child_category_ids"]').val();
					
						$('a[dialog="#reportfiltercategory_multi"]').attr('option', all_categories);
					}
				}
				
				else
				{
					var postvars = {
						category_id: $(this).attr('parent_ids')
					};
					
					/*//Should only listen when clicked save
					var parent_all_selected = ($('div[id="reportfiltercategory_multi"] div#parent_category_display a.listitem#ALL').hasClass('selected') ? '1' : '0');*/
					
					//Placeholder variable that may not be needed pending further development
					var parent_all_selected = '0';
					
					//Ajax call to get children
					$.post("/mobile/reports/ajax_get_child_categories", postvars, function(data){
						$('div#parent_category_display').hide();
						$('div#reportfiltercategory_multi a.back').show();
						
						if((data.status == 'success')&&(data.html != ''))
						{
							$('div#child_category_display').show();
							$('div#child_category_listing').html('');
							$('div#child_category_listing').html(data.html);
							
							initialize_child_categories('#reportfiltercategory_multi', parent_all_selected);
						}
						
						else
						{
							$('span.category_message').show().text(data.message).fadeOut(3000);
						}
					}, 'json');
				}
			}
				
			else if((parent_div == 'child_category_display')||(parent_div == 'child_category_listing'))
			{
				var option = $(this).attr('id');
				var rel = $(this).attr('rel');
				
				//Remove parent ALL category selection
				$('div[id="reportfiltercategory_multi"] div#parent_category_display a.listitem#ALL').removeClass('selected');
				
				if(option == 'ALL')
				{
					if($(this).hasClass('selected'))
					{
						$('div#child_category_display a.listitem').removeClass('selected');
					}
					
					else
					{
						$('div#child_category_display a.listitem').addClass('selected');
					}
				}
				
				else
				{
					$('div#child_category_display a[id="ALL"]').removeClass('selected');
					
					if($(this).hasClass('selected'))
					{
						$(this).removeClass('selected');
					}
					
					else
					{
						$(this).addClass('selected');
					}
				}
			}
		}
		
		return false;
	});
	//End category filter click listener
	
	//Regional Manager filter click listener
	$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_regional_manager_display"] a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_regional_manager_display"] a.listitem').addClass('selected');
			}
		}
		
		else
		{
			//Select one at a time
			if($(this).hasClass('selected'))
			{
				//Do nothing
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_regional_manager_display"] a.listitem').removeClass('selected');
				$(this).addClass('selected');
			}
			//End select one at a time
			
			/*Original logic to select multiple options
			$('div[id="reportfilterbuilding_multi_menu"] a[id="ALL"]').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
				$('div[id="reportfilterbuilding_multi_menu"] a[rel!="'+rel+'"]').removeClass('selected');
			}
			*/
		}
		
		return false;
	});
	//End Regional Manager filter click listener
	
	//SVP filter click listener
	$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_svp_display"] a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_svp_display"] a.listitem').addClass('selected');
			}
		}
		
		else
		{
			//Select one at a time
			if($(this).hasClass('selected'))
			{
				//Do nothing
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div[id="filter_svp_display"] a.listitem').removeClass('selected');
				$(this).addClass('selected');
			}
			//End select one at a time
			
			/*Original logic to select multiple options
			$('div[id="reportfilterbuilding_multi_menu"] a[id="ALL"]').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
				$('div[id="reportfilterbuilding_multi_menu"] a[rel!="'+rel+'"]').removeClass('selected');
			}
			*/
		}
		
		return false;
	});
	//End SVP filter click listener
	
	//Status listener for aging summary
	$('div[id="reportfilterstatus_requests"] a.listitem').click(function(){
		var option = $(this).attr('id');
		
		$(this).addClass('selected');
		$('div[id="reportfilterstatus_requests"] a[id!="'+option+'"]').removeClass('selected');
		
		var option = $('div[id="reportfilterstatus_requests"] a.selected:first').attr('id');
			
		$('a[dialog="#reportfilterstatus_requests"]:first').attr('option', option).text(option);
		$('input[type="hidden"][name="status"]').val(option);
			
		closedialog();
		
		return false;
	});
	//End status listener
	
	//Interval listener
	$('div[id="reportfilterinterval"] a.listitem').click(function(){
		var option = $(this).attr('id');
		
		$(this).addClass('selected');
		$('div[id="reportfilterinterval"] a[id!="'+option+'"]').removeClass('selected');
		
		var option = $('div[id="reportfilterinterval"] a.selected:first').attr('id');
			
		$('a[dialog="#reportfilterinterval"]:first').attr('option', option).text(option);
		$('input[type="hidden"][name="interval"]').val(option);
		
		closedialog();
		
		return false;
	});
	//End interval listener
	
	//Show all criteria logic
	$('span.show_all_criteria').live('click', function(){
		var show = $(this).attr('show');
		
		if(show == '1')
		{
			$('p.filter_criteria_list:first').hide();
			$('p.filter_criteria:first').show();
		}
		
		else
		{
			$('p.filter_criteria:first').hide();
			$('p.filter_criteria_list:first').show();
		}
	});
	//End show all
	
	//Status listener for resident activity
	$('div[id="reportfilterstatus_residents"] a.listitem').click(function(){
		var option = $(this).attr('id');
		
		$(this).addClass('selected');
		$('div[id="reportfilterstatus_residents"] a[id!="'+option+'"]').removeClass('selected');
		
		var option = $('div[id="reportfilterstatus_residents"] a.selected:first').attr('id');
			
		$('a[dialog="#reportfilterstatus_residents"]:first').attr('option', option).text(option);
		$('input[type="hidden"][name="status"]').val(option);
			
		closedialog();
		
		return false;
	});
	//End status listener
	
	//Login listener for resident activity and resident moveout
	$('div[id="reportfilterlogin"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var text = $(this).text();
		
		if(option == 'ALL')
		{
			$(this).addClass('selected');
			$('div[id="reportfilterlogin"] a[id!="'+option+'"]').removeClass('selected');
		}
		
		else
		{
			$(this).addClass('selected');
			$('div[id="reportfilterlogin"] a[id="ALL"]').removeClass('selected');
			$('div[id="reportfilterlogin"] a[id!="'+option+'"]').removeClass('selected');
		}
		
		$('a[dialog="#reportfilterlogin"]:first').attr('option', option).text(text);
		$('input[type="hidden"][name="login_status"]').val(option);
		
		closedialog();
		
		return false;
	});
	//End status listener
	
	//Building filter click listener for resident activity and resident moveout
	$('div[id="reportfilterbuilding_multi"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfilterbuilding_multi div.innercontent a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfilterbuilding_multi div.innercontent a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div[id="reportfilterbuilding_multi"] a[id="ALL"]').removeClass('selected');
		
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
		
		return false;
	});
	//End building filter click listener
	
	//Exclude filter click listener
	$('div[id="reportfilterexclude"] a.listitem').click(function(){
		var option = $(this).attr('id');
	
		if(option == 'NONE')
		{
			$('div#reportfilterexclude div.innercontent a.listitem').removeClass('selected');
			$(this).addClass('selected');
		}
		
		else
		{
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
			
			if(!$('div#reportfilterexclude div.innercontent a.listitem.selected').length)
			{
				$('div#reportfilterexclude div.innercontent a.listitem#NONE').addClass('selected');
			}
			
			else
			{
				$('div#reportfilterexclude div.innercontent a.listitem#NONE').removeClass('selected');
			}
		}
		
		return false;
	});
	
	//Hours open filter click listener
	$('div[id="reportfilterhours_open"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var text = $(this).text();
	
		if(option == 'ALL')
		{
			$('div#reportfilterhours_open div.innercontent a.listitem').addClass('selected');
		}
		
		else
		{
			$('div#reportfilterhours_open div.innercontent a.listitem').removeClass('selected');
			$(this).addClass('selected');
		}
		
		$('a[dialog="#reportfilterhours_open"]:first').attr('option', option).text(text);
		$('input[type="hidden"][name="hours_open"]').val(option);
		
		closedialog();
			
		return false;
	});
	
	//Building filter click listener for resident activity and resident moveout
	$('div[id="reportfilteremployee"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfilteremployee div.innercontent a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfilteremployee div.innercontent a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div[id="reportfilteremployee"] a[id="ALL"]').removeClass('selected');
		
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
		
		return false;
	});
	//End building filter click listener
	
	//Vendor filter click listener
	$('div[id="reportfiltervendor"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfiltervendor div.innercontent a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfiltervendor div.innercontent a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div[id="reportfiltervendor"] a[id="ALL"]').removeClass('selected');
		
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
		
		return false;
	});
	//End vendor filter click listener
	
	//Inventory group filter click listener
	$('div[id="reportfilterinventorygroup"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var rel = $(this).attr('rel');
		
		if(option == 'ALL')
		{
			if($(this).hasClass('selected'))
			{
				$('div#reportfilterinventorygroup div.innercontent a.listitem').removeClass('selected');
			}
			
			else
			{
				$('div#reportfilterinventorygroup div.innercontent a.listitem').addClass('selected');
			}
		}
		
		else
		{
			$('div[id="reportfilterinventorygroup"] a[id="ALL"]').removeClass('selected');
		
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
		
		return false;
	});
	//End inventory group filter click listener
	
	$('div#reportfiltervendor div.innercontent input[name="search_vendors"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfiltervendor div.innercontent span.vendor_message').html('').hide();
			$('div#reportfiltervendor div.innercontent a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfiltervendor div.innercontent a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var vendor_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = vendor_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfiltervendor div.innercontent a[show="no"]').hide();
			$('div#reportfiltervendor div.innercontent a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfiltervendor div.innercontent span.vendor_message').html('No vendors found').show();
				$('div#reportfiltervendor div.innercontent a#ALL').hide();
			}
			
			else
			{
				$('div#reportfiltervendor div.innercontent span.vendor_message').html('').hide();
				$('div#reportfiltervendor div.innercontent a#ALL').show();
			}
		}
	});
	
	$('div#reportfilterinventorygroup div.innercontent input[name="search_groups"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfilterinventorygroup div.innercontent span.groups_message').html('').hide();
			$('div#reportfilterinventorygroup div.innercontent a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfilterinventorygroup div.innercontent a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var vendor_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = vendor_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfilterinventorygroup div.innercontent a[show="no"]').hide();
			$('div#reportfilterinventorygroup div.innercontent a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfilterinventorygroup div.innercontent span.groups_message').html('No vendors found').show();
				$('div#reportfilterinventorygroup div.innercontent a#ALL').hide();
			}
			
			else
			{
				$('div#reportfilterinventorygroup div.innercontent span.groups_message').html('').hide();
				$('div#reportfilterinventorygroup div.innercontent a#ALL').show();
			}
		}
	});
	
	$('div#reportfilterbuilding_multi div.innercontent input[name="search_buildings"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfilterbuilding_multi div.innercontent span.building_message').html('').hide();
			$('div#reportfilterbuilding_multi div.innercontent a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfilterbuilding_multi div.innercontent a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var building_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = building_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfilterbuilding_multi div.innercontent a[show="no"]').hide();
			$('div#reportfilterbuilding_multi div.innercontent a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfilterbuilding_multi div.innercontent span.building_message').html('No buildings found').show();
				$('div#reportfilterbuilding_multi div.innercontent a#ALL').hide();
			}
			
			else
			{
				$('div#reportfilterbuilding_multi div.innercontent span.building_message').html('').hide();
				$('div#reportfilterbuilding_multi div.innercontent a#ALL').show();
			}
		}
	});
	
	$('div#reportfilteremployee div.innercontent input[name="search_employees"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfilteremployee div.innercontent span.employee_message').html('').hide();
			$('div#reportfilteremployee div.innercontent a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfilteremployee div.innercontent a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var employee_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = employee_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfilteremployee div.innercontent a[show="no"]').hide();
			$('div#reportfilteremployee div.innercontent a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfilteremployee div.innercontent span.employee_message').html('No employees found').show();
				$('div#reportfilteremployee div.innercontent a#ALL').hide();
			}
			
			else
			{
				$('div#reportfilteremployee div.innercontent span.employee_message').html('').hide();
				$('div#reportfilteremployee div.innercontent a#ALL').show();
			}
		}
	});
	
	$('div#reportfiltercategory div.innercontent input[name="search_categories"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfiltercategory div.innercontent span.category_message').html('').hide();
			$('div#reportfiltercategory div.innercontent a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfiltercategory div.innercontent a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var category_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = category_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfiltercategory div.innercontent a[show="no"]').hide();
			$('div#reportfiltercategory div.innercontent a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfiltercategory div.innercontent span.category_message').html('No categories found').show();
				$('div#reportfiltercategory div.innercontent a#ALL').hide();
			}
			
			else
			{
				$('div#reportfiltercategory div.innercontent span.category_message').html('').hide();
				$('div#reportfiltercategory div.innercontent a#ALL').show();
			}
		}
	});
	
	$('div#reportfiltercategory_multi div#child_category_display input[name="search_categories"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfiltercategory_multi div#child_category_display span.category_message').html('').hide();
			$('div#reportfiltercategory_multi div#child_category_display a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfiltercategory_multi div#child_category_display a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var category_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = category_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfiltercategory_multi div#child_category_display a[show="no"]').hide();
			$('div#reportfiltercategory_multi div#child_category_display a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfiltercategory_multi div#child_category_display span.category_message').html('No categories found').show();
				$('div#reportfiltercategory_multi div#child_category_display a#ALL').hide();
			}
			
			else
			{
				$('div#reportfiltercategory_multi div#child_category_display span.category_message').html('').hide();
				$('div#reportfiltercategory_multi div#child_category_display a#ALL').show();
			}
		}
	});
	
	function propagate_default_employee_selection()
	{
		$('div#employees_assigned_to_building div.innercontent a:[employees_id]').each(function()
		{
			if(($(this).hasClass('selected'))&&($(this).is(':visible')))
			{
				$(this).next('span#default_employee_selection').show();
			}
			
			else
			{
				$(this).next('span#default_employee_selection').hide();
			}
		});
	}
	
	$('div#employees_assigned_to_building div.innercontent input[name="search_employees"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#employees_assigned_to_building div.innercontent span.employee_message').html('').hide();
			$('div#employees_assigned_to_building div.innercontent a:[employees_id]').show().attr('show', 'yes');
			propagate_default_employee_selection();
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#employees_assigned_to_building div.innercontent a#all_employees_element').hide().attr('show', 'no');
			
			$('div#employees_assigned_to_building div.innercontent a:[employees_id]').each(function()
			{
				var id = $(this).attr('id');
				var employee_name = $(this).text();
				
				if(id != 'all_employees_element')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = employee_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#employees_assigned_to_building div.innercontent a[show="no"]').hide();
			$('div#employees_assigned_to_building div.innercontent a[show="yes"]').show();
			propagate_default_employee_selection();
			
			if(no_count == count)
			{
				$('div#employees_assigned_to_building div.innercontent span.employee_message').html('No employees found').show();
			}
			
			else
			{
				$('div#employees_assigned_to_building div.innercontent span.employee_message').html('').hide();
			}
		}
	});
	
	$('div#reportfilterbuilding_multi_menu div#filter_building_display input[name="search_buildings"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfilterbuilding_multi_menu div#filter_building_display span.building_message').html('').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_building_display a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfilterbuilding_multi_menu div#filter_building_display a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var building_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = building_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfilterbuilding_multi_menu div#filter_building_display a[show="no"]').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_building_display a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfilterbuilding_multi_menu div#filter_building_display span.building_message').html('No buildings found').show();
				$('div#reportfilterbuilding_multi_menu div#filter_building_display a#ALL').hide();
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div#filter_building_display span.building_message').html('').hide();
				$('div#reportfilterbuilding_multi_menu div#filter_building_display a#ALL').show();
			}
		}
	});
	
	$('div#reportfilterbuilding_multi_menu div#filter_employee_display input[name="search_employees"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfilterbuilding_multi_menu div#filter_employee_display span.employee_message').html('').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_employee_display a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfilterbuilding_multi_menu div#filter_employee_display a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var employee_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = employee_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfilterbuilding_multi_menu div#filter_employee_display a[show="no"]').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_employee_display a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfilterbuilding_multi_menu div#filter_employee_display span.employee_message').html('No employees found').show();
				$('div#reportfilterbuilding_multi_menu div#filter_employee_display a#ALL').hide();
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div#filter_employee_display span.employee_message').html('').hide();
				$('div#reportfilterbuilding_multi_menu div#filter_employee_display a#ALL').show();
			}
		}
	});
	
	$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display input[name="search_regional_managers"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display span.regional_manager_message').html('').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var manager_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = manager_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display a[show="no"]').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display span.regional_manager_message').html('No managers found').show();
				$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display a#ALL').hide();
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display span.regional_manager_message').html('').hide();
				$('div#reportfilterbuilding_multi_menu div#filter_regional_manager_display a#ALL').show();
			}
		}
	});
	
	$('div#reportfilterbuilding_multi_menu div#filter_svp_display input[name="search_svp"]:first').keyup(function(){
		var value = $(this).val();
		
		if(value == '')
		{
			$('div#reportfilterbuilding_multi_menu div#filter_svp_display span.svp_message').html('').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_svp_display a').show().attr('show', 'yes');
		}
		
		else
		{
			var count = 0;
			var no_count = 0;
			
			$('div#reportfilterbuilding_multi_menu div#filter_svp_display a[id!="ALL"]').each(function()
			{
				var id = $(this).attr('id');
				var svp_name = $(this).text();
				
				if(id != 'ALL')
				{
					count++;
					
					var compare = new RegExp(value, "gi");
					compare = svp_name.match(compare);
					
					if(compare != null)
					{
						$(this).attr('show', 'yes');
					}
					
					else
					{
						$(this).attr('show', 'no');
						no_count++;
					}
				}
			});
			
			$('div#reportfilterbuilding_multi_menu div#filter_svp_display a[show="no"]').hide();
			$('div#reportfilterbuilding_multi_menu div#filter_svp_display a[show="yes"]').show();
			
			if(no_count == count)
			{
				$('div#reportfilterbuilding_multi_menu div#filter_svp_display span.svp_message').html('No SVP found').show();
				$('div#reportfilterbuilding_multi_menu div#filter_svp_display a#ALL').hide();
			}
			
			else
			{
				$('div#reportfilterbuilding_multi_menu div#filter_svp_display span.svp_message').html('').hide();
				$('div#reportfilterbuilding_multi_menu div#filter_svp_display a#ALL').show();
			}
		}
	});
	
	//Status listener for resident satisfaction
	$('div[id="reportfilterstatus_satisfaction"] a.listitem').click(function(){
		var option = $(this).attr('id');
		var text = $(this).text();
		
		if(option == 'ALL')
		{
			$(this).addClass('selected');
			$('div[id="reportfilterstatus_satisfaction"] a[id!="'+option+'"]').removeClass('selected');
		}
		
		else
		{
			$('div[id="reportfilterstatus_satisfaction"] a[id="ALL"]').removeClass('selected');
			
			if($(this).hasClass('selected'))
			{
				$(this).removeClass('selected');
			}
			
			else
			{
				$(this).addClass('selected');
			}
		}
		
		return false;
	});
	//End status listener
	
	//Tenants only listener for aging summary
	$('input[name="tenants_only"]').click(function(){
		var checked = ($(this).is(':checked') ? 1 : 0);
		
		$('input[name="tenants_only"]').val(checked);
	});
	//End tenants only listener
	
	//Auto-populate hidden input for export csv fields
	var report_status;
	var report_filter_type;
	var report_filter_value;
	var report_filter_type_2;
	var report_filter_value_2;
	var report_summary;
	var report_login_status;
	var report_exclude;
	var report_tenants_only;
	var report_hours_open;
	var report_category;
	
	if($('form#aging_summary').length > 0)
	{
		report_status = $('a[dialog="#reportfilterstatus_requests"]:first').attr('option');
		report_filter_type = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('option');
		report_summary = $('a[dialog="#reportfilterinterval"]:first').attr('option');
		report_exclude = $('a[dialog="#reportfilterexclude"]:first').attr('option');
		report_hours_open = $('a[dialog="#reportfilterhours_open"]:first').attr('option');
		report_tenants_only = ($('input[name="tenants_only"]').is(':checked') ? 1 : 0);
	}
	
	else if($('form#maintenance_work_log').length > 0)
	{
		report_status = $('a[dialog="#reportfilterstatus_requests"]:first').attr('option');
		report_filter_type = $('a[dialog="#reportfilterbuilding_multi"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfilterbuilding_multi"]:first').attr('option');
		report_filter_type_2 = $('a[dialog="#reportfilteremployee"]:first').attr('rel');
		report_filter_value_2 = $('a[dialog="#reportfilteremployee"]:first').attr('option');
		report_summary = $('a[dialog="#reportfilterinterval"]:first').attr('option');
	}
	
	else if($('form#resident_activity').length > 0)
	{
		report_status = $('a[dialog="#reportfilterstatus_residents"]:first').attr('option');
		report_filter_type = $('a[dialog="#reportfilterbuilding_multi"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfilterbuilding_multi"]:first').attr('option');
		report_summary = $('a[dialog="#reportfilterinterval"]:first').attr('option');
		report_login_status = $('a[dialog="#reportfilterlogin"]:first').attr('option');
	}
	
	else if($('form#resident_moveout').length > 0)
	{
		//report_status = $('a[dialog="#reportfilterstatus_moveout"]:first').attr('option');
		report_status = 'ALL';
		report_filter_type = $('a[dialog="#reportfilterbuilding_multi"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfilterbuilding_multi"]:first').attr('option');
		report_summary = $('a[dialog="#reportfilterinterval"]:first').attr('option');
		report_login_status = $('a[dialog="#reportfilterlogin"]:first').attr('option');
	}
	
	else if($('form#resident_satisfaction').length > 0)
	{
		report_status = $('a[dialog="#reportfilterstatus_satisfaction"]:first').attr('option');
		report_filter_type = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('option');
		report_summary = $('a[dialog="#reportfilterinterval"]:first').attr('option');
	}
	
	else if($('form#inventory').length > 0)
	{
		report_filter_type = $('a[dialog="#reportfiltervendor"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfiltervendor"]:first').attr('option');
		report_filter_type_2 = $('a[dialog="#reportfilterinventorygroup"]:first').attr('rel');
		report_filter_value_2 = $('a[dialog="#reportfilterinventorygroup"]:first').attr('option');
		report_summary = $('a[dialog="#reportfilterinterval"]:first').attr('option');
	}
	
	else if($('form#maintenance_category').length > 0)
	{
		report_status = $('a[dialog="#reportfilterstatus_requests"]:first').attr('option');
		report_filter_type = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('option');
		
		if($('a[dialog="#reportfiltercategory_multi"]').length > 0)
		{
			report_category = $('a[dialog="#reportfiltercategory_multi"]:first').attr('option');
		}
		
		else
		{
			report_category = $('a[dialog="#reportfiltercategory"]:first').attr('option');
		}
	}
	
	else if($('form#employee_progression').length > 0)
	{
		report_status = 'ALL';
		report_filter_type = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('rel');
		report_filter_value = $('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('option');
		report_summary = 'MONTHLY';
	}
	
	$('input[type="hidden"][name="status"]').val(report_status);
	$('input[type="hidden"][name="filter_subject"]').val(report_filter_type);
	$('input[type="hidden"][name="filter"]').val(report_filter_value);
	$('input[type="hidden"][name="interval"]').val(report_summary);
	$('input[type="hidden"][name="exclude"]').val(report_exclude);
	
	if(typeof(report_login_status) !== 'undefined')
	{
		$('input[type="hidden"][name="login_status"]').val(report_login_status);
	}
	
	if(typeof(report_filter_type_2) !== 'undefined')
	{
		$('input[type="hidden"][name="filter_subject_2"]').val(report_filter_type_2);
		$('input[type="hidden"][name="filter_2"]').val(report_filter_value_2);
	}
	
	if(typeof(report_tenants_only) !== 'undefined')
	{
		$('input[type="hidden"][name="tenants_only"]').val(report_tenants_only);
	}
	
	if(typeof(report_hours_open) !== 'undefined')
	{
		$('input[type="hidden"][name="hours_open"]').val(report_hours_open);
	}
	
	if(typeof(report_category) !== 'undefined')
	{
		$('input[type="hidden"][name="category"]').val(report_category);
	}
	//End modal window navigation, auto-selected logic, change report link, auto-populate hidden fields
	
	
	
	
	
    // used for alerts
    var alertdialog = function(title, msg) {
        $('#alerttitle').html(title);
        $('#alerttext').html(msg);
        opendialog('#alertdialog');
    }
    
    // popping up the modal dialog for the selectors
    $('.selector').each(function () {
        $(this).click(function () {
        
            // knows which one to pop up with the dialog="#dialogname" attr
            dialog = $(this).attr('dialog');
            opendialog(dialog);
            
        });
    });
    
    var resetuploaddialog = function () {
        $('#upload_attachment_button').show(100);
        $('#upload_close').hide(100);
        $('#upload_complete').hide(100);
    }
    
    // closing the dialog
    var closedialog = function(d) {
        if (d === undefined) {
            d = 0;
        }
        
        if (dialog == '#uploadattachment') {
            resetuploaddialog();
        }
        
        if (dialog == '#employeelist')
        {
        	var employees_id =  $('a.assignment.selected').attr('employees_id');
        	if (employees_id == undefined)
        	{
        		employees_id = 0;
        	}
        	init_assignment(employees_id);


        	if (maintenance_record_mode != 'create')
        	{
        		var postvars = {
        				idmaintenance: idmaintenance,
        				employees_id: employees_id
        		};
            	
        		$.post("/mobile/maintenance/ajax_save_assignment", postvars, savedialog_callback, 'json');
        	}
        }
		
		if(dialog == '#reportfiltercategory_multi')
		{
			$('a[dialog="#reportfiltercategory_multi"]').removeAttr('previous_option');
		}
        
        if (dialog != '') {
            $(dialog).delay(d).fadeOut(anim_delay);
            dialog = '';
            if (dialogstack.length > 0) {
                dialog = dialogstack.pop();
                opendialog(dialog);
                
            } else {
                // if another dialog opened during fading time, let's
                // put the mask back up again.
                $('#mask').delay(d).fadeOut(anim_delay, function () {
                    if (dialog != '') {
                        $('#mask').fadeTo(anim_delay,0.2);
                    }
                });
            };
        }   
    }
	
	// closing the dialog
    var cancel_revert = function(d) {
        if (d === undefined) {
            d = 0;
        }
		
		if(dialog == '#reportfiltercategory_multi')
		{
			//Set previous options
			var previous_categories = $('a[dialog="#reportfiltercategory_multi"]').attr('previous_option');
					
			$('a[dialog="#reportfiltercategory_multi"]').attr('option', previous_categories);
			$('a[dialog="#reportfiltercategory_multi"]').removeAttr('previous_option');
			
			//Revert the button UI to match the previous option
			var option = $('a[dialog="#reportfiltercategory_multi"]:first').attr('option');
			var option_count = option.split(",");
			var child_count = parseInt($('input[name="all_child_count"]').val());
				
			if((option == 'ALL')||(option_count.length >= child_count))
			{
				$('a[dialog="#reportfiltercategory_multi"]:first').text('ALL');
			}
			
			else
			{
				if(option_count.length == 1)
				{
					$('a[dialog="#reportfiltercategory_multi"]:first').text('1 CATEGORY');
				}
				
				else
				{
					$('a[dialog="#reportfiltercategory_multi"]:first').text(option_count.length+' CATEGORIES');
				}
			}
		}
        
        if (dialog != '') {
            $(dialog).delay(d).fadeOut(anim_delay);
            dialog = '';
            if (dialogstack.length > 0) {
                dialog = dialogstack.pop();
                opendialog(dialog);
                
            } else {
                // if another dialog opened during fading time, let's
                // put the mask back up again.
                $('#mask').delay(d).fadeOut(anim_delay, function () {
                    if (dialog != '') {
                        $('#mask').fadeTo(anim_delay,0.2);
                    }
                });
            };
        }
    }
    
    var savedialog = function(d)
    {   
		if(dialog == '#createnotification')
		{
			var panel = $('div#createnotification a[function="save"]:first').attr('panel');
			
			if((typeof(panel) !== 'undefined')&&(panel == 'disabled'))
			{
				//Panel 3 of create notification, invalid save action
				alert('Please select units');
			}
			
			else if((typeof(panel) !== 'undefined')&&(panel == '3'))
			{
				//Valid panel 3 save action, move back to panel 1
				var send = $('div#createnotification div.panel_1 span.send a.selected:first').attr('id');
				var mode = $('div#createnotification a[function="save"]:first').attr('mode');
				
				if(send == 'NOW')
				{
					$('div#createnotification a[function="save"]:first').text('Send Now');
				}
				
				else
				{
					$('div#createnotification a[function="save"]:first').text('Schedule');
				}
			
				if(mode == 'create')
				{
					$('div#createnotification h3:first').html('Create Notification');
				}
				
				else
				{
					$('div#createnotification h3:first').html('Edit Notification');
				}
				
				//Change the "Select Recipients" text option in panel 1
				var tenant_ids = $('div#createnotification div.panel_1 input[name="tenant_ids"]:first').val();
				
				$.post("/mobile/tenant/ajax_create_notification_get_tenants_buildings", {'tenant_ids' : tenant_ids}, function(data){
					if(data.status == 'success')
					{
						$('div#createnotification div.panel_1 a#BUILDING:first').html(
							'<span class="text">'
								+ String(data.message)
							+ '</span>'
							+ '<img src="/resources/mobile/images/small_rightarrow.png" class="rightarrow">'
							+ '<span class="action">Change</span>'
						);
					}

					$('div#createnotification a.back:first').removeAttr('panel').hide();
					$('div#createnotification a[function="next"]:first').hide();
					$('div#createnotification div[class="panel_2"]').hide();
					$('div#createnotification div[class="panel_3"]').hide();
					$('div#createnotification div[class="panel_1"]:first').show();
					$('div#createnotification a[function="save"]:first').show().removeAttr('panel');
					$('div#createnotification a[function="close"]:first').show();
					//notification_delivery_details_text();
				}, 'json');
				//End building text
			}
			
			else
			{
				//Submit create notification
				$('div#createnotification div.savecancelbottombuttons span#spinner:first').show();
				$('div#createnotification a[function="save"]:first').hide();
				
				var page = $('div#createnotification a[function="save"]:first').attr('page');
				var mode = $('div#createnotification a[function="save"]:first').attr('mode');
				var message_id = $('div#createnotification a[function="save"]:first').attr('edit_message_id');
				var default_tenant_id = $('div#createnotification div.panel_1 input[name="default_tenant_id"]:first').val();
				var tenant_ids = $('div#createnotification div.panel_1 input[name="tenant_ids"]:first').val();
				var send_by_date = $('div#createnotification div.panel_1 input[name="send_by_date"]:first').val();
				var send_by_time = $('div#createnotification div.panel_1 input[name="send_by_time"]:first').val();
				var priority = $('div#createnotification div.panel_1 span.priority a.selected:first').attr('id');
				var title = $('div#createnotification div.panel_1 input[name="title"]:first').val();
				var content = $('div#createnotification div.panel_1 textarea[name="message"]:first').val();
				var notification_type = $('div#createnotification div.panel_1 span.send a.selected:first').attr('id');
				var selected_building_ids = Array();
					
				$('div#createnotification div.panel_2 a.selected').each(function()
				{
					var building_id = $(this).attr('id');
					selected_building_ids.push(building_id);
				});
					
				if(notification_type == 'SCHEDULE')
				{
					var post_vars = {
						'building_ids': selected_building_ids,
						'default_tenant_id': default_tenant_id,
						'tenant_ids': tenant_ids,
						'send_by_date':	send_by_date,
						'send_by_time': send_by_time,
						'priority': priority,
						'title': title,
						'content': content,
						'message_id': message_id
					};
				}
				
				else
				{
					var post_vars = {
						'building_ids': selected_building_ids,
						'default_tenant_id': default_tenant_id,
						'tenant_ids': tenant_ids,
						'priority': priority,
						'title': title,
						'content': content,
						'message_id': message_id
					};
				}
					
				if(mode == 'create')
				{
					$.post("/mobile/tenant/ajax_create_notification", post_vars, function(data){
						if(data.status == 'success')
						{
							if(page == 'tenant')
							{
								//Repopulate the form automatically on submission to the tenant's information
								var default_tenant_id = $('div#createnotification div.panel_1 input[name="default_tenant_id"]:first').val();
								var default_building_name = $('div#createnotification div.panel_1 input[name="default_notification_building_name"]:first').val();
								
								if(((typeof(default_tenant_id) == 'undefined')||(typeof(default_building_name) == 'undefined')||(jQuery.trim(default_building_name) == '')))
								{
									$('div#createnotification div.panel_1 input[name="tenant_ids"]').val('');
									$('div#createnotification div.panel_1 a#BUILDING:first').html('Select Recipients <img src="/resources/mobile/images/small_rightarrow.png" class="rightarrow">');
								}
								
								else
								{
									$('div#createnotification div.panel_1 input[name="tenant_ids"]').val(default_tenant_id);
									$('div#createnotification div.panel_1 a#BUILDING span.text:first').text(default_building_name);
								}
								//End repopulate the form automatically
								
								$('a#showmore_notifications:first').attr('rel', data.offset);
								$('span#notifications_nothing:first').hide();
								$('div#notifications_listing:first').html(data.message);
								$('div#createnotification div.panel_1 span.delivery_details:first').html('');
								$('div#createnotification div.panel_1 span.send a#NOW:first').addClass('selected');
								$('div#createnotification div.panel_1 span.send a[id!="NOW"]').removeClass('selected');
								$('div#createnotification div.panel_1 input[name="send_by_date"]').val('');
								$('div#createnotification div.panel_1 input[name="send_by_time"]:first').val('09:00 AM');
								$('div#createnotification div.panel_1 span.priority a.selected').removeClass('selected');
								$('div#createnotification div.panel_1 span.priority a#LOW').addClass('selected');
								$('div#createnotification div.panel_1 input[name="title"]:first').val('');
								$('div#createnotification div.panel_1 textarea[name="message"]').val('');
								$('div#createnotification div.panel_2 a.selected').removeClass('selected');
								$('div#createnotification div.panel_3 input[name="search"]:first').val('');
								$('div#createnotification div.panel_3 div.content_listing:first').html('');
								$('div#createnotification div.panel_3 input[name="search"]:first').val('');
								$('div#createnotification a[function="save"]').removeAttr('save_type');
								$('div#createnotification span#count').text('3000');
								
								if(data.offset >= 5)
								{
									$('a#showmore_notifications:first').show();
								}
								
								closedialog();
							}
							
							else
							{
								//This is for notifications dashboard
								$('div#createnotification div.panel_1 a#BUILDING:first').html('Select Recipients <img src="/resources/mobile/images/small_rightarrow.png" class="rightarrow">');
								$('div#createnotification div.panel_1 span.delivery_details:first').html('');
								$('div#createnotification div.panel_1 input[name="tenant_ids"]').val('');
								$('div#createnotification div.panel_1 span.send a#NOW:first').addClass('selected');
								$('div#createnotification div.panel_1 span.send a[id!="NOW"]').removeClass('selected');
								$('div#createnotification div.panel_1 input[name="send_by_date"]').val('');
								$('div#createnotification div.panel_1 input[name="send_by_time"]:first').val('09:00 AM');
								$('div#createnotification div.panel_1 span.priority a.selected').removeClass('selected');
								$('div#createnotification div.panel_1 span.priority a#LOW').addClass('selected');
								$('div#createnotification div.panel_1 input[name="title"]:first').val('');
								$('div#createnotification div.panel_1 textarea[name="message"]').val('');
								$('div#createnotification div.panel_2 a.selected').removeClass('selected');
								$('div#createnotification div.panel_3 input[name="search"]:first').val('');
								$('div#createnotification div.panel_3 div.content_listing:first').html('');
								$('div#createnotification div.panel_3 input[name="search"]:first').val('');
								$('div#createnotification a[function="save"]').removeAttr('save_type');
								$('div#createnotification span#count').text('3000');
								
								closedialog();
								window.location.reload();
							}
						}
						
						else
						{
							if(typeof(data.message) !== 'undefined')
							{
								alert(data.message);
								$('div#createnotification a[function="save"]:first').show();
							}
							
							else
							{
								alert('An error has occurred');
								$('div#createnotification a[function="save"]:first').show();
							}
						}
						
						$('div#createnotification div.savecancelbottombuttons span#spinner:first').hide();
					}, 'json');
				}
				
				else
				{
					$.post("/mobile/tenant/ajax_edit_notification", post_vars, function(data){
						if(data.status == 'success')
						{
							closedialog();
							window.location.reload();
						}
						
						else
						{
							if(typeof(data.message) !== 'undefined')
							{
								alert(data.message);
								$('div#createnotification a[function="save"]:first').show();
							}
							
							else
							{
								alert('An error has occurred');
								$('div#createnotification a[function="save"]:first').show();
							}
						}
						$('div#createnotification div.savecancelbottombuttons span#spinner:first').hide();
					}, 'json');
				}
			}
		}
		
		else if(dialog == '#copycreatenotification')
		{
			var panel = $('div#copycreatenotification a[function="save"]:first').attr('panel');
			
			if((typeof(panel) !== 'undefined')&&(panel == 'disabled'))
			{
				//Panel 3 of create notification, invalid save action
				alert('Please select units');
			}
			
			else if((typeof(panel) !== 'undefined')&&(panel == '3'))
			{
				//Valid panel 3 save action, move back to panel 1
				var send = $('div#copycreatenotification div.panel_1 span.send a.selected:first').attr('id');
				var mode = $('div#copycreatenotification a[function="save"]:first').attr('mode');
				
				if(send == 'NOW')
				{
					$('div#copycreatenotification a[function="save"]:first').text('Send Now');
				}
				
				else
				{
					$('div#copycreatenotification a[function="save"]:first').text('Schedule');
				}
			
				if(mode == 'create')
				{
					$('div#copycreatenotification h3:first').html('Create Notification');
				}
				
				else
				{
					$('div#copycreatenotification h3:first').html('Edit Notification');
				}
				
				//Change the "Select Recipients" text option in panel 1
				var tenant_ids = $('div#copycreatenotification div.panel_1 input[name="tenant_ids"]:first').val();
				
				$.post("/mobile/tenant/ajax_create_notification_get_tenants_buildings", {'tenant_ids' : tenant_ids}, function(data){
					if(data.status == 'success')
					{
						//$('div#copycreatenotification div.panel_1 a#BUILDING:first').html(data.message+'<span class="action">Change</span><img src="/resources/mobile/images/small_rightarrow.png" class="rightarrow">');
						$('div#copycreatenotification div.panel_1 a#BUILDING:first').html(
								'<span class="text">'
									+ String(data.message)
								+ '</span>'
								+ '<img src="/resources/mobile/images/small_rightarrow.png" class="rightarrow">'
								+ '<span class="action">Change</span>'
							);
					}
					
					$('div#copycreatenotification a.back:first').removeAttr('panel').hide();
					$('div#copycreatenotification a[function="next"]:first').hide();
					$('div#copycreatenotification div[class="panel_2"]').hide();
					$('div#copycreatenotification div[class="panel_3"]').hide();
					$('div#copycreatenotification div[class="panel_1"]:first').show();
					$('div#copycreatenotification a[function="save"]:first').show().removeAttr('panel');
					$('div#copycreatenotification a[function="close"]:first').show();
					//notification_delivery_details_text();
				}, 'json');
				//End building text
			}
			
			else
			{
				//Submit create notification
				$('div#copycreatenotification div.savecancelbottombuttons span#spinner:first').show();
				$('div#copycreatenotification a[function="save"]:first').hide();
				
				var page = $('div#copycreatenotification a[function="save"]:first').attr('page');
				var mode = $('div#copycreatenotification a[function="save"]:first').attr('mode');
				var message_id = $('div#copycreatenotification a[function="save"]:first').attr('edit_message_id');
				var default_tenant_id = $('div#copycreatenotification div.panel_1 input[name="default_tenant_id"]:first').val();
				var tenant_ids = $('div#copycreatenotification div.panel_1 input[name="tenant_ids"]:first').val();
				var send_by_date = $('div#copycreatenotification div.panel_1 input[name="send_by_date"]:first').val();
				var send_by_time = $('div#copycreatenotification div.panel_1 input[name="send_by_time"]:first').val();
				var priority = $('div#copycreatenotification div.panel_1 span.priority a.selected:first').attr('id');
				var title = $('div#copycreatenotification div.panel_1 input[name="title"]:first').val();
				var content = $('div#copycreatenotification div.panel_1 textarea[name="message"]:first').val();
				var notification_type = $('div#copycreatenotification div.panel_1 span.send a.selected:first').attr('id');
				var selected_building_ids = Array();
					
				$('div#copycreatenotification div.panel_2 a.selected').each(function()
				{
					var building_id = $(this).attr('id');
					selected_building_ids.push(building_id);
				});
					
				if(notification_type == 'SCHEDULE')
				{
					var post_vars = {
						'building_ids': selected_building_ids,
						'default_tenant_id': default_tenant_id,
						'tenant_ids': tenant_ids,
						'send_by_date':	send_by_date,
						'send_by_time': send_by_time,
						'priority': priority,
						'title': title,
						'content': content,
						'message_id': message_id
					};
				}
				
				else
				{
					var post_vars = {
						'building_ids': selected_building_ids,
						'default_tenant_id': default_tenant_id,
						'tenant_ids': tenant_ids,
						'priority': priority,
						'title': title,
						'content': content,
						'message_id': message_id
					};
				}
				
				$.post("/mobile/tenant/ajax_create_notification", post_vars, function(data){
					if(data.status == 'success')
					{
						$('div#copycreatenotification div.panel_1 a#BUILDING:first').html('Select Recipients <img src="/resources/mobile/images/small_rightarrow.png" class="rightarrow">');
						$('div#copycreatenotification div.panel_1 span.delivery_details:first').html('');
						$('div#copycreatenotification div.panel_1 input[name="tenant_ids"]').val('');
						$('div#copycreatenotification div.panel_1 span.send a#NOW:first').addClass('selected');
						$('div#copycreatenotification div.panel_1 span.send a[id!="NOW"]').removeClass('selected');
						$('div#copycreatenotification div.panel_1 input[name="send_by_date"]').val('');
						$('div#copycreatenotification div.panel_1 input[name="send_by_time"]:first').val('09:00 AM');
						$('div#copycreatenotification div.panel_1 span.priority a.selected').removeClass('selected');
						$('div#copycreatenotification div.panel_1 span.priority a#LOW').addClass('selected');
						$('div#copycreatenotification div.panel_2 a.selected').removeClass('selected');
						$('div#copycreatenotification div.panel_3 input[name="search"]:first').val('');
						$('div#copycreatenotification div.panel_3 div.content_listing:first').html('');
						$('div#copycreatenotification div.panel_3 input[name="search"]:first').val('');
						$('div#copycreatenotification a[function="save"]').removeAttr('save_type');
						$('div#copycreatenotification span#count').text('3000');
						
						closedialog();
						window.location.reload();
					}
					
					else
					{
						if(typeof(data.message) !== 'undefined')
						{
							alert(data.message);
							$('div#copycreatenotification a[function="save"]:first').show();
						}
						
						else
						{
							alert('An error has occurred');
							$('div#copycreatenotification a[function="save"]:first').show();
						}
					}
					
					$('div#copycreatenotification div.savecancelbottombuttons span#spinner:first').hide();
				}, 'json');
			}
		}
		
		else if(dialog == '#reputation_management')
		{
			var postvars = {
				reputation_testimonial:				($('#reputation_testimonial').is(':checked')) ? '1' : '0',
				reputation_external:				($('#reputation_external').is(':checked')) ? '1' : '0',
				reputation_external_satisfied:		($('#reputation_external_satisfied').is(':checked')) ? '1' : '0',
				reputation_external_not_satisfied:	($('#reputation_external_not_satisfied').is(':checked')) ? '1' : '0',
				reputation_url:						$('input[name="external_url"]').val(),
				reputation_url_satisfied:			$('input[name="external_url_satisfied"]').val(),
				reputation_url_not_satisfied:		$('input[name="external_url_not_satisfied"]').val(),
				idbuilding:							$('input#building_id').val()
			};
			
			//Found in building_details.js
			submit_reputation_controls(postvars, function(response){
				if(response == 'success')
				{
					closedialog();
				}
			});
		}
		
		else if(dialog == '#reportfilterstatus_satisfaction')
		{
			var display = '';
			var option = Array();
			var count = 0;
			
			$('div[id="reportfilterstatus_satisfaction"] a.selected').each(function()
			{
				if(count == 0)
				{
					display = $(this).text();	
				}
				
				else
				{
					display = display+','+$(this).text();
				}
				
				option[count++] = $(this).attr('id');
			});
			
			if((count == 0)||(count == 3))
			{
				option = 'ALL';
				display = 'ALL';
			}
			
			$('a[dialog="#reportfilterstatus_satisfaction"]:first').attr('option', option).text(display);
			$('input[type="hidden"][name="status"]').val(option);
			
			closedialog();
		}
		
		else if(dialog == '#reportfiltercategory')
		{
			var display = '';
			var option = Array();
			var count = 0;
			var total_categories_count = $('div[id="reportfiltercategory"] a').length;
			
			$('div[id="reportfiltercategory"] a.selected').each(function()
			{
				if(count == 0)
				{
					display = $(this).text();	
				}
				
				else
				{
					display = display+','+$(this).text();
				}
				
				option[count++] = $(this).attr('id');
			});
			
			if(((count == 0)||(total_categories_count == count)||(option[0] == 'ALL')))
			{
				option = 'ALL';
				display = 'ALL';
			}
			
			else
			{
				display = count+' ';
				
				if(count == 1)
				{
					display += 'CATEGORY';
				}
				
				else
				{
					display += 'CATEGORIES';
				}
			}
			
			$('a[dialog="#reportfiltercategory"]:first').attr('option', option).text(display);
			$('input[type="hidden"][name="category"]').val(option);
			
			//Get the text from the dialog button for categories
			var category_dialog_text = $('a[dialog="#reportfiltercategory"]:first').text();
			
			//Get and modify the current criteria text, only need to modify the category portion
			var current_filter_criteria = $('p.filter_criteria').html();
			var reverse_current_filter_criteria = current_filter_criteria.split('AND').reverse();
			
			//Get and modify the current criteria list text, only need to modify the category portion
			var current_filter_criteria_list = $('p.filter_criteria_list').html();
			var reverse_current_filter_criteria_list = current_filter_criteria_list.split('AND').reverse();
			
			if(reverse_current_filter_criteria[0].indexOf('CATEGORY') != -1)
			{
				var split_reverse_current_filter_criteria = jQuery.trim(reverse_current_filter_criteria[0]).split('CATEGORY');
			}
			
			else
			{
				var split_reverse_current_filter_criteria = jQuery.trim(reverse_current_filter_criteria[0]).split('CATEGORIES');
			}
			
			if(reverse_current_filter_criteria_list[0].indexOf('CATEGORY') != -1)
			{
				var split_reverse_current_filter_criteria_list = jQuery.trim(reverse_current_filter_criteria_list[0]).split('CATEGORY');
			}
			
			else
			{
				var split_reverse_current_filter_criteria_list = jQuery.trim(reverse_current_filter_criteria_list[0]).split('CATEGORIES');
			}
			
			//Put the dialog button text into the updated filter criteria container
			if(jQuery.trim(category_dialog_text) == 'ALL')
			{
				category_dialog_text = 'ALL CATEGORIES';
			}
			
			split_reverse_current_filter_criteria[0] = category_dialog_text;
			split_reverse_current_filter_criteria_list[0] = category_dialog_text;
			
			//Clear our filter criteria
			filter_criteria = '';
			var count_reverse_current_filter_criteria = reverse_current_filter_criteria.length;
			var count = 1;
			
			$.each(reverse_current_filter_criteria.reverse(), function(key, value)
			{
				if(count != count_reverse_current_filter_criteria)
				{
					if(count > 1)
					{
						filter_criteria += 'AND';
					}
					
					filter_criteria += value;
				}
				
				else
				{
					filter_criteria += 'AND '+split_reverse_current_filter_criteria[0]+split_reverse_current_filter_criteria[1];
				}
				
				count++;
			});
			
			//Clear our filter criteria list
			filter_criteria_list = '';
			var count_reverse_current_filter_criteria_list = reverse_current_filter_criteria_list.length;
			var count = 1;
			
			$.each(reverse_current_filter_criteria_list.reverse(), function(key, value)
			{
				if(count != count_reverse_current_filter_criteria_list)
				{
					if(count > 1)
					{
						filter_criteria_list += 'AND';
					}
					
					filter_criteria_list += value;
				}
				
				else
				{
					filter_criteria_list += 'AND '+split_reverse_current_filter_criteria_list[0]+split_reverse_current_filter_criteria_list[1];
				}
				
				count++;
			});
			
			$('p.filter_criteria').html(filter_criteria).show();
			$('p.filter_criteria_list').html(filter_criteria_list).hide();
			
			closedialog();
		}
		
		else if(dialog == '#reportfiltercategory_multi')
		{
			//alert('running category');
			var option = Array();
			var count = 0;
			var rel = '';
			var filter_criteria = '';
			var filter_criteria_list = '';
			var panel = $('div#parent_category_display').is(':visible') ? 'parent_display' : 'child_display';
			
			if(panel == 'parent_display')
			{
				if(($('a[dialog="#reportfiltercategory_multi"]').attr('option') == '')||($('div[id="reportfiltercategory_multi"] div#parent_category_display a#ALL').hasClass('selected')))
				{
					var all_categories = $('input[name="all_child_category_ids"]').val();
					
					$('a[dialog="#reportfiltercategory_multi"]').attr('option', all_categories);
					$('a[dialog="#reportfiltercategory_multi"]').text('ALL');
				}
				
				closedialog();
			}
			
			else
			{
				$('div#reportfiltercategory_multi a.back').hide();
				$('div#child_category_display').hide();
				$('div#parent_category_display').show();
				
				var a_dialog_option = $('a[dialog="#reportfiltercategory_multi"]').attr('option');
				
				$('div[id="reportfiltercategory_multi"] div#child_category_display a').each(function()
				{
					var id = $(this).attr('id');
					
					if($(this).hasClass('selected'))
					{
						if(id != 'ALL')
						{
							if(a_dialog_option == 'ALL')
							{
								a_dialog_option = id;
							}
							
							else if(a_dialog_option.search(id) == -1)
							{
								if(jQuery.trim(a_dialog_option) != '')
								{
									a_dialog_option = a_dialog_option+','+id;
								}
								
								else
								{
									a_dialog_option = id;
								}
							}
						}
						
						if(count == 0)
						{
							//filter_criteria = filter_criteria+$(this).text();
							//filter_criteria_list = $(this).text();
							rel = $(this).attr('rel');
						}
						
						else
						{
							//filter_criteria_list = filter_criteria_list+','+$(this).text();
						}
						
						option[count++] = $(this).attr('id');
					}
					
					else
					{
						if(id != 'ALL')
						{
							//Remove the ID and then fix double commas to single
							a_dialog_option = a_dialog_option.replace(id, '');
							a_dialog_option = a_dialog_option.replace(',,', ',');
						}
					}
				});
				
				//Remove the starting and last comma in string
				a_dialog_option = a_dialog_option.replace(/^,|,$/g, '');
				
				$('a[dialog="#reportfiltercategory_multi"]').attr('option', a_dialog_option);
				
				var selected_categories = $('a[dialog="#reportfiltercategory_multi"]').attr('option');
				var display = '';
				
				if(selected_categories == 'ALL')
				{
					display = 'ALL';
				}
				
				else
				{
					//Deselect parent ALL button
					$('div[id="reportfiltercategory_multi"] div#parent_category_display a.listitem#ALL').removeClass('selected');
					
					var split_options = selected_categories.split(',');
					var split_options_length = split_options.length;
					
					if(split_options_length > 0)
					{
						split_options_length = 0;
						
						$.each(split_options, function(key, value)
						{
							if(jQuery.trim(value) != '')
							{
								split_options_length++;
							}
						});
						
						display = jQuery.trim(split_options_length) + (split_options_length == 1 ? ' CATEGORY' : ' CATEGORIES');
						
					}
					
					else
					{
						display = 'ALL';
					}
				}
				
				$('a[dialog="#reportfiltercategory_multi"]:first').text(display);
				$('input[type="hidden"][name="category"]').val(selected_categories);
				
				initialize_categories('#reportfiltercategory_multi');
			}
			
			//Get the text from the dialog button for categories
			var category_dialog_text = $('a[dialog="#reportfiltercategory_multi"]:first').text();
			
			//Get and modify the current criteria text, only need to modify the category portion
			var current_filter_criteria = $('p.filter_criteria').html();
			var reverse_current_filter_criteria = current_filter_criteria.split('AND').reverse();
			
			//Get and modify the current criteria list text, only need to modify the category portion
			var current_filter_criteria_list = $('p.filter_criteria_list').html();
			var reverse_current_filter_criteria_list = current_filter_criteria_list.split('AND').reverse();
			
			if(reverse_current_filter_criteria[0].indexOf('CATEGORY') != -1)
			{
				var split_reverse_current_filter_criteria = jQuery.trim(reverse_current_filter_criteria[0]).split('CATEGORY');
			}
			
			else
			{
				var split_reverse_current_filter_criteria = jQuery.trim(reverse_current_filter_criteria[0]).split('CATEGORIES');
			}
			
			if(reverse_current_filter_criteria_list[0].indexOf('CATEGORY') != -1)
			{
				var split_reverse_current_filter_criteria_list = jQuery.trim(reverse_current_filter_criteria_list[0]).split('CATEGORY');
			}
			
			else
			{
				var split_reverse_current_filter_criteria_list = jQuery.trim(reverse_current_filter_criteria_list[0]).split('CATEGORIES');
			}
			
			//Put the dialog button text into the updated filter criteria container
			if(jQuery.trim(category_dialog_text) == 'ALL')
			{
				category_dialog_text = 'ALL CATEGORIES';
			}
			
			split_reverse_current_filter_criteria[0] = category_dialog_text;
			split_reverse_current_filter_criteria_list[0] = category_dialog_text;
			
			//Clear our filter criteria
			filter_criteria = '';
			var count_reverse_current_filter_criteria = reverse_current_filter_criteria.length;
			var count = 1;
			
			$.each(reverse_current_filter_criteria.reverse(), function(key, value)
			{
				if(count != count_reverse_current_filter_criteria)
				{
					if(count > 1)
					{
						filter_criteria += 'AND';
					}
					
					filter_criteria += value;
				}
				
				else
				{
					filter_criteria += 'AND '+split_reverse_current_filter_criteria[0]+split_reverse_current_filter_criteria[1];
				}
				
				count++;
			});
			
			//Clear our filter criteria list
			filter_criteria_list = '';
			var count_reverse_current_filter_criteria_list = reverse_current_filter_criteria_list.length;
			var count = 1;
			
			$.each(reverse_current_filter_criteria_list.reverse(), function(key, value)
			{
				if(count != count_reverse_current_filter_criteria_list)
				{
					if(count > 1)
					{
						filter_criteria_list += 'AND';
					}
					
					filter_criteria_list += value;
				}
				
				else
				{
					filter_criteria_list += 'AND '+split_reverse_current_filter_criteria_list[0]+split_reverse_current_filter_criteria_list[1];
				}
				
				count++;
			});
			
			$('p.filter_criteria').html(filter_criteria).show();
			$('p.filter_criteria_list').html(filter_criteria_list).hide();
		}
		
		else if(dialog == '#reportfilterbuilding_multi')
		{
			var option = Array();
			var count = 0;
			var rel = '';
			var filter_criteria = '';
			var filter_criteria_list = '';
			
			$('div[id="reportfilterbuilding_multi"] a.selected').each(function()
			{
				var id = $(this).attr('id');
				
				if(count == 0)
				{
					filter_criteria = filter_criteria+$(this).text();
					filter_criteria_list = $(this).text();
					rel = $(this).attr('rel');
				}
				
				else
				{
					filter_criteria_list = filter_criteria_list+','+$(this).text();
				}
				
				option[count++] = $(this).attr('id');
			});
			
			//Cannot select 0 buildings
			if(count == 0)
			{
				var display = 'ALL BUILDINGS';
				option[0] = 'ALL';
				rel = 'BUILDING';
			}
			
			else if(option[0] == 'ALL')
			{
				var display = 'ALL '+rel+'S';
				option = Array();
				option[0] = 'ALL';
				count = 0;
			}
			
			else if(count < 2)
			{
				var display = count+' '+rel;
			}
			
			else
			{
				var display = count+' '+rel+'S';
			}
			
			if(count > 1)
			{
				count--;
				filter_criteria = filter_criteria+' and '+count+' other '+rel+'S';
				filter_criteria = filter_criteria.toUpperCase();
				filter_criteria = 'Currently viewing: '+filter_criteria;
				filter_criteria_list = 'Currently viewing: '+filter_criteria_list.toUpperCase();
			}
			
			else if(count < 1)
			{
				filter_criteria = 'ALL '+rel+'S';
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
			}
			
			else
			{
				count = 0;
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
				filter_criteria_list = filter_criteria;
			}
			
			//Now that maintenance work log has two filters
			if($('a[dialog="#reportfilteremployee"]').length > 0)
			{
				var option_2 = Array();
				var count_2 = 0;
				
				$('div[id="reportfilteremployee"] a.selected').each(function()
				{
					var id = $(this).attr('id');
					option_2[count_2++] = $(this).attr('id');
				});
				
				//Cannot select 0 employees
				if((count_2 == 0)||(option_2[0] == 'ALL'))
				{
					filter_criteria = filter_criteria+' AND ALL EMPLOYEES';
					filter_criteria_list = filter_criteria_list+' AND ALL EMPLOYEES';
					
					if(count > 0)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
				
				else
				{
					var employee_text = 'EMPLOYEE';
					
					if(count_2 > 1)
					{
						employee_text = 'EMPLOYEES';	
					}
					
					filter_criteria = filter_criteria+' AND '+count_2+' '+employee_text;
					filter_criteria_list = filter_criteria_list+' AND '+count_2+' '+employee_text;
					
					if(count > 0)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
			}
			
			else if($('a[dialog="#reportfiltercategory"], a[dialog="#reportfiltercategory_multi"]').length > 0)
			{
				//Just grab text from the dialog button and use substring for count
				if($('a[dialog="#reportfiltercategory"]').length > 0)
				{
					var category_text = $('a[dialog="#reportfiltercategory"]').text();
				}
				
				else
				{
					var category_text = $('a[dialog="#reportfiltercategory_multi"]').text();
				}
				
				var category_count = category_text.split(" ", 1);
				
				if(jQuery.trim(category_count) == '1')
				{
					filter_criteria += ' AND '+category_count+' CATEGORY';
					filter_criteria_list += ' AND '+category_count+' CATEGORY';
				}
				
				else
				{
					filter_criteria += ' AND '+category_count+' CATEGORIES';
					filter_criteria_list += ' AND '+category_count+' CATEGORIES';
				}
				
				if(count > 0)
				{
					filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
					filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
				}
				
				$('p.filter_criteria').html(filter_criteria).show();
				$('p.filter_criteria_list').html(filter_criteria_list).hide();
			}
			
			else
			{
				if(count > 0)
				{
					filter_criteria = filter_criteria+' <span class="show_all_criteria" show="0">(show all)</span>';
					filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
				}
				
				$('p.filter_criteria').html(filter_criteria).show();
				$('p.filter_criteria_list').html(filter_criteria_list).hide();
			}
			
			$('a[dialog="#reportfilterbuilding_multi"]:first').attr('rel', rel);
			$('a[dialog="#reportfilterbuilding_multi"]:first').attr('option', option).text(display);
			$('input[type="hidden"][name="filter_subject"]').val(rel);
			$('input[type="hidden"][name="filter"]').val(option);
			
			closedialog();
		}
		
		else if(dialog == '#reportfilterexclude')
		{
			var display = '';
			var option = Array();
			var count = 0;
			
			$('div[id="reportfilterexclude"] a.selected').each(function()
			{
				if(count == 0)
				{
					display = $(this).text();	
				}
				
				else
				{
					display = count+1 + ' EXCLUSIONS';
				}
				
				option[count++] = $(this).attr('id');
			});
			
			$('a[dialog="#reportfilterexclude"]:first').attr('option', option).text(display);
			$('input[type="hidden"][name="exclude"]').val(option);
			
			closedialog();
		}
		
		else if(dialog == '#reportfilteremployee')
		{
			//Essentially a mimicry of the #reportfilterbuilding_multi
			var option = Array();
			var count = 0;
			var rel = '';
			var filter_criteria = '';
			var filter_criteria_list = '';
			var display = 'ALL EMPLOYEES';
			
			$('div[id="reportfilterbuilding_multi"] a.selected').each(function()
			{
				var id = $(this).attr('id');
				
				if(count == 0)
				{
					filter_criteria = filter_criteria+$(this).text();
					filter_criteria_list = $(this).text();
					rel = $(this).attr('rel');
				}
				
				else
				{
					filter_criteria_list = filter_criteria_list+','+$(this).text();
				}
				
				option[count++] = $(this).attr('id');
			});
			
			//Cannot select 0 buildings
			if(count == 0)
			{
				option[0] = 'ALL';
				rel = 'BUILDING';
			}
			
			else if(option[0] == 'ALL')
			{
				option = Array();
				option[0] = 'ALL';
				count = 0;
			}
			
			if(count > 1)
			{
				count--;
				filter_criteria = filter_criteria+' and '+count+' other '+rel+'S';
				filter_criteria = filter_criteria.toUpperCase();
				filter_criteria = 'Currently viewing: '+filter_criteria;
				filter_criteria_list = 'Currently viewing: '+filter_criteria_list.toUpperCase();
			}
			
			else if(count < 1)
			{
				filter_criteria = 'ALL '+rel+'S';
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
			}
			
			else
			{
				count = 0;
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
				filter_criteria_list = filter_criteria;
			}
			
			//Now that maintenance work log has two filters
			if($('a[dialog="#reportfilteremployee"]').length > 0)
			{
				var option_2 = Array();
				var count_2 = 0;
				
				$('div[id="reportfilteremployee"] a.selected').each(function()
				{
					var id = $(this).attr('id');
					option_2[count_2++] = $(this).attr('id');
				});
				
				//Cannot select 0 employees
				if(count_2 == 0)
				{
					option_2[0] = 'ALL';
				}
				
				else if(option_2[0] == 'ALL')
				{
					option_2 = Array();
					option_2[0] = 'ALL';
					count_2 = 0;
				}
				
				//Cannot select 0 employees
				if((count_2 == 0)||(option_2[0] == 'ALL'))
				{
					filter_criteria = filter_criteria+' AND ALL EMPLOYEES';
					filter_criteria_list = filter_criteria_list+' AND ALL EMPLOYEES';
					
					if(count > 0)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
				
				else
				{
					if(count_2 > 1)
					{
						var display = count_2+' EMPLOYEES';
					}
					
					else
					{
						var display = count_2+' EMPLOYEE';
					}
					
					filter_criteria = filter_criteria+' AND '+display;
					filter_criteria_list = filter_criteria_list+' AND '+display;
					
					if(count > 0)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
			}
			
			else
			{
				if(count > 0)
				{
					filter_criteria = filter_criteria+' <span class="show_all_criteria" show="0">(show all)</span>';
					filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
				}
				
				$('p.filter_criteria').html(filter_criteria).show();
				$('p.filter_criteria_list').html(filter_criteria_list).hide();
			}
			
			$('a[dialog="#reportfilteremployee"]:first').attr('rel', 'EMPLOYEE');
			$('a[dialog="#reportfilteremployee"]:first').attr('option', option_2).text(display);
			$('input[type="hidden"][name="filter_subject_2"]').val('EMPLOYEE');
			$('input[type="hidden"][name="filter_2"]').val(option_2);
			
			closedialog();
		}
		
		else if(dialog == '#reportfilterbuilding_multi_menu')
		{
			var option = Array();
			var count = 0;
			var rel = '';
			var save_id = $('div[id="reportfilterbuilding_multi_menu"] a[function="save"]').attr('id');
			var filter_criteria = '';
			var filter_criteria_list = '';
			
			if(save_id == 'filter_building_display')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_building_display"] a.selected').each(function()
				{
					if(count == 0)
					{
						filter_criteria = filter_criteria+$(this).text();
						filter_criteria_list = $(this).text();
						rel = $(this).attr('rel');
					}
					
					else
					{
						filter_criteria_list = filter_criteria_list+','+$(this).text();
					}
					
					option[count++] = $(this).attr('id');
				});
				
				//Cannot select 0 buildings
				if(count == 0)
				{
					var display = 'ALL BUILDINGS';
					option[0] = 'ALL';
					rel = 'BUILDING';
				}
				
				else if(option[0] == 'ALL')
				{
					var display = 'ALL '+rel+'S';
					option = Array();
					option[0] = 'ALL';
					count = 0;
				}
				
				else if(count < 2)
				{
					var display = count+' '+rel;
				}
				
				else
				{
					var display = count+' '+rel+'S';
				}
			}
			
			else if(save_id == 'filter_employee_display')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_employee_display"] a.selected').each(function()
				{
					if(count == 0)
					{
						filter_criteria = filter_criteria+$(this).text();
						filter_criteria_list = $(this).text();
						rel = $(this).attr('rel');
					}
					
					else
					{
						filter_criteria_list = filter_criteria_list+','+$(this).text();
					}
					
					option[count++] = $(this).attr('id');
				});
				
				//Cannot select 0 buildings
				if(count == 0)
				{
					var display = 'ALL EMPLOYEES';
					option[0] = 'ALL';
					rel = 'EMPLOYEE';
				}
				
				else if(option[0] == 'ALL')
				{
					var display = 'ALL '+rel+'S';
					option = Array();
					option[0] = 'ALL';
					count = 0;
				}
				
				else if(count < 2)
				{
					var display = count+' '+rel;
				}
				
				else
				{
					var display = count+' '+rel+'S';
				}
			}
			
			else if(save_id == 'filter_regional_manager_display')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_regional_manager_display"] a.selected').each(function()
				{
					if(count == 0)
					{
						filter_criteria = filter_criteria+$(this).text();
						filter_criteria_list = $(this).text();
						rel = $(this).attr('rel');
					}
					
					else
					{
						filter_criteria_list = filter_criteria_list+','+$(this).text();
					}
					
					option[count++] = $(this).attr('id');
				});
				
				//Remove underscore in regional_manager
				rel = rel.replace('_', ' ');
				
				//Cannot select 0 managers
				if(count == 0)
				{
					alert('Please select a manager');
					return;
					/*var display = 'ALL MANAGERS';
					option[0] = 'ALL';
					rel = 'MANAGER';
					*/
				}
				
				else if(option[0] == 'ALL')
				{
					var display = 'ALL '+rel+'S';
					option = Array();
					option[0] = 'ALL';
					count = 0;
				}
				
				else if(count < 2)
				{
					var display = count+' '+rel;
				}
				
				else
				{
					var display = count+' '+rel+'S';
				}
			}
			
			else if(save_id == 'filter_svp_display')
			{
				$('div[id="reportfilterbuilding_multi_menu"] div[id="filter_svp_display"] a.selected').each(function()
				{
					if(count == 0)
					{
						filter_criteria = filter_criteria+$(this).text();
						filter_criteria_list = $(this).text();
						rel = $(this).attr('rel');
					}
					
					else
					{
						filter_criteria_list = filter_criteria_list+','+$(this).text();
					}
					
					option[count++] = $(this).attr('id');
				});
				
				//Remove underscore in regional_manager
				rel = rel.replace('_', ' ');
				
				//Cannot select 0 managers
				if(count == 0)
				{
					alert('Please select an SVP');
					return;
					/*var display = 'ALL MANAGERS';
					option[0] = 'ALL';
					rel = 'MANAGER';
					*/
				}
				
				else if(option[0] == 'ALL')
				{
					var display = 'ALL '+rel+'S';
					option = Array();
					option[0] = 'ALL';
					count = 0;
				}
				
				else if(count < 2)
				{
					var display = count+' '+rel;
				}
				
				else
				{
					var display = count+' '+rel+'S';
				}
			}
			
			else
			{
				alert('An error has occurred: Save Button ID Invalid');	
			}
			
			//Add category filter information if this dialog is present
			if(($('a[dialog="#reportfiltercategory"]').length > 0)||($('a[dialog="#reportfiltercategory_multi"]').length > 0))
			{
				if($('a[dialog="#reportfiltercategory"]').length > 0)
				{
					var categories_text = $('a[dialog="#reportfiltercategory"]').text();
				}
				
				else
				{
					var categories_text = $('a[dialog="#reportfiltercategory_multi"]').text();
				}
				
				if(jQuery.trim(categories_text) == 'ALL')
				{
					categories_text = 'ALL CATEGORIES';
				}
			}
			
			if(count > 1)
			{
				count--;
				filter_criteria = filter_criteria+' and '+count+' other '+rel+'S';
				filter_criteria = filter_criteria.toUpperCase();
				
				if(categories_text != undefined)
				{
					filter_criteria = 'Currently viewing: '+filter_criteria+' AND '+categories_text+' <span class="show_all_criteria" show="0">(show all)</span>';
					filter_criteria_list = 'Currently viewing: '+filter_criteria_list.toUpperCase()+' AND '+categories_text+' <span class="show_all_criteria" show="1">(show less)</span>';
				}
				
				else
				{
					filter_criteria = 'Currently viewing: '+filter_criteria+' <span class="show_all_criteria" show="0">(show all)</span>';
					filter_criteria_list = 'Currently viewing: '+filter_criteria_list.toUpperCase()+' <span class="show_all_criteria" show="1">(show less)</span>';
				}
			}
			
			else if(count < 1)
			{
				if(categories_text != undefined)
				{
					filter_criteria = 'ALL '+rel+'S';
					filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase()+' AND '+categories_text;
				}
				
				else
				{
					filter_criteria = 'ALL '+rel+'S';
					filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
				}
			}
			
			else
			{
				if(categories_text != undefined)
				{
					filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase()+' AND '+categories_text;
					filter_criteria_list = filter_criteria;
				}
				
				else
				{
					filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
					filter_criteria_list = filter_criteria;
				}
			}
			
			//Put back underscore in regional_manager
			rel = rel.replace(' ', '_');
			
			$('p.filter_criteria').html(filter_criteria).show();
			$('p.filter_criteria_list').html(filter_criteria_list).hide();
			$('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('rel', rel);
			$('a[dialog="#reportfilterbuilding_multi_menu"]:first').attr('option', option).text(display);
			$('input[type="hidden"][name="filter_subject"]').val(rel);
			$('input[type="hidden"][name="filter"]').val(option);
			
			closedialog();
		}
		
		else if(dialog == '#reportfiltervendor')
		{
			var option = Array();
			var count = 0;
			var rel = '';
			var filter_criteria = '';
			var filter_criteria_list = '';
			
			$('div[id="reportfiltervendor"] a.selected').each(function()
			{
				var id = $(this).attr('id');
				
				if(count == 0)
				{
					filter_criteria = filter_criteria+$(this).text();
					filter_criteria_list = $(this).text();
					rel = $(this).attr('rel');
				}
				
				else
				{
					filter_criteria_list = filter_criteria_list+','+$(this).text();
				}
				
				option[count++] = $(this).attr('id');
			});
			
			//Cannot select 0 vendors
			if(count == 0)
			{
				var display = 'ALL VENDORS';
				option[0] = 'ALL';
				rel = 'VENDOR';
			}
			
			else if(option[0] == 'ALL')
			{
				var display = 'ALL '+rel+'S';
				option = Array();
				option[0] = 'ALL';
				count = 0;
			}
			
			else if(count < 2)
			{
				var display = count+' '+rel;
			}
			
			else
			{
				var display = count+' '+rel+'S';
			}
			
			if(count > 1)
			{
				count--;
				filter_criteria = filter_criteria+' and '+count+' other '+rel+'S';
				filter_criteria = filter_criteria.toUpperCase();
				filter_criteria = 'Currently viewing: '+filter_criteria;
				filter_criteria_list = 'Currently viewing: '+filter_criteria_list.toUpperCase();
			}
			
			else if(count < 1)
			{
				filter_criteria = 'ALL '+rel+'S';
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
			}
			
			else
			{
				count = 0;
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
				filter_criteria_list = filter_criteria;
			}
			
			//Second filter in inventory
			if($('a[dialog="#reportfilterinventorygroup"]').length > 0)
			{
				var option_2 = Array();
				var count_2 = 0;
				
				$('div[id="reportfilterinventorygroup"] a.selected').each(function()
				{
					var id = $(this).attr('id');
					option_2[count_2++] = $(this).attr('id');
				});
				
				//Cannot select 0 groups
				if((count_2 == 0)||(option_2[0] == 'ALL'))
				{
					filter_criteria = filter_criteria+' AND ALL INVENTORY GROUPS';
					filter_criteria_list = filter_criteria_list+' AND ALL INVENTORY GROUPS';
					
					if(count > 0)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
				
				else
				{
					var group_text = 'INVENTORY GROUP';
					
					if(count_2 > 1)
					{
						group_text = 'INVENTORY GROUPS';	
					}
					
					filter_criteria = filter_criteria+' AND '+count_2+' '+group_text;
					filter_criteria_list = filter_criteria_list+' AND '+count_2+' '+group_text;
					
					if(count > 1)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
			}
			
			else
			{
				if(count > 0)
				{
					filter_criteria = filter_criteria+' <span class="show_all_criteria" show="0">(show all)</span>';
					filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
				}
				
				$('p.filter_criteria').html(filter_criteria).show();
				$('p.filter_criteria_list').html(filter_criteria_list).hide();
			}
			
			$('a[dialog="#reportfiltervendor"]:first').attr('rel', rel);
			$('a[dialog="#reportfiltervendor"]:first').attr('option', option).text(display);
			$('input[type="hidden"][name="filter_subject"]').val(rel);
			$('input[type="hidden"][name="filter"]').val(option);
			
			closedialog();
		}
		
		else if(dialog == '#reportfilterinventorygroup')
		{
			var option = Array();
			var count = 0;
			var rel = '';
			var filter_criteria = '';
			var filter_criteria_list = '';
			var display = 'ALL INVT GROUPS';
			
			$('div[id="reportfiltervendor"] a.selected').each(function()
			{
				var id = $(this).attr('id');
				
				if(count == 0)
				{
					filter_criteria = filter_criteria+$(this).text();
					filter_criteria_list = $(this).text();
					rel = $(this).attr('rel');
				}
				
				else
				{
					filter_criteria_list = filter_criteria_list+','+$(this).text();
				}
				
				option[count++] = $(this).attr('id');
			});
			
			//Cannot select 0 vendors
			if(count == 0)
			{
				option[0] = 'ALL';
				rel = 'VENDOR';
			}
			
			else if(option[0] == 'ALL')
			{
				option = Array();
				option[0] = 'ALL';
				count = 0;
			}
			
			if(count > 1)
			{
				count--;
				filter_criteria = filter_criteria+' and '+count+' other '+rel+'S';
				filter_criteria = filter_criteria.toUpperCase();
				filter_criteria = 'Currently viewing: '+filter_criteria;
				filter_criteria_list = 'Currently viewing: '+filter_criteria_list.toUpperCase();
			}
			
			else if(count < 1)
			{
				filter_criteria = 'ALL '+rel+'S';
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
			}
			
			else
			{
				count = 0;
				filter_criteria = 'Currently viewing: '+filter_criteria.toUpperCase();
				filter_criteria_list = filter_criteria;
			}
			
			//Inventory Group filter
			if($('a[dialog="#reportfilterinventorygroup"]').length > 0)
			{
				var option_2 = Array();
				var count_2 = 0;
				
				$('div[id="reportfilterinventorygroup"] a.selected').each(function()
				{
					var id = $(this).attr('id');
					option_2[count_2++] = $(this).attr('id');
				});
				
				//Cannot select 0 employees
				if(count_2 == 0)
				{
					option_2[0] = 'ALL';
				}
				
				else if(option_2[0] == 'ALL')
				{
					option_2 = Array();
					option_2[0] = 'ALL';
					count_2 = 0;
				}
				
				//Cannot select 0 groups
				if((count_2 == 0)||(option_2[0] == 'ALL'))
				{
					filter_criteria = filter_criteria+' AND ALL INVENTORY GROUPS';
					filter_criteria_list = filter_criteria_list+' AND ALL INVENTORY GROUPS';
					
					if(count > 0)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					filter_criteria = filter_criteria.replace("INVT GROUP","INVENTORY GROUP");
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
				
				else
				{
					if(count_2 > 1)
					{
						var display = count_2+' INVT GROUPS';
					}
					
					else
					{
						var display = count_2+' INVT GROUP';
					}
					
					filter_criteria = filter_criteria+' AND '+display;
					filter_criteria_list = filter_criteria_list+' AND '+display;
					
					if(count > 0)
					{
						filter_criteria = filter_criteria+'  <span class="show_all_criteria" show="0">(show all)</span>';
						filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
					}
					
					filter_criteria = filter_criteria.replace("INVT GROUP","INVENTORY GROUP");
					
					$('p.filter_criteria').html(filter_criteria).show();
					$('p.filter_criteria_list').html(filter_criteria_list).hide();
				}
			}
			
			else
			{
				if(count > 0)
				{
					filter_criteria = filter_criteria+' <span class="show_all_criteria" show="0">(show all)</span>';
					filter_criteria_list = filter_criteria_list+' <span class="show_all_criteria" show="1">(show less)</span>';
				}
				
				filter_criteria = filter_criteria.replace("INVT GROUP","INVENTORY GROUP");
				
				$('p.filter_criteria').html(filter_criteria).show();
				$('p.filter_criteria_list').html(filter_criteria_list).hide();
			}
			
			$('a[dialog="#reportfilterinventorygroup"]:first').attr('rel', 'INVT GROUP');
			$('a[dialog="#reportfilterinventorygroup"]:first').attr('option', option_2).text(display);
			$('input[type="hidden"][name="filter_subject_2"]').val('INVT GROUP');
			$('input[type="hidden"][name="filter_2"]').val(option_2);
			
			closedialog();
		}
		
		else if (dialog == '#progressindicator')
        {
        	var currarrow = $('#arrows .selected').attr('status');
        	pending_reason = $('#pendingreasons .selected').attr('reason');
        	pending_reason_other = $('#pendinginput').val();
        	var total_hours = $('#hoursinput').val();
        	var total_cost = $('#dollarsinput').val();
        	var overtime = ($('#overtimecheck').attr('checked') == 'checked') ? 1 : 0;
        	
        	if (pending_reason == undefined)
        	{
        		pending_reason = '';
        	}
        	
        	if (pending_reason_other == 'Or type reason here')
        	{
        		pending_reason_other = '';
        	}

        	if (currarrow == 'incomplete')
        	{
        		init_status(0, '', '');
        	}
        	else if (currarrow == 'complete')
        	{
        		if (parseInt(employees_id) == 0)
        		{
        			alert('A maintenance request cannot be closed until it has been assigned to someone.');
        			return;
        			//init_status(0, '', '');
        		}
        		init_status(1, '', '');
        	}
        	else if (currarrow == 'pending')
        	{
        		if (parseInt(employees_id) == 0)
        		{
        			//alert('A maintenance request cannot be marked pending until it has been assigned to someone.');
        			//init_status(0, '', '');
        			//return;
        			changeassigned_dialog();
        		}
        		init_status(2, pending_reason, pending_reason_other);
        	}
        	
        	if (maintenance_record_mode != 'create')
        	{
        		var postvars = {
        				idmaintenance: idmaintenance,
        				request_status: request_status,
        				pending_reason: pending_reason,
        				pending_reason_other: pending_reason_other,
        				total_hours: total_hours,
        				total_cost: total_cost,
        				overtime: overtime
        		};
        	
        		$.post("/mobile/maintenance/ajax_save_status", postvars, savedialog_callback, 'json');
        	}
        	else
        	{
        		 closedialog();
        		 return;
        	}

        	//closedialog(0);
        }
        else if (dialog == '#edittenant')
        {
        	if (tenant_save_mode == 'insert')
        	{
        		var idbuilding = $('#residential_buildings a.listitem.selected').attr('idbuilding');
        	}
        	else
        	{
        		var idbuilding = $("#tenant_building").attr('idbuilding');
        	}
            
			var tenant_id = $('#tenant_id').val();
			var tenant_email = $('input[name="current_tenant_email"]').val();
			var apartment_num = $('#tenant_aptnumber').val();
            var first_name = $('#tenant_firstname').val();
            var last_name = $('#tenant_lastname').val();
            var business_name = $('#tenant_business_name').val();
            var email = $('#tenant_email').val();
            var phone = $('#tenant_cellphone').val();
            var start_m = $('#start_m').val();
            var start_d = $('#start_d').val();
            var start_y = $('#start_y').val();
            var lease_start_date = start_m + '/' + start_d + '/' + start_y;
            var end_m = $('#end_m').val();
            var end_d = $('#end_d').val();
            var end_y = $('#end_y').val();           
            var lease_end_date = end_m + '/' + end_d + '/' + end_y;
            var moveout_m = $('#moveout_m').val();
            var moveout_d = $('#moveout_d').val();
            var moveout_y = $('#moveout_y').val();           
            var lease_moveout_date = moveout_m + '/' + moveout_d + '/' + moveout_y;
            var monthtomonth = $('#monthtomonth').is(':checked') ? 1 : 0;
            var pets_cats = $('#pets_cats').is(':checked') ? 1 : 0;
            var pets_dogs = $('#pets_dogs').is(':checked') ? 1 : 0;
            var pets_other = $('#pets_other').val();
            
            //alert(monthtomonth + ', ' + pets_cats + ', ' + pets_dogs);
            
            if (idbuilding == undefined)
            {
            	alert('Please select a building');
            	return false;
            }
            
            if (apartment_num == '')
            {
            	alert('Please enter an apartment number');
            	return false;
            }
            
            if (business_name == '')
            {
            	if (first_name == '')
				{
					alert('Please enter the '+commercial_term+'\'s first name');
					return false;
				}  
				
				if (last_name == '')
				{
					alert('Please enter the '+commercial_term+'\'s last name');
					return false;
				}
            }
            
            if (lease_start_date == '//')
            {
            	lease_start_date = '';
            }
            else if (checkdateformat(lease_start_date) == false)
            {
            	alert('Please enter the lease start date in the following format: dd/mm/yyyy');
            	return false;           	
            }
            
            if (lease_end_date == '//')
            {
            	lease_end_date = '';
            }
            else
            {
            	if (checkdateformat(lease_end_date) == false)
            	{
            		alert('Please enter the lease end date in the following format: dd/mm/yyyy');
            		return false;
            	}
            }
            
            if (lease_moveout_date == '//')
            {
            	lease_moveout_date = '';
            }
            else if (checkdateformat(lease_moveout_date) == false)
            {
            	alert('Please enter the lease moveout date in the following format: dd/mm/yyyy');
            	return false;           	
            }
            
            if ((monthtomonth == 0) && ((lease_start_date != '') && (lease_end_date == '')))
            {
            	alert('Please enter both a lease start and end date');
            	return false;
            }
            
            if (lease_moveout_date != '')
            {
            	var tmp_current_date = new Date();
            	var tmp_lease_moveout_date = new Date(lease_moveout_date);

            	//alert( tmp_current_date.toString('dd/mm/yyyy') + ', ' + tmp_lease_moveout_date.toString('dd/mm/yyyy'));
            	var difference = (tmp_current_date.getTime() - tmp_lease_moveout_date.getTime()) / (1000 * 60 * 60 * 24);
            	//alert(difference);
            	if (difference > 30)
            	{
            		if (!confirm("Because the moveout you have specified is 30 or more days in the past, \nyou are about to mark this "+commercial_term+" record as being inactive.\n\nDo you wish to proceed?"))
            		{
            			return false;
            		}
            	}
            }
            
            if ((tenant_save_mode != 'insert') && (typeof(tenant_email) != 'undefined'))
            {
				if(email != tenant_email)
            	{
            		if (!confirm("You are about to change the "+commercial_term+"'s email address. Do you wish to proceed?"))
            		{
            			return false;
            		}
            	}
            }
            
            /*
            alert(
            	tenant_id + "\n"
            	+ idbuilding + ",\n"
            	+ apartment_num + ",\n"
            	+ first_name + ' '
            	+ last_name + ",\n"
            	+ email + ",\n"
            	+ phone + ",\n"
            	+ lease_start_date + ' to '
            	+ lease_end_date + ",\n"
            	+ pets_cats +  ",\n"
            	+ pets_dogs +  ",\n"
            	+ pets_other +  ",\n"
            );
            */
            
            var postvars = {
            	tenant_save_mode : tenant_save_mode,
            	tenant_id : tenant_id, 
            	idbuilding : idbuilding,
            	apartment_num : apartment_num,
            	first_name : first_name,
            	last_name : last_name,
            	business_name : business_name,
            	email : email,
            	phone : phone,
            	start_m : start_m,
            	start_d : start_d,
            	start_y : start_y,
            	lease_start_date : lease_start_date,
            	end_m : end_m,
            	end_d : end_d,
            	end_y : end_y,
            	lease_end_date : lease_end_date,
            	moveout_m : moveout_m,
            	moveout_d : moveout_d,
            	moveout_y : moveout_y,
            	lease_moveout_date : lease_moveout_date,
            	monthtomonth : monthtomonth,
            	pets_cats : pets_cats,
            	pets_dogs : pets_dogs,
            	pets_other : pets_other
            }

        	if (tenant_save_mode == 'insert')
        	{
                $.post('/mobile/tenant/ajax_save_tenant', postvars, save_tenant_callback, 'json');
        	}
        	else
        	{
				$.post('/mobile/tenant/ajax_save_tenant', postvars, update_tenant_callback, 'json');
                // closedialog();
                //updateApartmentText();
        	}
        }
		
		else if(dialog == '#editemployee')
		{
			$('div#editemployee a[function="save"]').hide();
			$('div#editemployee_spinner').show();
			
			var role = $('a#employee_changerole span.text').text();
			var fname = $('input#employee_firstname').val();
			var lname = $('input#employee_lastname').val();
			var email = $('input#employee_email').val();
			var cell = $('input#employee_cellphone').val();
			var office = $('input#employee_officephone').val();
			var fax = $('input#employee_faxnumber').val();
			var status = $('a[class="employeestatus options selected"]').text();
			
			if((jQuery.trim(role) == '')||(role == 'Select Role'))
			{
				alert('Please select a Role');
				$('div#editemployee_spinner').hide();
				$('div#editemployee a[function="save"]').show();
				return false;
			}
			
			if(jQuery.trim(employeeBuildings) == '')
			{
				//Comma separated building names
				alert('Please select a Building');
				$('div#editemployee_spinner').hide();
				$('div#editemployee a[function="save"]').show();
				return false;
			}
			
			if(jQuery.trim(fname) == '')
			{
				//Comma separated building names
				alert('Please add a First Name');
				$('div#editemployee_spinner').hide();
				$('div#editemployee a[function="save"]').show();
				return false;
			}
			
			if(jQuery.trim(lname) == '')
			{
				//Comma separated building names
				alert('Please add a Last Name');
				$('div#editemployee_spinner').hide();
				$('div#editemployee a[function="save"]').show();
				return false;
			}
			
			if(jQuery.trim(status) == '')
			{
				//Comma separated building names
				alert('Please choose a Status');
				$('div#editemployee_spinner').hide();
				$('div#editemployee a[function="save"]').show();
				return false;
			}
			
			var role = $('a#employee_changerole span.text').text();
			var fname = $('input#employee_firstname').val();
			var lname = $('input#employee_lastname').val();
			var email = $('input#employee_email').val();
			var cell = $('input#employee_cellphone').val();
			var office = $('input#employee_officephone').val();
			var fax = $('input#employee_faxnumber').val();
			var status = $('a.employeestatus.selected').text();
			var login = $('a.employeelogin.selected').text();
			var assign_to_request = $('a.assign_to_request.selected').text();
			
			var location = String(window.location);
			
			if(jQuery.trim(location) !== '')
			{
				if(location.indexOf("employee/details") != -1)
				{
					var account_id = $('input[type="hidden"][id="modal_employee_id"]').val();
					
					if(jQuery.trim(account_id) != '')
					{
						var postvars = {
							role : role,
							buildings : employeeBuildings,
							fname : fname,
							lname : lname,
							email : email,
							cell : cell,
							office : office,
							fax : fax,
							status : status,
							account_id : account_id,
							login : login,
							assign_to_request : assign_to_request
						}
						
						$.post('/mobile/employee/ajax_edit_employee', postvars, edit_employee_callback, 'json')
					}
					
					else
					{
						alert('An error has occurred: Employee ID not found');
					}
				}
				
				else
				{
					var postvars = {
						role : role,
						buildings : employeeBuildings,
						fname : fname,
						lname : lname,
						email : email,
						cell : cell,
						office : office,
						fax : fax,
						status : status,
						login : login,
						assign_to_request : assign_to_request
					}
					
					$.post('/mobile/employee/ajax_add_employee', postvars, add_employee_callback, 'json')
				}
			}
			
			else
			{
				alert('An error has occurred: Window location not found');
				$('div#editemployee_spinner').hide();
				$('div#editemployee a[function="save"]').show();
			}
		}
		
		else if(dialog == '#addbuilding')
		{
			var is_commercial = ($('#building_is_commercial').hasClass('selected')) ? 1 : 0;
			var name = $('input#building_buildingname').val();
			var alias = jQuery.trim($('input#building_alias').val());
			var use_alias = $('input#building_use_alias').is(':checked') ? 1 : 0;
			var use_apartment_alias = $('input#building_use_apartment_alias').is(':checked') ? 1 : 0;
			var address1 = $('input#building_address1').val();
			var address2 = $('input#building_address2').val();
			var zip = $('input#building_zipcode').val();
			var city_state = $('input#building_citystate').val();
			var units = $('input#building_numunits').val();
			var parking = $('input#building_numparking').val();
			var storage = $('input#building_numstorage').val();
			//var fee = $('input#building_appfee').val();
			var description = $('textarea#building_buildingdesc').val();
			var emergency_contact_information = $('textarea#building_emergency_contact_information').val();
			var website = $('input#building_website').val();
			var employee_ids = '';
			var tag_group_id = $('#tag_group input:checked').val();
			var primary_employee_id = $('#employees_assigned_to_building span[id="default_employee_selection"][default="1"]').prev('a:[employees_id]').attr('employees_id');
			var phone_number = $('input#building_phone_number').val();
			var email = $('input#building_email').val();
			var integration_id = $('input#building_integration_id').val();
			var api_type = $('input#building_api_type').val();
			var api_key = $('input#building_api_key').val();
			
			if(primary_employee_id == undefined)
			{
				primary_employee_id = '';
			}
			
		    $('#employees_assigned_to_building a.listitem.selected').each(function()
			{
				if (employee_ids == '')
				{
					employee_ids = $(this).attr('employees_id');
				}
				else
				{
					employee_ids = employee_ids + ',' +$(this).attr('employees_id');
				}
			});

			if(jQuery.trim(name) == '')
			{
				//Comma separated building names
				alert('Please add a Building Name');
				return false;
			}
			
			if(jQuery.trim(address1) == '')
			{
				//Comma separated building names
				alert('Please add an Address');
				return false;
			}
			
			if(jQuery.trim(zip) == '')
			{
				//Comma separated building names
				alert('Please add a Zip Code');
				return false;
			}
			
			/*
			if(jQuery.trim(fee) == '')
			{
				//Comma separated building names
				alert('Please add a Fee');
				return false;
			}
			*/
			
			if (emergency_contact_information.length > 300)
			{
				// enforce max length for emergency_contact_information
				alert('Emergency contact information text cannot exceed 300 characters');
				return false;
			}
			
			if (alias.length > 4)
			{
				alert('Building alias text cannot exceed 4 characters');
				return false;				
			}
			
			var postvars = {
				is_commercial : is_commercial,
				name : name,
				alias: alias,
				use_alias: use_alias,
				use_apartment_alias: use_apartment_alias,
				address1 : address1,
				address2 : address2,
				zip : zip,
				city_state : city_state,
				units : units,
				parking : parking,
				storage : storage,
				/*fee : fee,*/
				description : description,
				emergency_contact_information : emergency_contact_information,
				website: website,
				employee_ids: employee_ids,
				tag_group_id: tag_group_id,
				primary_employee_id: primary_employee_id,
				phone_number: phone_number,
				email: email,
				integration_id: integration_id,
				api_type: api_type,
				api_key: api_key
			}
			
			$.post('/mobile/building/ajax_add_building', postvars, add_building_callback, 'json');
		}
		
		else if(dialog == '#editbldgamenities')
		{
			var id = $('input[type="hidden"][id="building_id"]:first').val();
			
			var postvars = {
				'amenities' : building_amenities,
				'type' : 'building',
				'building_id' : id
			}
			
			$.post('/mobile/building/ajax_edit_amenities', postvars, edit_amenities_callback, 'json')
		}
		
		else if(dialog == '#editcommamenities')
		{
			var id = $('input[type="hidden"][id="building_id"]:first').val();
			
			var postvars = {
				'amenities' : community_amenities,
				'type' : 'community',
				'building_id' : id
			}
			
			$.post('/mobile/building/ajax_edit_amenities', postvars, edit_amenities_callback, 'json')
		}
		
		else if(dialog == '#editbuilding')
		{
			var is_commercial = ($('#building_is_commercial').hasClass('selected')) ? 1 : 0;
			var building_id = $('input[type="hidden"][id="building_id"]:first').val();
			var name = $('input#building_buildingname').val();
			var alias = jQuery.trim($('input#building_alias').val());
			var use_alias = $('input#building_use_alias').is(':checked') ? 1 : 0;
			var use_apartment_alias = $('input#building_use_apartment_alias').is(':checked') ? 1 : 0;
			var address1 = $('input#building_address1').val();
			var address2 = $('input#building_address2').val();
			var zip = $('input#building_zipcode').val();
			var city_state = $('input#building_citystate').val();
			var units = $('input#building_numunits').val();
			var parking = $('input#building_numparking').val();
			var storage = $('input#building_numstorage').val();
			/*var fee = $('input#building_appfee').val();*/
			var description = $('textarea#building_buildingdesc').val();
			var emergency_contact_information = $('textarea#building_emergency_contact_information').val();
			var website = $('input#building_website').val();
			var employee_ids = '';
			var tag_group_id = $('#tag_group input:checked').val();
			var primary_employee_id = $('#employees_assigned_to_building span[id="default_employee_selection"][default="1"]').prev('a:[employees_id]').attr('employees_id');
			var phone_number = $('input#building_phone_number').val();
			var email = $('input#building_email').val();
			
			if(primary_employee_id == undefined)
			{
				primary_employee_id = '';
			}
			
		    $('#employees_assigned_to_building a.listitem.selected').each(function()
			{
				if (employee_ids == '')
				{
					employee_ids = $(this).attr('employees_id');
				}
				else
				{
					employee_ids = employee_ids + ',' +$(this).attr('employees_id');
				}
			});
		    
			if(jQuery.trim(building_id) == '')
			{
				//Comma separated building names
				alert('Building not found');
				return false;
			}
			
			if(jQuery.trim(name) == '')
			{
				//Comma separated building names
				alert('Please add a Building Name');
				return false;
			}
			
			if(jQuery.trim(address1) == '')
			{
				//Comma separated building names
				alert('Please add an Address');
				return false;
			}
			
			if(jQuery.trim(zip) == '')
			{
				//Comma separated building names
				alert('Please add a Zip Code');
				return false;
			}
			
			/*
			if(jQuery.trim(fee) == '')
			{
				//Comma separated building names
				alert('Please add a Fee');
				return false;
			}
			*/
			
			if (emergency_contact_information.length > 300)
			{
				// enforce max length for emergency_contact_information
				alert('Emergency contact information text cannot exceed 300 characters');
				return false;
			}
			
			if (alias.length > 4)
			{
				alert('Building alias text cannot exceed 4 characters');
				return false;				
			}
			
			var postvars = {
				is_commercial : is_commercial,
				building_id : building_id,
				name : name,
				alias: alias,
				use_alias: use_alias,
				use_apartment_alias: use_apartment_alias,
				address1 : address1,
				address2 : address2,
				zip : zip,
				city_state : city_state,
				units : units,
				parking : parking,
				storage : storage,
				/*fee : fee,*/
				description : description,
				emergency_contact_information : emergency_contact_information,
				website: website,
				employee_ids: employee_ids,
				tag_group_id: tag_group_id,
				primary_employee_id: primary_employee_id,
				phone_number: phone_number,
				email: email
			}
			
			$.post('/mobile/building/ajax_edit_building', postvars, edit_building_callback, 'json')
		}
		else if (dialog == '#edit_notificationcontact')
		{
			var settings_notif_email = Array();
			var settings_notif_phone = Array();
			var email_count = 0;
			var phone_count = 0;
			
			$("input[name^=settings_notif_email]").each(function()
			{
				settings_notif_email[email_count++] = $(this).val();
			});
			
			$("input[name^=settings_notif_phone]").each(function()
			{
				settings_notif_phone[phone_count++] = $(this).val();
			});
			
			postvars = {
				email_ids:			settings_notif_email,
				mobile_numbers:		settings_notif_phone	
			}
			
			$.post('/mobile/settings/ajax_edit_notifications_contacts', postvars, edit_notifications_contacts_callback, 'json');
		}
		else if (dialog == '#create_additional_contacts')
		{
			var email_html = '';
			var email_csv = '';
			var phone_html = '';
			var phone_csv = '';
			
			$("input[name^=settings_notif_email]").each(function()
			{
				var email_string = $(this).val();
				
				if(jQuery.trim(email_string) != '')
				{
					email_html = email_html + $(this).val()+"<br>";
					email_csv = email_csv + $(this).val()+',';
				}
			});
			
			$("input[name^=settings_notif_phone]").each(function()
			{
				var phone_string = $(this).val();
				
				if(jQuery.trim(phone_string) != '')
				{
					phone_html = phone_html + $(this).val()+"<br>";
					phone_csv = phone_csv + $(this).val()+',';
				}
			});
			
			if((jQuery.trim(email_html) != '')||(jQuery.trim(phone_html) != ''))
			{
				$('span.additional_contacts_title').show();
				
				$('div#additional_contacts_email').html(email_html);
				$('div#additional_contacts_phone').html(phone_html);
				
				$('input[name="additional_contacts_email"]').val(email_csv);
				$('input[name="additional_contacts_phone"]').val(phone_csv);
			}
			
			else
			{
				$('span.additional_contacts_title').hide();
				$('div#additional_contacts_email').html('');
				$('div#additional_contacts_phone').html('');
				$('input[name="additional_contacts_email"]').val('');
				$('input[name="additional_contacts_phone"]').val('');
			}
			
			closedialog();
		}
		else if ((dialog == '#edit_notificationsettings')||(dialog == '#employee_edit_notificationsettings'))
		{
			var settings_notif_email = Array();
			var settings_notif_phone = Array();
			var email_count = 0;
			var phone_count = 0;
			
			$("input[name^=settings_notif_email]").each(function()
			{
				settings_notif_email[email_count++] = $(this).val();
			});
			
			$("input[name^=settings_notif_phone]").each(function()
			{
				settings_notif_phone[phone_count++] = $(this).val();
			});
			
			var postvars = {
				email_ids:										settings_notif_email,
				mobile_numbers:									settings_notif_phone,
				maintenance_request_email: 						$('#maintenance_request_email').is(':checked'),
				maintenance_request_sms: 						$('#maintenance_request_sms').is(':checked'),
				maintenance_request_assignment_email: 			$('#maintenance_request_assignment_email').is(':checked'),
				maintenance_request_assignment_sms: 			$('#maintenance_request_assignment_sms').is(':checked'),
				maintenance_request_message_sent_email: 		$('#maintenance_request_message_sent_email').is(':checked'),
				maintenance_request_message_sent_sms: 			$('#maintenance_request_message_sent_sms').is(':checked'),
				maintenance_request_completion_email:			$('#maintenance_request_completion_email').is(':checked'),
				maintenance_request_completion_sms:				$('#maintenance_request_completion_sms').is(':checked'),
				maintenance_weekly_summary_email:				$('#maintenance_weekly_summary_email').is(':checked'),
				resident_account_confirmation_email: 			$('#resident_account_confirmation_email').is(':checked'),
				resident_account_confirmation_sms: 				$('#resident_account_confirmation_sms').is(':checked'),
				resident_lease_update_email:					$('#resident_lease_update_email').is(':checked'),
				resident_lease_update_sms:						$('#resident_lease_update_sms').is(':checked'),
				daily_tickler_email:							$('#daily_tickler_email').is(':checked'),
				maintenance_weekly_report_email:				$('#maintenance_weekly_report_email').is(':checked')
			}
			//console.log(postvars);
			
			if(dialog == '#edit_notificationsettings')
			{
				$.post('/mobile/settings/ajax_edit_notifications', postvars, edit_notifications_callback, 'json');
			}
			
			else
			{
				//Found in employee_details.js
				get_notification_text(postvars, function(response){
					if(response == 'success')
					{
						closedialog();
					}
				});
			}
		}
		
		else if(dialog == '#edit_employee_access')
		{
			var postvars = {
				email: $('div#edit_employee_access input#employee_email').val(),
				login: $('a.employeelogin2.selected').text(),
				account_id: $('input[type="hidden"][id="modal_employee_id"]').val(),
				login_option: $('.login_access_options.selected').attr('id'),
				password: $('div#edit_employee_access input#set_password').val(),
				confirm_password: $('div#edit_employee_access input#confirm_password').val()
			};
			
			//Found in employee_details.js
			edit_employee_access(postvars, function(response){
				if(response == 'success')
				{
					closedialog();
				}
			});
		}
		
		else if(dialog == '#add_forwarding_address')
		{
			var postvars = {
				tenant_id:					$('input[name="tenant_id"]:first').val(),
				address_1:					$('div#add_forwarding_address input[name="address_1"]:first').val(),
				address_2:					$('div#add_forwarding_address input[name="address_2"]:first').val(),
				city: 						$('div#add_forwarding_address input[name="city"]:first').val(),
				state: 						$('div#add_forwarding_address input[name="state"]:first').val(),
				zipcode: 					$('div#add_forwarding_address input[name="zipcode"]:first').val()
			}
			//console.log(postvars);
			
			$.post('/mobile/tenant/ajax_edit_forward_address', postvars, edit_forward_address_callback, 'json');
		}
		
		else if(dialog == '#recurring_request')
		{
			recurring_request_savedialog_callback(function(response){
				if(response == 'success')
				{
					closedialog();
				}
			});
		}
    }
	
	var states_array = [
    	'Alabama',
    	'Alaska',
    	'Arizona',
    	'Arkansas',
    	'California',
    	'Colorado',
    	'Connecticut',
    	'Delaware',
    	'District of Columbia',
    	'Florida',
    	'Georgia',
    	'Hawaii',
    	'Idaho',
    	'Illinois',
    	'Indiana',
    	'Iowa',
    	'Kansas',
    	'Kentucky',
    	'Louisiana',
   		'Maine',
    	'Maryland',
    	'Massachusetts',
    	'Michigan',
    	'Minnesota',
    	'Mississippi',
    	'Missouri',
    	'Montana',
    	'Nebraska',
    	'Nevada',
    	'New Hampshire',
    	'New Jersey',
    	'New Mexico',
    	'New York',
    	'North Carolina',
    	'North Dakota',
    	'Ohio',
    	'Oklahoma',
    	'Oregon',
    	'Pennsylvania',
    	'Rhode Island',
    	'South Carolina',
    	'South Dakota',
    	'Tennessee',
    	'Texas',
    	'Utah',
    	'Vermont',
    	'Virginia',
    	'Washington',
    	'West Virginia',
    	'Wisconsin',
  		'Wyoming'
	];
	
	$('input#state_autocomplete').autocomplete({
		source: function(request, response) {
			
			if(jQuery.trim(request.term) == '')
			{
				$('div#state_results').hide();
			}
			
			else
			{
				var post_vars = { search_filter: request.term };
				$.post('/mobile/tenant/ajax_state_search', post_vars, state_search_callback, 'json');
			}
		},
		minLength: 0,
		delay: 250,
		close: function( event, ui ) {
			$('div#state_results').hide();
		},
		select: function( event, ui ) {
			$('div#state_results').hide();
		}
	});
	
	function state_search_callback(data)
	{
		if(data.status == 'success')
		{
			if(jQuery.trim(data.message) !== '')
			{
				$('div#state_results').html(data.message).show();
			}
			
			else
			{
				$('div#state_results').hide();
			}
		}
		
		else
		{
			alert(data.message);
		}
	}
	
	$('a.state_search').live('click', function(){
		var state = $(this).text();
		$('input#state_autocomplete').val(state);
		$('div#state_results').hide();
	});
    
    var savedialog_callback = function(data)
    {
    	if ((data.status = 'success'))
    	{
    		if (data.redirect != undefined)
    		{
    			window.location = data.redirect;
    		}
    		else
    		{
    			closedialog();
    		}
    	}
    	
    	if ('data.status' == 'failed')
    	{
    		alert(data.message);
    	}
    }
    
    var save_tenant_callback = function(data)
    {
    	if (data.status == 'success')
    	{
    		closedialog();
    		/*
    		more_tenants_to_load = 'yes';
    		tenants_offset = 0;
    		search_filter = '';
    		load_tenant_list();
    		*/
    		clear_tenant_fields();
    		window.location = '/mobile/tenant/';
    	}
    	else
    	{
    		alert(data.message);
    	}
    }
	
	var add_building_callback = function(data)
    {
		if(data.status == 'success')
    	{
    		/*Will eventually ajax
			$('input#building_buildingname').val();
			$('input#building_address1').val();
			$('input#building_address2').val();
			$('input#building_zipcode').val();
			$('input#building_citystate').val();
			$('input#building_numunits').val();
			$('input#building_numparking').val();
			$('input#building_numstorage').val();
			$('input#building_appfee').val();
			$('textarea#building_buildingdesc').val();
			*/
			
			window.location = '/mobile/building/';
    	}
		
    	else
    	{
    		alert(data.message);
    	}
    }
	
	var edit_building_callback = function(data)
    {
		if(data.status == 'success')
    	{
			var is_commercial = ($('#building_is_commercial').hasClass('selected')) ? 1 : 0;
			var name = $('input#building_buildingname').val();
			var address1 = $('input#building_address1').val();
			var address2 = $('input#building_address2').val();
			var zip = $('input#building_zipcode').val();
			var city_state = $('input#building_citystate').val();
			var units = $('input#building_numunits').val();
			var parking = $('input#building_numparking').val();
			var storage = $('input#building_numstorage').val();
			var fee = $('input#building_appfee').val();
			var description = $('textarea#building_buildingdesc').val();
			
			$('div#address_display:first').html('<strong>'+address1+'</strong>');
			$('div#city_state_display:first').text(city_state+' '+zip);
			$('div#building_name_display:first').text(name);
			$('div#building_desc_display:first').text(description);
			$('div#units_display:first').text(units);
			$('div#parking_display:first').text(parking);
			$('div#storage_display:first').text(storage);
			$('div#fee_display:first').text('$'+fee);
			$('div#building_type').html(is_commercial ? 'Commercial' : 'Residential');
			
			if ((data.building.alias.length > 1) && ((data.building.use_alias == 1) || (data.building.use_apartment_alias == 1)))
			{
				$('div#building_alias_display').removeClass('gray');
				$('div#building_alias_display').html(data.building.alias);
			}
			else
			{
				$('div#building_alias_display').addClass('gray');
				$('div#building_alias_display').html('None');
			}
			
			if (employeesAssignedToBuilding.length < 1)
			{
				$('#building_employee_name_list').html('None');
			}
			
			else
			{
				/* Original, won't work with showing primary employee as employee_id does not come through
					var s = employeesAssignedToBuilding[0];
					
					/*for (var i = 1; i < employeesAssignedToBuilding.length; i++)
					{
						s = (s + '<br>' + employeesAssignedToBuilding[i]);
					}
					
					$('#building_employee_name_list').html(s);
				*/
				
				var display = '';
				var total = data.count_employee_list;
				var count = 1;
				
				$.each(data.employee_list, function(employee_id, employee_name){					
					if(employee_id == data.primary_employee_id)
					{
						display = display+employee_name+' <strong>(Primary)</strong> <br>';
					}
					
					else
					{
						display = display+employee_name+' <br>';
					}
					
					if(count >= total)
					{
						$('p#building_employee_name_list').html(display);
					}
					
					count++;
				});
			}
			
			if ((data.tag_group_name == undefined) || (data.tag_group_name == ""))
			{
				$("#division_display").css('display', 'none');
				$("#tag_group_name").html('');
			}
			else
			{
				$("#division_display").css('display', 'block');
				$("#tag_group_name").html(data.tag_group_name);
			}
	
			closedialog();
    	}
		
    	else
    	{
    		alert(data.message);
    	}
    }
	
	var edit_forward_address_callback = function(data)
	{
		if(data.status == 'success')
		{
			$('p#forward_address_p:first').html(data.address);
			closedialog();
		}
		
		else
		{
			alert(data.message);
		}
	}
    
    var edit_notifications_callback = function(data)
    {
 		if(data.status != 'success')
    	{
    		alert(data.message);
    	}
		
		else
		{
			closedialog();
			$('#text_maintenance_request_create').html(data.maintenance_request_notification_text);
			$('#text_maintenance_request_assignment').html(data.maintenance_request_assignment_notification_text);
			$('#text_maintenance_request_message_sent').html(data.maintenance_request_message_sent_notification_text);
			$('#text_maintenance_request_completion').html(data.maintenance_request_completion_text);
			$('#text_maintenance_weekly_summary').html(data.maintenance_weekly_summary_text);
			$('#text_resident_account_confirmation').html(data.resident_account_confirmation_notification_text);
			$('#text_resident_lease_update').html(data.resident_lease_update_notification_text);
			$('#text_daily_tickler').html(data.daily_tickler_text);
			$('#text_maintenance_weekly_report').html(data.maintenance_weekly_report_text);
			//window.location = window.location;
		}
    }
    
    var edit_notifications_contacts_callback = function(data)
    {
 		if(data.status != 'success')
    	{
    		alert(data.message);
    	}
		
		else
		{
			closedialog();
			window.location = window.location;
		}   	
    }
	
	var edit_amenities_callback = function(data)
    {
		if(data.status != 'success')
    	{
    		alert(data.message);
    	}
		
		else
		{
			closedialog();
		}
    }
	
	var add_employee_callback = function(data)
    {
		$('div#editemployee_spinner').hide();
		$('div#editemployee a[function="save"]').show();
		
		if(data.status == 'success')
    	{
			$('div#employee_search_filter_crumbs').hide();
			var pm = $('input[type="hidden"][id="employee_pm_id"]:first').val();
			
			if(jQuery.trim(pm) !== '')
			{ 
				$.get('/mobile/employee/employee_list_ajax/'+pm, function(view_data){
					
					if(view_data.status == 'success')
					{
						if(!jQuery.isEmptyObject(view_data.count_data))
						{
							var total_count = 0;
							
							$.each(view_data.count_data, function(building_name, employee_count){
								$('#buildingfilters span[id="'+building_name+'"]:first').text(employee_count);
								total_count += parseInt(employee_count);
							});
							
							$('#buildingfilters span[id="any_building"]:first').text(total_count);
						}
						
						$('#buildingfilters a').removeClass('current');
						$('#buildingfilters a:first').addClass('current');
						$('#rolefilters a').removeClass('current');
						$('#rolefilters a:first').addClass('current');
						$('input[name="search_filter"]').val('');
						$('tbody#employee_index_listing').remove();
						$(view_data.message).insertAfter('thead');
						closedialog();
						clear_employee_fields();
					}
					
					else
					{
						alert(view_data.message);
					}
				}, 'json');
			}
			
			else
			{
				alert('Property Manager not found');
			}
    	}
		
    	else
    	{
    		alert(data.message);
    	}
    }
	
	var edit_employee_callback = function(data)
    {
		$('div#editemployee_spinner').hide();
		$('div#editemployee a[function="save"]').show();
		
		if(data.status == 'success')
    	{
			var role = $('a#employee_changerole span.text').text();
			var fname = $('input#employee_firstname').val();
			var lname = $('input#employee_lastname').val();
			var email = $('input#employee_email').val();
			var cell = $('input#employee_cellphone').val();
			var office = $('input#employee_officephone').val();
			var fax = $('input#employee_faxnumber').val();
			var status = $('a.employeestatus.selected').text();
			var login = $('a.employeelogin.selected').text();
			var assign_request = $('a.assign_to_request.selected').text();
			var clean_cell = phone_format(cell);
			var clean_office = phone_format(office);
			var clean_fax = phone_format(fax);
			
			$('p#employee_name:first').text(fname+' '+lname);
			$('p#employee_email:first').text(email);
			$('p#employee_cell:first').text(clean_cell);
			$('p#employee_office:first').text(clean_office);
			$('p#employee_fax:first').text(clean_fax);
			$('input#employee_cellphone').val(clean_cell);
			$('input#employee_officephone').val(clean_office);
			$('input#employee_faxnumber').val(clean_fax);
			
			if(employeeBuildings.length)
			{
				var building_string = '';
				var len = employeeBuildings.length;
				
				for(var i = 0; i < len; i++)
				{
					var building_name = String(employeeBuildings[i]);
					building_string = building_string+building_name;
				  
					if(i !== len-1)
					{
						building_string = building_string+' \n';
					}
				}
				
				building_string = nl2br(building_string);
				
				$('p#employee_buildings:first').html(building_string);
			}
			
			if(status == 'Active Employee')
			{
				$('span#employee_status:first').text('Active');
			}
			
			else
			{
				$('span#employee_status:first').text('Inactive');
				login = 'No';
				assign_request = 'No';
				
				$('a.employeelogin').removeClass('selected');
				$('a.employeelogin:last').addClass('selected');
				$('a.assign_to_request').removeClass('selected');
				$('a.assign_to_request:last').addClass('selected');
			}
			
			if(login == 'Yes')
			{
				$('#login_allowed_text:first').text('Has login access');
				
				//Propagate to access control dialog
				$('.employeelogin2').removeClass('selected');
				$('.employeelogin2:first').addClass('selected');
				$('a#login_send_activation').show();
				$('div#edit_employee_access div#email_container').show();
				$('div#edit_employee_access div#options_container').show();
				$('#login_password_container').hide();
				$('.login_access_options').removeClass('selected');
				$('#password_activation_text').hide();
				$('#default_password_activation_text').show();
			}
			
			else
			{
				$('#login_allowed_text:first').text('Does not have login access');
				
				//Propagate to access control dialog
				$('.employeelogin2').removeClass('selected');
				$('.employeelogin2:last').addClass('selected');
				$('a#login_send_activation').hide();
				$('a#login_send_activation').removeClass('selected');
				$('#login_password_container').hide();
				$('.login_access_options').removeClass('selected');
				$('#password_activation_text').hide();
				$('#default_password_activation_text').show();
				$('div#edit_employee_access div#email_container').hide();
				$('div#edit_employee_access div#options_container').hide();
			}
			
			if(assign_request == 'Yes')
			{
				$('#can_assign_to_request_text').text('Can assign to requests');
			}
			
			else
			{
				$('#can_assign_to_request_text').text('Cannot assign to requests');
			}
			
			//Propagate email to access control
			$('div#edit_employee_access input#employee_email').val(email);
			
			closedialog();
			
			//Refresh page
			if(data.usertype_changed == '1')
			{
				location.reload();
			}
    	}
		
    	else
    	{
    		alert(data.message);
    	}
    }
	
	var clear_employee_fields = function ()
    {
        $('#buildinglistemployee a.listitem.selected').each(function(){
        	$(this).removeClass('selected');
        });
		
		$('#rolelistemployee a.listitem.selected').each(function(){
			$(this).removeClass('selected');													 
		});
		
		 employeeBuildings = new Array();
		
		$('a#employee_changebuilding span.text').html('<em>Select Building</em>');
		$('a#employee_changerole span.text').html('<em>Select Role</em>');
		$('input#employee_firstname').val('');
		$('input#employee_lastname').val('');
		$('input#employee_email').val('');
		$('input#employee_cellphone').val('');
		$('input#employee_officephone').val('');
		$('input#employee_faxnumber').val('');
		$('a.employeestatus').removeClass('selected');
		$('a.employeestatus:first').addClass('selected');
		$('a.employeelogin').removeClass('selected');
		$('a.employeelogin:first').addClass('selected');
		$('a.assign_to_request').removeClass('selected');
		$('a.assign_to_request:first').addClass('selected');
    }
    
    var update_tenant_callback = function(data)
    {
    	if (data.status == 'success')
    	{
    		var tenant_id = $('#tenant_id').val();
			
			/*Reloading page
			var tenant_email = $('input#tenant_email').val();
			$('input[name="current_tenant_email"]').val(tenant_email);
			*/
			
			//alert(data.message);
    		//update_tenant_edit_dialog_fields($data);
    		closedialog();
    		window.location = '/mobile/tenant/details/' + tenant_id;
    	}
		
    	else
    	{
    		alert(data.message);
    	}   	
    }
    
    var clear_tenant_fields = function ()
    {
        $('#residential_buildings a.listitem.selected').each(function() {
        		$('#tenant_changebuilding').html('Select Building');
        		$(this).removeClass('selected');
        	}
        );
        
        $('#tenant_aptnumber').val('');
        $('#tenant_firstname').val('');
        $('#tenant_lastname').val('');
        $('#tenant_email').val('');
        $('#tenant_cellphone').val('');
        $('#start_m').val('');
        $('#start_d').val('');
        $('#start_y').val('');
        $('#end_m').val('');
        $('#end_d').val('');
        $('#end_y').val('');
        $('#moveout_m').val('');
        $('#moveout_d').val('');
        $('#moveout_y').val('');
        $('#pets_cats').removeAttr('checked');
        $('#pets_dogs').removeAttr('checked');
        $('#monthtomonth').removeAttr('checked');
        $('#pets_other').val('');   	
    }
       
    $('a[function="close"]').click(closedialog);
	
    $('#mask').click(closedialog);
    
    $('a[function="save"]').click(savedialog);
    $('a[function="cancel"]').click(closedialog);
	$('a[function="cancel_revert"]').click(cancel_revert);
    
    // so you can only select one item from the divs that have
    // the class "singleselect"
    $('div.singleselect a.listitem').click(function () {
        $(this).closest('.innercontent').children('.listitem').removeClass('selected');
        $(this).addClass('selected');
    });
    
    $(window).keydown(function (event){ 
        if (event.which == 27) {
            closedialog();
        }
    });
    
    // closes the dialog once you selected something
    $('div.closeonselect a.listitem').click(function () {
        closedialog(150);
    });
    
    //// PROGRESS ARROW STUFF ////
    
    // formats the progress dialog on load
    /*
     var formatprogressdialog = function() {
        var currarrow = $('#arrows .selected').attr('status');
    
        
        if (currarrow == 'incomplete') {
        
            if ($('#pendingreasons').css('display') != 'none') {
                $('#pendingreasons').hide(anim_delay);
                $('#savecancelbottombuttons').hide(anim_delay);
            } else if ($('#completeddetails').css('display') != 'none') {
                $('#completeddetails').hide(anim_delay);
                $('#savecancelbottombuttons').hide(anim_delay);
            }
            
        } else if (currarrow == 'pending') {
            
            if ($('#completeddetails').css('display') != 'none') {
                $('#completeddetails').hide(anim_delay);
            }
            
            if ($('#pendingreasons').css('display') == 'none') {
                $('#pendingreasons').show(anim_delay);
            }
            
            if ($('#savecancelbottombuttons').css('display') == 'none') {
                $('#savecancelbottombuttons').show(anim_delay);
            }
            
        } else if (currarrow == 'complete') {
            if ($('#pendingreasons').css('display') != 'none') {
                $('#pendingreasons').hide(anim_delay);
            }
        
            if ($('#completeddetails').css('display') == 'none') {
                $('#completeddetails').show(anim_delay);
            }
            
            if ($('#savecancelbottombuttons').css('display') == 'none') {
                $('#savecancelbottombuttons').show(anim_delay);
            }
        }
     }
     */
    var formatprogressdialog = function()
    {
    	var currarrow = $('#arrows .selected').attr('status');
    	if (currarrow == 'incomplete')
    	{
    		$('#pendingreasons').hide(anim_delay);
    		$('#completeddetails').hide(anim_delay);
    		$('#savecancelbottombuttons').hide(anim_delay);
    	}
    	else if (currarrow == 'pending')
    	{    
    		if ($('#completeddetails').css('display') != 'none')
    		{
                $('#completeddetails').hide(anim_delay);
            }
            
            if ($('#pendingreasons').css('display') == 'none')
            {
                $('#pendingreasons').show(anim_delay);
            }
            
            if ($('#savecancelbottombuttons').css('display') == 'none')
            {
                $('#savecancelbottombuttons').show(anim_delay);
            }
            
        }
    	else if (currarrow == 'complete')
    	{
            if ($('#pendingreasons').css('display') != 'none')
            {
                $('#pendingreasons').hide(anim_delay);
            }
        
            if ($('#completeddetails').css('display') == 'none')
            {
                $('#completeddetails').hide(anim_delay);
            }
            
            if ($('#savecancelbottombuttons').css('display') == 'none')
            {
                $('#savecancelbottombuttons').show(anim_delay);
            }
        }
     }
    
    $('.progressarrow').click(function () {
        $('.progressarrow').removeClass('selected');
        $(this).addClass('selected');
        formatprogressdialog();
    });
    
    $('.pendingreason').click(function () {
        $('.pendingreason').removeClass('selected');
        $(this).addClass('selected');
    });
    
    // wrapping for inventoryitemlist, purely UI stuff
    var inventorylistsize_modal = function () {
        if (dialog != '#progressindicator' 
            || $('#arrows .selected').attr('status') != 'complete') {
            return;    
        }
        offset = 
            $('#inventoryitemlist_modal .inventoryitem:first').offset();
        
        if (offset == null) {
            return;
        }
        
        lowestinventoryoffset = offset.top;
        
        $('#inventoryitemlist_modal .inventoryitem span.text').each(function () {
            var off = $(this).offset().top;
            if (off > lowestinventoryoffset) {
                lowestinventoryoffset = off;
                var inventoryboxsize = 
                    parseInt($('#inventoryitemlist_modal').height());
                $('#inventoryitemlist_modal').css('height',inventoryboxsize+40);
                
            }
        });
    }
    
    // function for setting the hour 
    var edithour = function(h) {
        var hours = 0;
        var input = parseFloat($('#hoursinput').val());
        if (!isNaN(input)) {
            hours = input;
        }
        hours += h;
        if (hours < 0) {
            hours = 0;
        }
        
        $('#hoursinput').css('color','#333');
        $('#hoursinput').val(hours);
    }
    
    // changing the hours
    $('#uparrow').mousedown(function() {
        $(this).css('background-image','url(\''+images_folder+'/arrow_increase_sel.png\')');
    });
    
    $('#uparrow').mouseup(function() {
        $(this).css('background-image','url(\''+images_folder+'/arrow_increase.png\')');
        edithour(1);
    });
    
    $('#downarrow').mousedown(function() {
        $(this).css('background-image','url(\''+images_folder+'/arrow_decrease_sel.png\')');
    });
    
    $('#downarrow').mouseup(function() {
        $(this).css('background-image','url(\''+images_folder+'/arrow_decrease.png\')');
        edithour(-1);
    });
    $('#hoursinput').focus(function () {
        $('#hoursinput').css('color','#333');
    });
    
    // saving from the progress arrows to update the status
    $('#progressindicator .savecancelbottombuttons a.orangeroundedbutton').click(function () {
        if ($('#progress_incomplete').hasClass('selected')) {
            $('#status_selector').addClass('sel_incomplete');
            $('#status_selector').removeClass('sel_pending');
            $('#status_selector').removeClass('sel_complete');
            
            $('#status_selector span.text').text('Incomplete');
            
        } else if ($('#progress_pending').hasClass('selected')) {
            $('#status_selector').removeClass('sel_incomplete');
            $('#status_selector').addClass('sel_pending');
            $('#status_selector').removeClass('sel_complete');
            
            var reason = $('#pendinginput').val();
            if (reason.length <= 0 || $('#pendinginput').attr('focused') == 'no') {
                reason = $('a.pendingreason.selected').text();
            }
			
			if(jQuery.trim(pending_reason) !== '')
			{
				$('#status_selector span.text').html("<strong>"+pending_reason+"</strong>");
				$('#pendinginput').val('');
			}
			
			else
			{
				$('#status_selector span.text').html("<strong>"+pending_reason_other+"</strong>");
			}
			
        } else if ($('#progress_complete').hasClass('selected')) {
            $('#status_selector').removeClass('sel_incomplete');
            $('#status_selector').removeClass('sel_pending');
            $('#status_selector').addClass('sel_complete');
            
            
            
            $('#status_selector span.text').text('Complete');
        }
        
        var assignedto = $('#sel_assigned span.text').text();
        // making sure it's not pending/complete w/out an assignment
        //if (!$('#progress_incomplete').hasClass('selected')
        if ($('#progress_complete').hasClass('selected')
            && assignedto == 'No One') {
            //pushDialog('#employeelist');
        }
    });
    
    // I apologize for the mess of the stack.
    // dialog is the current dialog open
    // the stack represents what's gonna be opened after
    // the current dialog closes
    var pushDialog = function(whichdialog) {
        if (dialog == '') {
            opendialog(whichdialog);
        } else {
            dialogstack.push(whichdialog);
        }
    }
    
    $('#completed_addinventory').click(function () {
        pushDialog('#progressindicator');
        pushDialog('#addinventory');
        closedialog(0);
        
    });
    
    $('#changeassigned').click(function () {
    	//alert('#changeassigned');
        pushDialog('#progressindicator');
        pushDialog('#employeelist');
        closedialog();
    });
    
    $('#changeassigned_modal').click(function () {
    	//alert('#changeassigned_modal');
        pushDialog('#progressindicator');
        pushDialog('#empty_dialog');
        pushDialog('#employeelist');
        closedialog(0);
    })
    
    function changeassigned_dialog()
	{
    	//alert('#changeassigned_dialog');
    	pushDialog('#progressindicator');
    	pushDialog('#employeelist');
    	//closedialog();
    	$("#employeelist_close_button").css('display', 'none');
	}   
    
    //// END PROGRESS ARROW STUFF ////
    
    //// EMPLOYEE LIST STUFF ////
    $('#employeelist a.listitem').click(function () {
        $('#sel_assigned span.text').html($(this).text());
        
        // update the "assigned to" field
        $('#assignedtoperson strong').html('Assigned to '+$(this).text());
        
        //closedialog();
        
    });
    
    //// END EMPLOYEE LIST STUFF ////
    
    /// BUILDING LIST MODAL DIALOG ///
    
    // currentbuilding/currentapt now substitute for the buildings array
    currentbuilding = '';
    currentapt = '';
    
    var updateApartmentText = function () {
        
		var selected = '<strong>'+currentbuilding+'</strong>';
        
		//Newly added with resident info on create maintenance section change
		selected += '<br /><br />';
		
		if (currentapt != '')
        {
			if (cv_use_mobile_template)
        	{
        		selected += ', '+currentapt;
        	}
        	else
        	{
        		if(selected_apartment != undefined)
				{
					selected += '#'+selected_apartment;
				}
        	}
        }
		
        $('#selected_apartment').html(selected);
	   
	   /*
        var sel_apts = '';
        for (var b in buildings) {
            sel_apts += '<strong>'+b+'</strong>';
            var apts = buildings[b];
            if (apts.length > 0) {
                sel_apts += ': ';
                
                for (var i=0; i < apts.length; i++) {
                    sel_apts += apts[i] + ', ';
                }
                
            } else {
                sel_apts += ', ';
            }
        }

        $('#selected_apartment').html(sel_apts.substring(0,sel_apts.length-2));
        */
    }

    
    var populateBuildingList = function () {
        $('#buildinglist a.listitem').each(function () {
            var text = $.trim($(this).text());
            // select it if the currentbuilding is set to itself
            if (text == currentbuilding) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
            
            /*
            var selected = false;
            for (var b in buildings) {
                if (b == text) {
                    selected = true;
                }
            }
            
            if (selected) {
                $(this).addClass('selected');
            }
            */
        });
    }
    
    // list of buildings ids that have been selected
    // FOR SINGLE SELECT WE'RE NOT USING THIS
    //buildingids = new Array();
	
	function assign_primary_employee(idbuilding)
	{
		if(idbuilding != undefined)
		{
			postvars = {
    			idbuilding : idbuilding
    		};
			
			$.post("/mobile/maintenance/ajax_assign_primary_employee", postvars, function(data){
				if(data.status == 'success')
				{
					if(jQuery.trim(data.message) != '')
					{
						if($('a.assignment.selected').length == 0)
						{
							$('a.assignment.selected').removeClass('selected');
							
							var employee_name = $('a.assignment[employees_id="'+data.message+'"]').text();
							
							$('a.assignment[employees_id="'+data.message+'"]').addClass('selected');
							$('#sel_assigned span.text').html(employee_name);
						}
					}
				}
				
				else
				{
					alert(data.message);
				}
			
			}, 'json');
		}
	}
    
    $('#buildinglist a.listitem').click(function () {
		currentbuilding = $(this).text();
        currentapt = '';
        
        selected_idbuilding = $(this).attr('idbuilding');
        selected_apartment = $(this).attr('selected_apartment');
        selected_tenant_id = $(this).attr('tenant_id');
        
        updateApartmentText();
		assign_primary_employee(selected_idbuilding);
        
        /*    
        if ($(this).hasClass('selected')) {
            
            // remove the buildings
            $(this).removeClass('selected');
            delete buildings[sel_building];
            
            return;
        }
    
        
        var alreadyin = 0;
        for (var b in buildings) {
            if (b == sel_building) {
                alreadyin = 1;
            }
        }
        
        if (alreadyin == 0) {
            buildings[sel_building] = new Array();
        }

        $(this).addClass('selected');
        
        */
    });

    
        
    $('#buildinglist .orangeroundedbutton').click(function () {
        closedialog();
        updateApartmentText();
    });   
    
    /// END BUILDING LIST MODAL DIALOG ///
    
    /// BUILDING LIST -- SINGLE SELECTION for editing tenants ///
    
    // choosing a building for adding a tenant
    $('#tenant_changebuilding').click(function () {
        $(this).addClass('selected');
        pushDialog('#edittenant');
        pushDialog('#buildinglisttenant');
        closedialog(0);
    });
    
    $('#buildinglisttenant a.listitem').click(function () {
        
        $('#buildinglisttenant a.listitem').removeClass('selected');
        $(this).addClass('selected');
        $('#tenant_changebuilding').removeClass('selected');
        $('#tenant_changebuilding span.text').text($(this).text());
        $('#tenant_changebuilding span.action').show();
        
    });
    
    /// END BUILDING LIST -- SINGLE SELECTION ///
    
    /// MAKING AN EMPLOYEE SUB-DIALOGS /// added 25nov
    
    $('#employee_changerole').click(function () {
        $(this).addClass('selected');
        pushDialog('#editemployee');
        pushDialog('#rolelistemployee');
        closedialog();
    });
    
    $('#rolelistemployee a.listitem').click(function () {
		$('#employee_changerole').removeClass('selected');
        $('#employee_changerole span.text').text($(this).text());
        $('#employee_changerole span.action').show();
		
		//View only type account
		if($(this).text() == 'Regional Manager')
		{
			$('tr#assign_to_requests a').removeClass('selected');
			$('tr#assign_to_requests a:last').addClass('selected');
		}
		
		else
		{
			$('tr#assign_to_requests a').removeClass('selected');
			$('tr#assign_to_requests a:first').addClass('selected');
		}
    });
    
    $('#employee_changebuilding').click(function () {
        $(this).addClass('selected');
        pushDialog('#editemployee');
        pushDialog('#buildinglistemployee');
        closedialog(0);
    });
    
    $('#addbuilding #building_editemployees').click(function()
    {
        $(this).addClass('selected');
        pushDialog('#addbuilding');
        pushDialog('#employees_assigned_to_building');
        closedialog(0);   	   	
    });
    
    $('#editbuilding #building_editemployees').click(function()
    {
		$(this).addClass('selected');
		pushDialog('#editbuilding');
		pushDialog('#employees_assigned_to_building');
		closedialog(0);
		propagate_default_employee_selection();
    });
	
    // keeps track of all selected buildings for this employee!
    var employeeBuildings = new Array();
    var employeesAssignedToBuilding = new Array();
	
	//Pre-populates the employeeBuildings variable on page load for employee/details page on mobile
	if($('#buildinglistemployee a.listitem.selected').length)
	{
		$('#buildinglistemployee a.listitem.selected').each(function(){
			employeeBuildings.push($(this).text());													 
		});
	}
	
	
	if($('#employees_assigned_to_building a.listitem.selected').length)
	{
		$('#employees_assigned_to_building a.listitem.selected').each(function(){
			employeesAssignedToBuilding.push($(this).text());													 
		});
	}	
	
    $('#buildinglistemployee a.listitem').click(function ()
    {
    	if ($(this).attr('id') == 'all_buildings_element')
    	{
    		employeeBuildings = new Array();
    		
    		if ($(this).hasClass('selected'))
    		{
    	        $('#buildinglistemployee a.listitem.selected').each(function(){
    	        	$(this).removeClass('selected');
    	        });
    		}
    		else
    		{
    	        $('#buildinglistemployee a.listitem.selected').each(function(){
    	        	$(this).removeClass('selected');
    	        });
    	        
    	        $('#buildinglistemployee a.listitem').each(function(){
    	        	$(this).addClass('selected');
    	        	if ($(this).attr('id') !== 'all_buildings_element')
    	        	{
    	        		employeeBuildings.push($(this).text());
    	        	}
    	        });
    	        
    	        employeeBuildings.sort();
    		}
    		return;
    	}
    	else if ($(this).hasClass('selected'))
        {
			if ($('#all_buildings_element').hasClass('selected'))
    		{
    			$('#all_buildings_element').removeClass('selected');
    		}
    		
            $(this).removeClass('selected');
			
			//This 'if' is needed because IE8 does not properly support indexOf
			if(!employeeBuildings.indexOf)
			{
				var building_name = $(this).text();
				var idx = jQuery.inArray(building_name, employeeBuildings);
			}
			
			else
			{
				var idx = employeeBuildings.indexOf($(this).text());
			}
			
			if (idx >= 0)
            {
                employeeBuildings.splice(idx,1);
            }
			
            return;
        }
    	else
    	{
    		$(this).addClass('selected');
    		employeeBuildings.push($(this).text());
    		employeeBuildings.sort();
    	}
    });
    
    $('#employees_assigned_to_building a.listitem').click(function ()
    {
    	if ($(this).attr('id') == 'all_employees_element')
    	{
			employeesAssignedToBuilding = new Array();
    		
    		if ($(this).hasClass('selected'))
    		{
				//Hide control to select as default employee
				$('span#default_employee_selection').attr('default', '0');
				$('span#default_employee_selection a.options').html('Make Primary Employee');
			   
				$('#employees_assigned_to_building span#default_employee_selection').hide();
				$('#employees_assigned_to_building span#default_employee_text').hide();
				
				$('#employees_assigned_to_building a.listitem.selected').each(function(){
    	        	$(this).removeClass('selected');
    	        });
    		}
    		else
    		{
    	        //Show control to select as default employee
				$('#employees_assigned_to_building span#default_employee_selection').show();
				$('#employees_assigned_to_building span#default_employee_text').show();
				
				$('#employees_assigned_to_building a.listitem.selected').each(function(){
    	        	$(this).removeClass('selected');
    	        });
    	        
    	        $('#employees_assigned_to_building a.listitem').each(function(){
    	        	$(this).addClass('selected');
    	        	if ($(this).attr('id') !== 'all_employees_element')
    	        	{
    	        		employeesAssignedToBuilding.push($(this).text());
    	        	}
    	        });
    	        
    	        employeesAssignedToBuilding.sort();
    		}
    		return;
    	}
    	else if ($(this).hasClass('selected'))
        {
			//Remove control to select as default
			$(this).parent('span#default_employee_selection').attr('default', '0');
			
			$(this).next('span#default_employee_selection').hide();
			$(this).next('span#default_employee_selection').next('span#default_employee_text').hide();
			
			if ($('#all_employees_element').hasClass('selected'))
    		{
    			$('#all_employees_element').removeClass('selected');
    		}
    		
            $(this).removeClass('selected');
            var idx = employeesAssignedToBuilding.indexOf($(this).text());
            if (idx >= 0)
            {
            	employeesAssignedToBuilding.splice(idx,1);
            }
            return;
        }
    	else
    	{
			//Show control to select as default
			$(this).next('span#default_employee_selection').show();
			$(this).next('span#default_employee_selection').next('span#default_employee_text').show();
			
			$(this).addClass('selected');
    		employeesAssignedToBuilding.push($(this).text());
    		employeesAssignedToBuilding.sort();
    	}
    });
	
	$('#employees_assigned_to_building span#default_employee_selection a.options').click(function(){
		var set_default = $(this).parent('span#default_employee_selection').attr('default');
		var test_example_number = $(this).parent('span#default_employee_selection').prev('a.listitem').attr('employees_id');
		
		if((set_default != undefined)&&(test_example_number != undefined))
		{
			if(set_default == 0)
			{
				//Having to add the background css here because Safari is not propagating properly
				$('span#default_employee_selection').attr('default', '0');
				$('span#default_employee_selection a.options').html('Make Primary Employee').css('background','#edebe6');
				
				$(this).parent('span#default_employee_selection').attr('default', '1');
				$(this).html('Is Primary Employee').css('background','#E35D1A');
			}
			
			else
			{
				$(this).parent('span#default_employee_selection').attr('default', '0');
				$(this).html('Make Primary Employee').css('background','#edebe6');
			}
		}
	});
    
    $('#buildinglistemployee .orangeroundedbutton').click(function () {
		$('#employee_changebuilding').removeClass('selected');
        $('#employee_changebuilding span.action').show();
        var c = employeeBuildings.length;
		
		if (c == 1) {
			$('#employee_changebuilding span.text').text(employeeBuildings[0]);
        } else {
            var s = c + " buildings";
            $('#employee_changebuilding span.text').html('<span class="mult">'+s+'</span>');
        }
		
		closedialog(0);
    });
    
    $('#employees_assigned_to_building .orangeroundedbutton').click(function ()
    {
    	//alert('debug: clicked employees_assigned_to_building .orangeroundedbutton');
		$('#building_editemployees').removeClass('selected');
        $('#building_editemployees span.action').show();
        var c = employeesAssignedToBuilding.length;
		
		if (c == 1) {
			$('#building_editemployees span.text').text(employeesAssignedToBuilding[0]);
        } else {
            var s = c + " employees";
            $('#building_editemployees span.text').html('<span class="mult">'+s+'</span>');
        }
		
		closedialog(0);
    });
    
    /// END MAKING AN EMPLOYEE SUB-DIALOGS ///
    
    /// APARTMENT LIST MODAL DIALOG ///
    tdialog = '';
    // the key in buildings is a string, which maps to an array
    // the array has more strings that tell you the apartment numbers
    // if the array is empty, we assume it's just the whole building
    // NOT USING THIS FOR SINGLE SELECT
    //buildings = new Array();
    
    // DECLARED ABOVE FOR SINGLE SELECT
    //currentbuilding = '';
    $('#buildings a.listitem').click(function () {
		$(this).addClass('selected');
        tdialog = $(this).attr('dialog');
        
        // THIS IS FOR DEBUG JUST TO CHECK OUT THE UI!
        if (tdialog == undefined) {
            tdialog = '#building_default';
        }
        // NOT FOR PRODUCTION
        
        var barray = $(this).text().toString().split('<');
        currentbuilding = barray[0];
        
        $('#apartmentlist h3').html(currentbuilding);
        $('#apartmentlist h3').animate({'margin-left':'4.6em'}, 'fast');
        $('#buildings').hide(250);
        $(tdialog).show(250);
        
        /*
        
        $(tdialog+' a.listitem').removeClass('selected');
        $(tdialog+' a.listitem').each(function () {
            var arr = $(this).text().toString().split('(');
            var text = $.trim(arr[0]);
            var selected = false;
            var apts = buildings[currentbuilding];
            if (apts.indexOf(text) >= 0) {
                $(this).addClass('selected');
            }
        });
        
        */
        
    });
    
    $('.tenantlist a.back').click(function () {
		$(tdialog).hide(250);
        $('div#buildings').show(250);
        $('#apartmentlist h3').html('Select Building');
        $('#apartmentlist h3').animate({'margin-left':'1em'}, 'fast');
        $('#buildings a.listitem').removeClass('selected');
    });
    
    $('.tenantlist a.listitem').click(function () {
        var idbuilding = $(this).attr('idbuilding');
		assign_primary_employee(idbuilding);
		currentapt = $(this).html();
		selected_apartment = $(this).attr('selected_apartment');
		$('.tenantlist a.listitem').removeClass('selected');
        $(this).addClass('selected');
        updateApartmentText();
        // *** start of hack put in to force single select, remove we go to multi-select ***
        selected_idbuilding = $(this).attr('idbuilding');
        selected_tenant_id = $(this).attr('tenant_id');
        //alert(selected_idbuilding + ', ' + selected_apartment + ', ' + selected_tenant_id);
        closedialog();
        // *** end of hack - put in to force single select, remove we go to multi-select ***
        
        /*
        // removing the item from the list
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            var aptarray = $(this).text().toString().split('(');
            var sel_apt = $.trim(aptarray[0]);
            
            var apts = buildings[currentbuilding];
            var idx = apts.indexOf(sel_apt);
            if (idx != -1) {
                apts.splice(idx, 1);
            }
            
            // what if it's empty now?
            if (apts.length == 0) {
                delete buildings[currentbuilding];
            }
            
            return;
        }
        
        $(this).addClass('selected');
        
        var aptarray = $(this).text().toString().split('(');
        var alreadyin = 0;
        var sel_apt = $.trim(aptarray[0]);
        
        if (!(currentbuilding in buildings)) {
            buildings[currentbuilding] = new Array();
        }
        
        var apts = buildings[currentbuilding];
        
        for (var apt in apts) {
            if (apts[apt] == sel_apt) {
                alreadyin = 1;
            }
        }
        
        if (alreadyin == 0) {
            apts.push(sel_apt);
        }
        */
        
    });
        
    $('#apartmentlist .orangeroundedbutton').click(function () {
        updateApartmentText();
    });
	
	$('div#apartmentlist div.innercontent input[name="search_units"]').keyup(function(){
		var value = jQuery.trim($(this).val());
		
		if(value !== '')
		{
			$('div#apartmentlist div.innercontent div.tenantlist a[class*="listitem"]').each(function()
			{
				var unit_tenant_text = $(this).text();
				var compare = new RegExp(value, "gi");
				
				compare = unit_tenant_text.match(compare);
					
				if(compare != null)
				{
					$(this).attr('show', 'yes');
				}
				
				else
				{
					$(this).attr('show', 'no');
				}
			});
			
			$('div#apartmentlist div.innercontent div.tenantlist a[class*="listitem"][show="no"]').hide();
			$('div#apartmentlist div.innercontent div.tenantlist a[class*="listitem"][show="yes"]').show();
		}
		
		else
		{
			$('div#apartmentlist div.innercontent div.tenantlist a[class*="listitem"]').show();
		}
	});
    
    
    /// END APARTMENT LIST MODAL DIALOG ///    
    
    
    /// INVENTORY AFFECTED DIALOG ///
    
    // duplicate of the bindbuttons method inside html file, because
    // it is now dynamically loaded through the 'items' object
    var bindButtons = function () {
        $('.invplusminus').click(function () {
            var qty = 0;
            var input = parseInt($(this).siblings('.invcount').val());
            if (!isNaN(input)) {
                qty = input;
            }
            if ($(this).hasClass('invplus')) {
                qty += 1;
            } else if ($(this).hasClass('invminus')) {
                qty -= 1;
            }
            
            if (qty < 0) {
                qty = 0;
            }
            
            $(this).siblings('.invcount').val(qty);
            
            if (qty == 0) {
                removeselected($(this).siblings('.invcount').attr('name'));
            } else {
                addselected($(this).siblings('.invcount').attr('name'));
            }
            
        });
        
        $('.invcount').click(function () {
            $(this).focus();
            $(this).select();
        });
    }
    
    // loads from the 'items' object.
    var populateinventorylist = function () {
        $('#addinventory .inventorycounter').css('display','none');
        $('#addinventory a.listitem').removeClass('selected');
        
        //alert('in populateinventoryList()');
        
        for (item in items) {
            if (items[item] > 0) {
                $('#addinventory a.listitem').each(function () {
                    //if ($(this).text() == item) {
                	if ($(this).attr('inventory_id') == item) {
                        $(this).addClass('selected');
                        //$('div.inventorycounter[name="'+item+'"]').css('display','block');
                        //$('input.invcount[name="'+item+'"]').val(items[item]);
                        $('div.inventorycounter[inventory_id="'+item+'"]').css('display','block');
                        $('input.invcount[inventory_id="'+item+'"]').val(items[item]);
                        $(this).attr('hasButtons','yes');
                    }
                })
                
            } else {
            
                $('#addinventory a.listitem').each(function () {
                    //if ($(this).text() == item) {
                	if ($(this).attr('inventory_id') == item) {
                        $(this).attr('hasButtons','no');
                    }
                })
            } 
        }
    }
    
    
    // anybody that cares about the items being updated put your code here!
    var itemsUpdated = function () {
        var str = '';
        var inventory_name;
        var category_name;
        var sel_inventory_name;
        
        for (var item in items) {
            if (items[item] > 0) {
            	//alert('itemsUpdated - item: ' + item);
            	sel_inventory_name = 'a.listitem[inventory_id="' + item + '"]';
            	//alert(sel_inventory_name);
            	inventory_name = $(sel_inventory_name).attr('inventory_name');
            	//alert(inventory_name);
            	category_name = $(sel_inventory_name).attr('category_name');
            	//alert(category_name);
            	//alert('inventory_name: ' + inventory_name);
                str += '<a class="inventoryitem"><span class="text">'
                    + inventory_name +' <span class="gray">(' + category_name + ')</span></span><span class="number">'
                    + items[item] +'</span></a>';
            } 
        }
        
        if (str.length > 0) {
            $('#inventoryitemlist').html(str);
            
            if ($('#inventoryitemlist_modal').css('display') != 'none') {
                $('#inventoryitemlist_modal').html(str);
            }
        }
        
    	if (maintenance_record_mode != 'create')
    	{
    		items_serialized = serializeArray(items);
    		postvars = {
    				idmaintenance: idmaintenance,
    				items : items_serialized
    		};
        
    		$.post("/mobile/maintenance/ajax_save_inventory", postvars, savedialog_callback, 'json');
    	}
    	else
    	{
    		closedialog();
    	}
    }
    
    $('#addinventory .savecancelbottombuttons .orangeroundedbutton').click(function () {
        $('#addinventory .invcount').each(function () {
            //var name = $(this).attr('name');
        	var inventory_id = $(this).attr('inventory_id');
            var num = parseInt($(this).val());
            //items[name] = num;
            items[inventory_id] = num;
        });
        
        // callback for items being updated
        itemsUpdated();
        
        
    });
    /// END INVENTORY AFFECTED DIALOG ///
	
	
	// MAINTENANCE REQUEST ATTACHMENT LOGIC //
	function setFileName()
	{
		$('#filename').val($('#file').val().replace(/C:\\fakepath\\/i, ''));
	}
	
	$('input#upload_attachment_button').live('click', function(){
		
		var desc = $('input[id="attachmentdesc"][name="attachment_name"]').val();
		
		if(jQuery.trim(desc) !== '')
		{
			setFileName();
			$(this).hide(150);
			$('#spinner_uploading').show(anim_delay);
			
			document.getElementById('form_attachment').onsubmit=function(){
				//'upload_target' is the name of the iframe
				document.getElementById('form_attachment').target = 'upload_target';
				$('iframe#upload_target').attr('onload', 'uploadDone();');
			}
		}
		
		else
		{
			alert('Please add a description');
			return false;
		}
	});
	// END MAINTENANCE ATTACHMENT LOGIC
	
	//// BUILDING DETAILS DIALOGS ////
   
    // keeps track of building amenities
    building_amenities = new Array();
	
	if($('#editbldgamenities a.listitem.selected').length)
	{
		$('#editbldgamenities a.listitem.selected').each(function(){
			building_amenities.push($(this).text());													 
		});
		
		$('#building_amenities_nothing').hide();
		$('#building_amenities_box').show();
		
		var aitems = "";
		
		for(var aitem in building_amenities)
		{
			aitems += '<div class="itembox">'+building_amenities[aitem]+'</div>';
		}
		
		$('#building_amenities_box').html(aitems);
	}
    
    // hello Chet or Mike, call this function 
    // when you're loading from the AJAX call
    var populateBuildingAmenities = function () {
        $('#editbldgamenities a.listitem').each(function () {
            if (building_amenities.indexOf($(this).text()) >= 0) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
        });
    }
    
    $('#editbldgamenities a.listitem').click(function () {
        var aitem = $(this).text();
        
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            var idx = building_amenities.indexOf(aitem);
            if (idx > -1) {
                building_amenities.splice(idx,1);
            }
            return;
        }
        
        building_amenities.push(aitem);
        $(this).addClass('selected');
    });
    
    $('#editbldgamenities a.orangeroundedbutton').click(function () {
        if (building_amenities.length == 0) {
            $('#building_amenities_nothing').show();
            $('#building_amenities_box').hide();
        } else {
            $('#building_amenities_nothing').hide();
            $('#building_amenities_box').show();
            
            var aitems = "";
            for (var aitem in building_amenities) {
                aitems += '<div class="itembox">'+building_amenities[aitem]+'</div>';
            }
            
            $('#building_amenities_box').html(aitems);
            $('#building_amenities_box').css('height',0);
            var top = $('#building_amenities_box .itembox:first').offset().top;
            var bottom = $('#building_amenities_box .itembox:last').offset().top;
            
            var diff = bottom-top;
            $('#building_amenities_box').css('height','+='+diff);
            
            closedialog(0);
        }
    });
    
    // now for community amenities, almost the same thing
    
    // keeps track of building amenities
    community_amenities = new Array();
	
	if($('#editcommamenities a.listitem.selected').length)
	{
		$('#editcommamenities a.listitem.selected').each(function(){
			community_amenities.push($(this).text());													 
		});
		
		$('#community_amenities_nothing').hide();
        $('#community_amenities_box').show();
		
		var aitems = "";
		
		for(var aitem in community_amenities)
		{
			aitems += '<div class="itembox">'+community_amenities[aitem]+'</div>';
		}
		
		 $('#community_amenities_box').html(aitems);
	}
    
    // hello Chet or Mike, call this function 
    // when you're loading from the AJAX call
    var populateBuildingAmenities = function () {
        $('#editcommamenities a.listitem').each(function () {
            if (community_amenities.indexOf($(this).text()) >= 0) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
        });
    }
    
    $('#editcommamenities a.listitem').click(function () {
        var aitem = $(this).text();
        
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            var idx = community_amenities.indexOf(aitem);
            if (idx > -1) {
                community_amenities.splice(idx,1);
            }
            return;
        }
        
        community_amenities.push(aitem);
        $(this).addClass('selected');
    });
    
    $('#editcommamenities a.orangeroundedbutton').click(function () {
        if (community_amenities.length == 0) {
            $('#community_amenities_nothing').show();
            $('#community_amenities_box').hide();
        } else {
            $('#community_amenities_nothing').hide();
            $('#community_amenities_box').show();
            
            var aitems = "";
            for (var aitem in community_amenities) {
                aitems += '<div class="itembox">'+community_amenities[aitem]+'</div>';
            }
            
            $('#community_amenities_box').html(aitems);
            $('#community_amenities_box').css('height',0);
            var top = $('#community_amenities_box .itembox:first').offset().top;
            var bottom = $('#community_amenities_box .itembox:last').offset().top;
            
            var diff = bottom-top;
            $('#community_amenities_box').css('height','+='+diff);
            
            
            closedialog(0);
        }
    });
    
   //// END BUILDING DETAILS DIALOGS ////
   //// SETTINGS CALLABACKS ////
    var emergency_contact_messag_callback = function(data)
    {
    	if (data.status == 'success')
    	{
    		$('#emergency_message_text').html(data.emergency_contact_message);
    		closedialog();
    	}
    	else
    	{
    		alert(data.message);
    	}
    };
    
    var edit_password_callback = function(data)
    {
    	if (data.status == 'success')
    	{
    		alert('Your password has been updated');
    		closedialog();
    	}
    	else
    	{
    		alert(data.message);
    	}    	
    };
    
    var edit_pm_profile_callback = function(data)
    {
    	if (data.status == 'success')
    	{
    		alert('Your profile has been updated');
    		/*
         	$('#settings_businessname').val(data['settings']['business_name']);
        	$('#settings_business_contact_name').val(data['settings']['business_contact_name']);
        	$('#settings_address_line_1').val(data['settings']['address_line_1']);
        	$('#settings_address_line_2').val(data['settings']['address_line_2']);
        	$('#settings_zip_code').val(data['settings']['zipcode']);
        	$('#settings_city_state').val(data['settings']['citystate']);
        	$('#settings_phone_number').val(data['settings']['businessphone']);
        	$('#settings_contact_name').val(data['settings']['office_contact_name']);
        	$('#settings_contact_phone').val(data['settings']['officephone']);
        	$('#settings_fax').val(data['settings']['faxnumber']);
        	$('#settings_contact_email').val(data['settings']['officeemail']);
        	$('#settings_description').val(data['settings']['companydesc']);
        	$('#settings_website').val(data['settings']['website']);
        	$('#settings_facebook').val(data['settings']['facebookpage']);
    		$('#settings_office_hours_weekday').val(data['settings']['hoursweekday']);
    		$('#settings_office_hours_weekend').val(data['settings']['hoursweekend']);	   		
    		*/
    		closedialog();
    		//window.location = window.location;
    		location.reload();
    	}
    	else
    	{
    		alert(data.message);
    	}
    };
    
    var edit_employee_profile_callback = function(data)
    {
     	if (data.status == 'success')
    	{
    		alert('Your profile has been updated');
    		closedialog();
    		window.location = window.location;
    	}
    	else
    	{
    		alert(data.message);
    	}   	
    };
   
   //// SETTINGS DIALOGS /////
    
    // PROFILE
    $('#edit_emergencymessage .orangeroundedbutton').click(function ()
    {
    	var post_vars = {
    		account_id: 				account_id,
    		emergency_contact_message:	$('textarea#settings_emergencymessage').val()
    	};
    	
    	$.post('/mobile/settings/ajax_edit_emergency_contact_message', post_vars, emergency_contact_messag_callback, 'json');      
    });
    
    $('#changepassword .orangeroundedbutton').click(function()
    {
    	var post_vars = {
    		account_id:					account_id,
    		current_password:			$('#settings_currentpw').val(),
    		new_password:				$('#settings_newpw').val(),
    		confirm_password:			$('#settings_confirmpw').val()
    	};
    	
    	$.post('/mobile/settings/ajax_edit_password', post_vars, edit_password_callback, 'json');    

    });
    
    $('#settings_editprofile .orangeroundedbutton').click(function()
    {
		if (user_account_type == 'pm')
    	{
    		var post_vars = {
        		account_id:				account_id,
        		business_name:			$('#settings_businessname').val(),
        		business_contact_name:	$('#settings_business_contact_name').val(),
        		address_line_1:			$('#settings_address1').val(),
        		address_line_2:			$('#settings_address2').val(),
        		zip_code:				$('#settings_zipcode').val(),
        		city_state:				$('#settings_citystate').val(),
        		phone_number:			$('#settings_businessphone').val(),
        		contact_name:			$('#settings_office_contact_name').val(),
        		contact_phone:			$('#settings_officephone').val(),
        		fax:					$('#settings_faxnumber').val(),
        		contact_email:			$('#settings_officeemail').val(),
        		description:			$('#settings_companydesc').val(),
        		website:				$('#settings_website').val(),
        		facebook:				$('#settings_facebookpage').val(),
    			office_hours_weekday:	$('#settings_hoursweekday').val(),
    			office_hours_weekend:	$('#settings_hoursweekend').val(),
				twitter:				$('#settings_twitterpage').val()
        	};
    	
    		$.post('/mobile/settings/ajax_edit_pm_profile', post_vars, edit_pm_profile_callback, 'json');
    	}
    	else if (user_account_type == 'employee')
    	{
    		var post_vars = {
        		account_id:				account_id,
				first_name:				$('#settings_first_name').val(),
				last_name:				$('#settings_last_name').val(),
				email:					$('#settings_email').val(),
				cell_phone:				$('#settings_cell_phone').val(),
				office_phone:			$('#settings_office_phone').val(),
				fax:					$('#settings_fax').val()	
        	};
    	
    		$.post('/mobile/settings/ajax_edit_employee_profile', post_vars, edit_employee_profile_callback, 'json'); 		
    	}
    });
    
    //// END SETTINGS DIALOG ////
    
});