﻿
//used for display in the map
var arrResults = new Array();  
var mapAddress = "";
var mapAddressDescription = "";

//HARDCODED VALUES that correspond to the image_category in the rt_property_image
var building_category = "Building";
var unit_category = "Property";
var floor_plan_category = "Floor Plan";

//The number of thumbnail images to display in the details section
var thumb_display_number = 3;

//CREATE Rental Namespace (need to move all objects into it eventually)
AV.Rental = {};


Ext.EventManager.on(window, 'load', function(){
    
  //Perform the default query              
  
  //Commented 3/10/2008
  /*
  var q_string = "default=default&action=search";
  AV.results_store.createStore(q_string);         
  AV.results_store.getStore().load({callback: resultsLoaded});                         
  AV.results_panel.getPanel(); 
  
  //Show the searching dialog
  dlgProgress.show(); 
  
  */
  
  var returnMap = new Ext.KeyMap(Ext.get("div_main"), {
              key: 13, // or Ext.EventObject.ENTER
              fn: doSearch,
              scope: Ext.get("div_main")
          });
});

AV.results_store = new function()
{
  var store; 
  var reader;
  
  return{
    
        createStore: function(q_string){
                   
          store = new Ext.data.Store({              
              url: 'property_search.asp?' + q_string ,

              // the return will be XML, so lets set up a reader
              reader: new Ext.data.XmlReader({
                     record: 'AvailUnit',
                     id: 'property_id'
                 }, [                    
                                          
                     'property_id',   //Added by AV as a unique identifier
                     'Building', 
                     'Unit', 
                     'Address', 
                     'City', 
                     'State', 
                     'Zip', 
                     {name: 'Rent', mapping: 'Rent', type:'float'}, //specify float to enable numeric sort
                     'Description',
                     'Area', 
                     'Status', 
                     'Beds', 
                     'Baths', 
                     {name: 'SquareFeet', mapping: 'SquareFeet', type:'int'},           
                     {name: 'UnitType', mapping: 'Type'}, 
                     {name: 'FloorPlan', mapping: 'PriceCode'},    //basically, the floorplan code (used to display floorplan  images
                     {name: 'YearBuilt', mapping: 'Built'},       //changed from 'Age'
                     {name: 'SecurityDeposit', mapping: 'SecDep'}, 
                     'Details',
                     'DefaultImage',
                     {name: 'Thumbs', mapping: 'Thumbs'},
                     'CentralAir',
                     'ACWindowUnit',
                     'Attic',
                     'Basmnt',
                     'BkArea',
                     'BonRm',
                     'Cats',
                     'ComPg',
                     'ComPl',
                     'ComTC',
                     'CrptFl',
                     'DW',
                     'Deck',
                     'DinRm',
                     'Dis',
                     'Dogs',
                     'ElecWa',
                     'ElHt',
                     'FmRm',
                     'Fence',
                     'FirePl',
                     'Fit',
                     'Foyer',
                     'Gar2',
                     'Garage',		
                     'Gas',
                     'GasWH',
                     'HOA',
                     'HWflr',
                     'Kitchn',
                     'Lake',
                     'Laundy',
                     'LaundryRm',
                     'LawnCr',
                     'LinFl',
                     'LivRm',
                     'LTOwn',
                     'Metro',
                     'Micro',
                     'PaidWS',
                     'Parking',
                     'Patio',
                     'PetsNg',
                     'PetsNo',
                     'PetsYs',
                     'Pond',
                     'Pool',
                     'Porch',
                     'Range',
                     'RbCt',
                     'RecFld',
                     'Refrig',
                     'Sec8',
                     'Secure',
                     'Shop',
                     'Storag',
                     'StorAr',
                     'SwgSet',
                     'TC',
                     'TileFl',
                     'WD'
                 ])
          }); 
          
          //set the Default sort
          store.setDefaultSort("Rent", "asc");         
          
          store.on("load", function(){
            temp_xml = store.reader.xmlData;
          });   
          
          //Increase proxy's timeout due to the fact that some of the jenark's queries can take many minutes
          store.proxy.conn.timeout = 360000;
          
        },
        getStore: function(){     //data is not loaded until .load is called
          if(!store)
            this.createStore();
            
          return store;
        }     
  }
  
}();


//ADDED FOR RENTAL DEMO (3/31/08)
function getDemoBrochureLink()
{ 
  if(assnId == '10613' || assnId == '12665')
  {  
    //return ' | <a href="http://www.associationvoice.com/hoa/assn10613/documents/Property_Management.pdf" target="_blank">Brochure</a>';
    return '';

  }    
  else
    return '';
}

//ADDED FOR RENTAL DEMO (3/31/08
function getDemoApplicationLink(actionEl)
{ 
  if(assnId == '10613' || assnId == '12665')
  {      
   //return ' | <a href="http://www.associationvoice.com/forms/formDisplay.asp?frm_id=27827" target="_blank">Apply</a>';
   //return ' | <a href="http://www.associationvoice.com/Prospects/apply.asp" target="_blank">Apply</a>';
   //this avoids the message to the user when closing, "the application is trying to close the window..."
   //return ' | <a href="javascript:window.open(\'http://www.associationvoice.com/Prospects/apply.asp\'); void(0)">Apply</a>';
   return ' | <a href="javascript:AV.prospects.appWindow.showAppWin(\'' + actionEl + '\');">Apply</a>';
  }  
  else
    return '';
}


AV.Rental.Contact = new function(){
  
  function SendContactEmail(property_id, animLink, property_address)
  {    
    var frmContactEmailInfo = new Ext.form.FormPanel({
      labelWidth:80,
      url:'/rental/email_property.asp?action=contactRequest',       
      bodyStyle: 'padding:10px;background-color:#FFFFFF;',
      border: false,
      bodyBorder: false,
      defaultType:'textfield',      
      defaults: {
        labelSeparator: '',
        msgTarget: 'under',
        labelStyle: 'font-family:Arial,Helvetica; font-size: 11px; font-weight:bold;'              
      },

      items:[{
              id: 'txtContactFirstName',
              fieldLabel:'First Name',             
              name:'txtContactFirstName',
              allowBlank:false,
              blankText: 'This field is required.',
              width: 200
            },{
              id: 'txtContactLastName',
              fieldLabel:'Last Name',             
              name:'txtContactLastName',
              allowBlank:false,
              blankText: 'This field is required.',
              width: 200
            },{
              id: 'txtContactEmail',
              fieldLabel:'Email',              
              name:'txtContactEmail',
              allowBlank:false,
              blankText: 'This field is required.',
              width: 200,
              validator: AV.Rental.ValidateEmail.validateSingleEmail,
              validationEvent:'blur',
              invalidText: 'Please enter a valid email address.'
            },{
              id: 'txtContactTo',
              fieldLabel:'To',              
              name:'txtContactTo',                                 
              width: 200,
              value: contact_default_to,    //global var set in xsl
              disabled: true
            },                     
            new Ext.form.Hidden({     
              id: 'txtContactEmailTo',         
              name:'txtContactEmailTo',
              value: contact_email        //global var set in xsl
            }),                    
            {
              id: 'txtContactSubject',
              fieldLabel:'Subject',              
              name:'txtContactSubject',
              allowBlank:false,    
              blankText: 'This field is required.',          
              width: 200,
              value: property_address
            },                                      
            new Ext.form.TextArea({     
              id: 'txtContactDetails',     
              fieldLabel:'Details',     
              name:'txtContactDetails',
              width: 250,
              height: 100,
              hideLabel: false,
              value: contact_default_message  + '  ' + property_address    //global var set in xsl        
            }),     
            new Ext.form.ComboBox({
              id: 'comboContactRespond',
              fieldLabel:'Please Respond',              
              name:'comboContactRespond',                      
              width: 200,
              editable: false,          
              mode: 'local',
              store: [['0','Immediately'],['1', 'Soon'],['2','At Your Convenience']],             
              triggerAction: 'all',   //for some reason this is required.  otherwise the combo does not work properly
              value: '0',
              forceSelection: true              
            }),      
            new Ext.form.ComboBox({
              id: 'comboContactContactBy',
              fieldLabel:'Contact By',              
              name:'comboContactContactBy',                      
              width: 100,
              editable: false,
              mode: 'local',
              store: [['0','Email'],['1', 'Phone'],['2','Fax']],
              triggerAction: 'all',   //for some reason this is required.  otherwise the combo does not work properly
              value: '0',
              forceSelection: true              
            }),   
             {
              id: 'txtContactNumber',           
              fieldLabel: '',            
              name:'txtContactNumber',                        
              width: 200,
              hideMode: 'visibility',
              emptyText: 'Enter Phone/Fax #'
            },     
            new Ext.form.ComboBox({
              id: 'comboContactBestTime',
              fieldLabel:'Contact Time',              
              name:'comboContactBestTime',                      
              width: 100,
              editable: false,
              mode: 'local',
              store: [['0','Evening'],['1', 'Day'],['2','Weekend']],
              triggerAction: 'all',   //for some reason this is required.  otherwise the combo does not work properly
              value: '0',
              forceSelection: true              
            })
         ]                           
    });                         
    
    var contactInstructions = '<div style="padding: 10px;"><div style="font-family:Arial,Helvetica; font-size: 20px; font-weight:bold;">Contact Request</div><div style="font-family:Arial,Helvetica; font-size: 10px; font-weight:normal;"><table><tr>';        
    contactInstructions += '<td>Enter your information below.  Also, please include your contact preferences. </td>';
    contactInstructions += '</tr></table></div></div>';
    
    var contactInstructionPanel = new Ext.Panel({        
        //frame:true,   
        border: false,
        bodyBorder: false,                   
        header: false,
        html: contactInstructions,
        bodyStyle: 'background-color:#FFFFFF;'
    });
      
    var winContactEmailInfo = new Ext.Window({
        closable:true,
        resizable: false,
        width:390,        
        plain:true,
        modal:true,       
        buttons: [{
                  id: "btn_send_contact_email",
                  text: "Send",
                  handler: function(){
                  
                    if(Ext.getCmp('txtContactFirstName').isValid() && Ext.getCmp('txtContactLastName').isValid() && Ext.getCmp('txtContactSubject').isValid() && Ext.getCmp('txtContactEmail').isValid()  && Ext.getCmp('txtContactDetails').isValid())
                    {                                          
                      frmContactEmailInfo.getForm().submit({                         
                        waitTitle:'Please Wait', 
                        waitMsg:'Sending data...',
 
                          
			                  //EXAMPLE { success: false, errors: { reason: 'The email can not be sent.  Your email address is invalid.' }} 
                        success:function(form, action){ 
                        
                          obj = Ext.util.JSON.decode(action.response.responseText); 

			                    winContactEmailInfo.close();
                        },
 
                        failure:function(form, action){                         
                          
                          if(action.failureType == 'server'){ 
                              obj = Ext.util.JSON.decode(action.response.responseText);                               
                              Ext.Msg.alert('Email Failed!', obj.errors.reason); 
                          }
                          else{ Ext.Msg.alert('Warning!', 'Email server is unreachable : ' + action.response.responseText + "abcd"); } 
                        } 
                      }); 
                      
                      
                    }                                    
                  }
                },
                {
                  id: "btn_cancel_contact_email",
                  text: "Cancel",
                  handler: function(){
                    
                    if (document.getElementById('headerHide')) document.getElementById('headerHide').style.visibility = "visible";
                    
                    winContactEmailInfo.close();                  
                  }
                }
               ],
        items: [contactInstructionPanel, frmContactEmailInfo]  
    });        
    
    //This allows the ext dialog to be displayed "above" a flash header
    if (document.getElementById('headerHide')) document.getElementById('headerHide').style.visibility = "hidden";
    //this is here because function "HM_f_PageClick" in HMScriptDOM.js gets called on every page on mouse down by default and pulls flash headers in front of the dialog
    var bodyEl = Ext.get(window.document);
    bodyEl.addListener('mousedown', function (){ if (document.getElementById('headerHide')) { document.getElementById('headerHide').style.visibility = "hidden"; } });
    
    winContactEmailInfo.show(animLink);
  
    //Ext.getCmp('txtContactNumber').initialConfig.hideLabel=true;
    Ext.getCmp('txtContactNumber').hide();
    Ext.getCmp('comboContactContactBy').on('select', function(combo, record, index){
                                                      //if phone or fax is selected
                                                      if(record.get('value') != 0) { Ext.getCmp('txtContactNumber').show(); }   
                                                      else 
                                                      { 
                                                        Ext.getCmp('txtContactNumber').hide(); 
                                                        Ext.getCmp('txtContactNumber').setValue('');
                                                        
                                                      }

                                                    }
    );
  }
  
  return {
  
    sendContactEmail : function(property_id, animLink, property_address){     
      SendContactEmail(property_id, animLink, property_address);
    },
    getContactEmailLink : function(property_id, property_address){
      if( assnId != '11297' ) 
      {
        var temp_property_id = "'" + property_id + "'";
        var anchor_id = "'" + "a_contact_email_" + property_id + "'";
        var temp_address = "'" + property_address + "'";
        return '<a id=' + anchor_id + ' href="javascript:AV.Rental.Contact.sendContactEmail(' + temp_property_id + ', ' + anchor_id + ', ' + temp_address + ')">' + contact_text + '</a>';
      }
      else { return '';}
    },
    getContactEmailLinkAsPropertyMenuItem : function(property_id, property_address){
      if( assnId == '11297' ) 
      {     
        var temp_property_id = "'" + property_id + "'";
        var anchor_id = "'" + "a_contact_email_" + property_id + "'";
        var temp_address = "'" + property_address + "'";
        return ' | <a id=' + anchor_id + ' href="javascript:AV.Rental.Contact.sendContactEmail(' + temp_property_id + ', ' + anchor_id + ', ' + temp_address + ')">' + contact_text + '</a>';
      }
      else { return '';}
    }     
  }
   
}


var objFeatures = new function() {

  var featureList = {

    features: [{
      code: 'Rent',
      desc: 'Rent',
      printList: true,      //display in the print page feature list
      displayList: false    //display in-page property listing feature list
    },{
      code: 'Beds',
      desc: 'Bedrooms',
      printList: true,
      displayList: false
    },{
      code: 'Baths',
      desc: 'Bathrooms',
      printList: true,
      displayList: false
    },{
      code: 'SquareFeet',
      desc: 'Square Feet',
      printList: true,
      displayList: false
    },{
      code: 'UnitType',
      desc: 'Unit Type',
      printList: true,
      displayList: false
    },{
      code: 'YearBuilt',
      desc: 'Year Built',
      printList: true,
      displayList: false
    },{
      code: 'SecurityDeposit',
      desc: 'Deposit',
      printList: true,
      displayList: false
    },{
      code: 'CentralAir',
      desc: 'A/C',
      printList: true,
      displayList: true
    },{
      code: 'ACWindowUnit',
      desc: 'A/C Unit',
      printList: true,
      displayList: true
    },{
      code: 'Attic',
      desc: 'Attic',
      printList: true,
      displayList: true
    },{
      code: 'Basmnt',
      desc: 'Basement',
      printList: true,
      displayList: true
    },{
      code: 'BkArea',
      desc: 'Breakfast Area',
      printList: true,
      displayList: true
    },{
      code: 'BonRm',
      desc: 'Bonus Room',
      printList: true,
      displayList: true
    },{
      code: 'Cats',
      desc: 'Cats Only',
      printList: true,
      displayList: true
    },{
      code: 'ComPg',
      desc: 'Playground',
      printList: true,
      displayList: true
    },{
      code: 'ComPl',
      desc: 'Pool',
      printList: true,
      displayList: true
    },{
      code: 'ComTC',
      desc: 'Tennis COurt',
      printList: true,
      displayList: true
    },{
      code: 'CrptFl',
      desc: 'Carpeted Floors',
      printList: true,
      displayList: true
    },{
      code: 'DW',
      desc: 'Dishwasher',
      printList: true,
      displayList: true
    },{
      code: 'Deck',
      desc: 'Deck',
      printList: true,
      displayList: true
    },{
      code: 'DinRm',
      desc: 'Dining Room',
      printList: true,
      displayList: true
    },{
      code: 'Dis',
      desc: 'Disposal',
      printList: true,
      displayList: true
    },{
      code: 'Dogs',
      desc: 'Dogs Only',
      printList: true,
      displayList: true
    },{
      code: 'ElecWa',
      desc: 'Electric Water Heater',
      printList: true,
      displayList: true
    },{
      code: 'ElHt',
      desc: 'Electric Heat',
      printList: true,
      displayList: true
    },{
      code: 'FmRm',
      desc: 'Family Room',
      printList: true,
      displayList: true
    },{
      code: 'Fence',
      desc: 'Fenced Yard',
      printList: true,
      displayList: true
    },{
      code: 'FirePl',
      desc: 'Fire Place',
      printList: true,
      displayList: true
    },{
      code: 'Fit',
      desc: 'Fitness Center',
      printList: true,
      displayList: true
    },{
      code: 'Foyer',
      desc: 'Foyer',
      printList: true,
      displayList: true
    },{
      code: 'Gar2',
      desc: '2 Car Garage',
      printList: true,
      displayList: true
    },{
      code: 'Garage',
      desc: '1 Car Garage',
      printList: true,
      displayList: true
    },{
      code: 'Gas',
      desc: 'Gas Heat',
      printList: true,
      displayList: true
    },{
      code: 'GasWH',
      desc: 'Gas Water Heater',
      printList: true,
      displayList: true
    },{
      code: 'HOA',
      desc: 'HOA Governed',
      printList: true,
      displayList: true
    },{
      code: 'HWflr',
      desc: 'Hardwood Floors',
      printList: true,
      displayList: true
    },{
      code: 'Kitchn',
      desc: 'Kitchen',
      printList: true,
      displayList: true
    },{
      code: 'Lake',
      desc: 'Lake Front',
      printList: true,
      displayList: true
    },{
      code: 'Laundy',
      desc: 'Laundry Hook-ups',
      printList: true,
      displayList: true
    },{
      code: 'LaundryRm',
      desc: 'Laundry Room',
      printList: true,
      displayList: true
    },{
      code: 'LawnCr',
      desc: 'Lawncare Included',
      printList: true,
      displayList: true
    },{
      code: 'LinFl',
      desc: 'Linoleum Floors',
      printList: true,
      displayList: true
    },{
      code: 'LivRm',
      desc: 'Living Room',
      printList: true,
      displayList: true
    },{
      code: 'LTOwn',
      desc: 'Lease To Own',
      printList: true,
      displayList: true
    },{
      code: 'Metro',
      desc: 'Metro',
      printList: true,
      displayList: true
    },{
      code: 'Micro',
      desc: 'Microwave',
      printList: true,
      displayList: true
    },{
      code: 'PaidWS',
      desc: 'Paid Water & Sewer',
      printList: true,
      displayList: true
    },{
      code: 'Parking',
      desc: 'Parking',
      printList: true,
      displayList: true
    },{
      code: 'Patio',
      desc: 'Patio',
      printList: true,
      displayList: true
    },{
      code: 'PetsNg',
      desc: 'Pets-Negotiable',
      printList: true,
      displayList: true
    },{
      code: 'PetsNo',
      desc: 'Pets Not Allowed',
      printList: true,
      displayList: true
    },{
      code: 'PetsYs',
      desc: 'Pets Allowed',
      printList: true,
      displayList: true
    },{
      code: 'Pond',
      desc: 'Pond',
      printList: true,
      displayList: true
    },{
      code: 'Pool',
      desc: 'Pool Included',
      printList: true,
      displayList: true
    },{
      code: 'Porch',
      desc: 'Porch',
      printList: true,
      displayList: true
    },{
      code: 'Range',
      desc: 'Range/Stove',
      printList: true,
      displayList: true
    },{
      code: 'RbCt',
      desc: 'Racquet Ball Ct',
      printList: true,
      displayList: true
    },{
      code: 'RecFld',
      desc: 'Rec Field',
      printList: true,
      displayList: true
    },{
      code: 'Refrig',
      desc: 'Refrig Included',
      printList: true,
      displayList: true
    },{
      code: 'Sec8',
      desc: 'Section 8',
      printList: true,
      displayList: true
    },{
      code: 'Secure',
      desc: 'Security System',
      printList: true,
      displayList: true
    },{
      code: 'Shop',
      desc: 'Workshop',
      printList: true,
      displayList: true
    },{
      code: 'Storag',
      desc: 'Storage Shed',
      printList: true,
      displayList: true
    },{
      code: 'StorAr',
      desc: 'Storage Area',
      printList: true,
      displayList: true
    },{
      code: 'SwgSet',
      desc: 'Swing Set',
      printList: true,
      displayList: true
    },{
      code: 'TC',
      desc: 'Tennis Court',
      printList: true,
      displayList: true
    },{
      code: 'TileFl',
      desc: 'Tiled Floor',
      printList: true,
      displayList: true
    },{
      code: 'WD',
      desc: 'Washer-Dryer',
      printList: true,
      displayList: true
    }]
  };
  
  var count = 0;
    
  return{
    getFeatures : function(){     
      count = 0; //reset count everytime
      return featureList.features;
    },
    
    getCount : function(){
      return count;
    },
    
    incrementCount : function(){
      return ++count;
    }
  
  }  
}


AV.Print = new function(){

  function getSingleFeatureTable(name, value)
  {   	
	  var table = '<td nowrap="true" style="padding: 0px 8px 0px 0px;"><span style="font-size:12px;"><b>' + name + '</b></span></td>';
			  table += '<td><span style="font-size:12px;">' + value + '</span></td>';
	  return table;
  }

  function GetFeaturesForPrint(record)
  {
    var featureTable = '<table width="660"><tr><td width="10%"><td width="15%"></td><td width="15%"></td><td width="15%"></td><td width="15%"></td><td width="15%"></td><td width="15%"></td></tr><tr><td></td>';    
    
    var features = objFeatures.getFeatures();
    
    for(var i = 0; i<features.length; i++)
    {          
      var value = record.get(features[i].code);
      if(value != "" && value != "0" && value != "$0" && features[i].printList) 
      {         
        featureTable += getSingleFeatureTable(features[i].desc, value == 'Yes' ? '' : value) + (objFeatures.incrementCount() % 3 === 0 ? "</tr><tr><td></td>" : "");
      }
    }  
   
    featureTable += '</tr></table>';
    
    return featureTable;    
  }

  function LaunchPrint(printHtml)
  {               
    var newWin = window.open('/rental/print_property.asp', 'printWin', 'height=590,width=780,menubar=yes,resizable=yes,scrollbars=yes');
    newWin.document.write(printHtml);
    newWin.document.close();    
  }
  
  function GetPrint(property_id, forEmail)
  {
    var headerLogo = '';
    
    //image_logo and news_header_image are vars set in the xsl
    //If a news header image exists, use it for the brochure header...then the image_logo, and finally scrape the header if necessary
    if(news_header_image != '') { headerLogo = news_header_image; }
    else if(logo_image != '') { headerLogo = logo_image; }
    else {headerLogo = Ext.select('div.clsLogoImage img').elements[0].src; }
    
    var strDomain = '';
    var strMessage = '';
    var strFooter = '';
    
    //use full absolute links instead of relative for emails.  Also add message and footer
    if(forEmail == true) 
    { 
      strDomain = 'http://' + window.location.hostname;
      
      strMessage = '<div style="width:760px;text-align:left;padding:10px;" >' + Ext.getCmp('txtMessage').getValue() + '</div><br/>';      
      
      strFooter = '<br/><br/><p style="line-height:normal"><span style="font-size:8.0pt;color:#333333">';
      strFooter += 'This message has been sent to ';
      strFooter += '<a style="color: blue; text-decoration: underline; text-underline: single" href="mailto:' + Ext.getCmp('txtTo').getValue() + '">' + Ext.getCmp('txtTo').getValue() + '</a></span></p>';      
      
      strFooter += '<p style="line-height:normal"><span style="font-size:8.0pt;color:#333333">';
      strFooter += 'To view our privacy policy, click ';
      strFooter += '<a style="color: blue; text-decoration: underline; text-underline: single" href="http://www.associationvoice.com/legal/privacy.htm">';
      strFooter += '<span style="color:#333333">Privacy Policy</span></a>.</span></p>';
      
      strFooter += '<p style="line-height:normal"><span style="font-size:8.0pt;color:#333333">';
      strFooter += 'This message has been sent as a service of ';
      strFooter += '<a style="color: blue; text-decoration: underline; text-underline: single" href="http://www.AssociationVoice.com/">';
      strFooter += '<span style="color:#333333">AssociationVoice</span></a>';
      strFooter += ', provider of smart Websites for Associations and Management, ';
      
      var year = new Date().getFullYear();
      
      strFooter += '400 S. Colorado Blvd. Ste 790, Denver, CO  80246. AssociationVoice © ' + year + '. All rights reserved.</span></p>';      
    }         
      
    var store = AV.results_store.getStore();    
    var record = store.getById(property_id);    
    var features = GetFeaturesForPrint(record);
   
    var t = new Ext.XTemplate(
    
      '<html>',
      '<head>',
      '<title>Property Print: {Address} {City}, {State} {Zip}</title>',
       
      '</head>',
      '<body onload="window.print();">',
        strMessage,
        '<div style="width:760px;" align="center">',
          '<div id="headerLogo">',
            '<div align="center">',
              '<a href="rental_search.asp">',
				        '<img src="'+ strDomain + headerLogo + '" border="0" />',
			        '</a>',
			      '</div>',
          '</div>',
                  
          '<div align="center" style="margin: 10px 50px 0px 50px;">',
	          '<div style="text-align:left;">',
		          '<div id="PropertyDetails">',
			          '<h4>Property Details</h4>',
			          '<div id="PropertyImage" align="center">',
				          '<div>',
					          '<img src="' + strDomain + '{DefaultImage}" /> <br />',
				          '</div>',
			          '</div>',
			          '<div id="PropertyDescription" style="border-bottom: solid;">',
				          '<h3>{Address} {City}, {State} {Zip} <br />',
				            '<span style="font-size:12px; color:#000000;">',
				              '{[values.Rent != "$0" && values.Rent != "" ? values.Rent + " Rent / " : ""]}',
				              '{[values.Beds != "0" && values.Beds != "" ? values.Beds + " Beds / " : ""]}',
				              '{[values.Baths != "0" && values.Baths != "" ? values.Baths + " Baths / " : ""]}',
				              '{[values.SquareFeet != "0"  && values.SquareFeet != ""? values.SquareFeet + " Total SqFt / " : ""]}',
				              '{[values.UnitType != "" ? values.UnitType + " / " : ""]}',
				              '{[values.YearBuilt != "0" && values.YearBuilt != "" ? "Built in " + values.YearBuilt + " / " : ""]}',
				              '{[values.SecurityDeposit != "$0"  && values.SecurityDeposit != ""? values.SecurityDeposit + " Deposit / " : ""]}',
				              
				              '<br />',
				            '</span>',
				          '</h3>',
				          '<p style="font-size:14px; color:#000000;">',
				          '{[values.Description.replace(/\n/g, "<br/>")]}',
				          '</p>',
			          '</div>',
			          '<br/>',
			          '<div id="PropertyFeatures" >',
  					     
				          features,

			          '</div>',				     
		          '</div>',
	          '</div>',
          '</div>',
                     
        '</div>',
        strFooter,
      '</body>',
      '</html>'        

    );
    
    return t.apply(record.data);
  }
 
 
  function SendEmail(property_id, animLink) {
  
		var frmEmailInfo = new Ext.form.FormPanel({
			labelWidth:80,
			url:'/rental/email_property.asp?action=emailProperty', 
			//frame:true, 
			bodyStyle: 'padding:10px;background-color:#FFFFFF;',
			border: false,
			bodyBorder: false,
			defaultType:'textfield',      
			defaults: {
				labelSeparator: '',
				msgTarget: 'under',
				labelStyle: 'font-family:Arial,Helvetica; font-size: 11px; font-weight:bold;'
			},
			//monitorValid:true,
			items:[{
				id: 'txtTo',
				fieldLabel:'To',             
				name:'txtTo',
				allowBlank:false,
				blankText: 'This field is required.',
				width: 200,
				validator: AV.Rental.ValidateEmail.validateEmail,
				validationEvent:'blur',
				invalidText: 'Please enter a valid email address.'
			},{
				id: 'txtBcc',
				fieldLabel:'Bcc',              
				name:'txtBcc',
				width: 200,
				validationEvent:false
			},{
				id: 'txtSubject',
				fieldLabel:'Subject',              
				name:'txtSubject',
				allowBlank:false,    
				blankText: 'This field is required.',          
				width: 200
			},{
				id: 'txtYourEmail',
				fieldLabel:'Your Email',              
				name:'txtYourEmail',
				allowBlank:false,
				blankText: 'This field is required.',
				width: 200,
				validator: AV.Rental.ValidateEmail.validateSingleEmail,
				validationEvent:'blur',
				invalidText: 'Please enter a valid email address.'
			},
			new Ext.form.Checkbox({
				id: 'chkCopyMe',
				boxLabel:'Copy Me',             
				name:'chkCopyMe',
				x: 80 
			}),
			new Ext.form.Label({
				text: 'Message',
				style: 'font-family:Arial,Helvetica; font-size: 11px; font-weight:bold;'
			}),         
			new Ext.form.TextArea({     
				id: 'txtMessage',         
				name:'txtMessage',
				width: 350,
				//maxLength: 500,
				//maxlengthText: 'Please limit your message to 500 characters.',
				hideLabel: true
				//msgTarget: 'under'
			}),          
			new Ext.form.Hidden({     
				id: 'txtHtml',         
				name:'txtHtml'        
			})
		]                           
	});                 
        
	var instructions = '<div style="padding: 10px;"><div style="font-family:Arial,Helvetica; font-size: 20px; font-weight:bold;">Email a Friend</div><div style="font-family:Arial,Helvetica; font-size: 10px; font-weight:normal;"><table><tr>';        
	instructions += '<td>Enter recipient email address(es) and subject below.  Separate multiple addresses with commas(,).</td>';
	instructions += '</tr></table></div></div>';
    
	var instructionPanel = new Ext.Panel({        
		//frame:true,   
		border: false,
		bodyBorder: false,                   
		header: false,
		html: instructions,
		bodyStyle: 'background-color:#FFFFFF;'
	});
    
	var winEmailInfo = new Ext.Window({
		//title: 'Email to a Friend',
		closable:true,
		resizable: false,
		width:390,        
		plain:true,
		modal:true,       
		buttons: [{
			id: "btn_send_email",
			text: "Send Email",
			handler: function(){
				if(Ext.getCmp('txtTo').isValid() && Ext.getCmp('txtSubject').isValid() && Ext.getCmp('txtYourEmail').isValid()  && Ext.getCmp('txtMessage').isValid()) {
					var bcc = Ext.getCmp("txtBcc");
					if (bcc.getValue() !== "" && !Ext.form.VTypes.email(bcc.getValue())) {
						return;
					}
					Ext.getCmp('txtHtml').setValue(GetPrint(property_id, true));
                    
					frmEmailInfo.getForm().submit({                         
						waitTitle:'Please Wait', 
						waitMsg:'Sending data...',
						success:function(form, action){ 
							obj = Ext.util.JSON.decode(action.response.responseText);
							if(obj.sameDomainMsg.msg != "") {
								Ext.Msg.alert('Status', 'Your email was sent successfully.  However, ' + obj.sameDomainMsg.msg, function(btn, text){
									if (btn == 'ok'){}
								});
							}                                                                           
							winEmailInfo.close();
						},
						failure:function(form, action){
							if(action.failureType == 'server'){ 
								obj = Ext.util.JSON.decode(action.response.responseText);                               
								Ext.Msg.alert('Email Failed!', obj.errors.reason); 
							} else { 
								Ext.Msg.alert('Warning!', 'Email server is unreachable'); 
							} 
						} 
					}); 
				}
			}
		},
		{
			id: "btn_cancel_email",
			text: "Cancel",
			handler: function(){
				if (document.getElementById('headerHide')) {
					document.getElementById('headerHide').style.visibility = "visible";
				}
				winEmailInfo.close();
				//winEmailInfo.hide(Ext.get(animLink), function(){ winEmailInfo.close(); });                    
			}
		}],
		items: [instructionPanel, frmEmailInfo]  
});        
    
    //This allows the ext dialog to be displayed "above" a flash header
    if (document.getElementById('headerHide')) document.getElementById('headerHide').style.visibility = "hidden";
    //this is here because function "HM_f_PageClick" in HMScriptDOM.js gets called on every page on mouse down by default and pulls flash headers in front of the dialog
    var bodyEl = Ext.get(window.document);
    bodyEl.addListener('mousedown', function (){ if (document.getElementById('headerHide')) { document.getElementById('headerHide').style.visibility = "hidden"; } });

    
    winEmailInfo.show(Ext.get(animLink));
  }

  return {
  
    launchPrint : function(property_id){
      LaunchPrint(GetPrint(property_id, false));
    },
    
    getPrint : function(property_id){
      return GetPrint(property_id, false);     
    },
    getPrintLink : function(property_id){
      property_id = "'" + property_id + "'";
      return ' | <a href="javascript:AV.Print.launchPrint(' + property_id + ')">Brochure</a>';
    },
    sendEmail : function(property_id, animLink){     
      SendEmail(property_id, animLink);
    },
    getEmailLink : function(property_id){
      var temp_property_id = "'" + property_id + "'";
      var anchor_id = "'" + "a_email_" + property_id + "'";
      return ' | <a id=' + anchor_id + ' href="javascript:AV.Print.sendEmail(' + temp_property_id + ', ' + anchor_id + ')">Email to a Friend</a>';
    }
  }
}

AV.Rental.ValidateEmail = new function() {
 
  function ValidateEmail(value)
  {
    //split multiple addresses by and validate
    var addresses = value.replace(' ', '').split(',');
    for(var i = 0; i < addresses.length; i++)
    {
      if(!isEmailAddr(addresses[i].replace(' ', ''))) { return false;}
    }
    return true;
  }
  
  function ValidateSingleEmail(value)
  {   
    if(!isEmailAddr(value.replace(' ', ''))) { return false;}
    return true;
  }
  
  return {
    validateEmail : function(value) { return ValidateEmail(value); },
    validateSingleEmail : function(value) { return ValidateSingleEmail(value); }
  }
}


AV.AdditionalFeatures = new function(){

  function writeAdditionalFeature(text, value)
  {    
    return '<td class="clsInstructions" style="padding: 0px 20px 0px 0px;">&#8226;&nbsp;' + text + '</td>';    
  }

  return {
    
    getAdditionalFeatures : function(values){
      
      var features = objFeatures.getFeatures();
      var count = 0;
      var strFeatures;
      
      for(var i = 0; i<features.length; i++)
      {            
        if(count == 0) { strFeatures = '<tr>'; }
        
        var value = eval('values.' + features[i].code);
        
        if(value && value != '' && features[i].displayList)
        {
          strFeatures +=  writeAdditionalFeature(features[i].desc, '') + (++count % 3 === 0 ? "</tr><tr>" : "");      
        }    
      }  
          
      if(count > 0) { strFeatures += '</tr>'; }
     
      return strFeatures;
    }
  }
}  

AV.tpl_unit = new function(){
  
  var template;
    
  function ToggleDetails(div_id)
  {    
    var detailDiv = Ext.get(div_id);
    if(detailDiv)
    {    
      if(detailDiv.dom.style.display == "") 
      {      
        detailDiv.slideOut('t', {
            easing: 'easeOut',
            duration: .5,
            callback: function(){
              detailDiv.dom.style.display = "none";
              var view_details_anchor = Ext.get("a_" + div_id)
              view_details_anchor.dom.innerHTML = "View Details";                        
              
              view_details_anchor.frame("", 1, {duration: .5});
            }
        });     
      } 
      else if(detailDiv.dom.style.display == "none") 
      {      
        detailDiv.slideIn('t', {
            easing: 'easeOut',
            duration: .5,
            callback: function(){
                       
              var view_details_anchor = Ext.get("a_" + div_id)
              view_details_anchor.dom.innerHTML = "Hide Details";
              view_details_anchor.frame("", 1, {duration: .5});
            }
        });     
      } 
    }         
  }
  
  function ShowArea(area)
  {
    //Display area for henderson
    if(assnId == '11297')
      { return '<tr><td class="clsInstructions" nowrap="" style="padding: 0px 10px 0px 0px;"><b>Area</b></td><td class="clsInstructions">' + area + '</td></tr>'; }
    else { return ''; }
  }

  function SetToolTipCssClass(src)
  { 
    //if the "no image available" is the default image, don't enable the tool tip
    if(src == 'images/house.gif') { return ''; }
    else { return 'tooltipAnchor'; }
  }
  
  function GetOrigDisplayImage(property_id, thumbs, default_image)
  {
    if(thumbs != "")
    {
      if(thumbs.lastIndexOf(",") == thumbs.length -1){ thumbs = thumbs.substr(0, thumbs.length -1); }
        
      var arrThumbs = thumbs.split(",");
      var display_image;
          
      //if there is more than one image, make sure that the image to be displayed is not the same as the default image
      //this avoids having the same image displayed twice when the user first expands the details div
      if(arrThumbs.length > 1)
      {
        var i = 0;
        for(i = 0; i < arrThumbs.length; i++)
        {
          //get the display image, based on thumb path
          display_image = getSrcFromThumbSrc(arrThumbs[i]);          
          
          //return the first image that is not the default image
          if(display_image != default_image)
            { return '<img id="img_display_' + property_id + '" src="' + display_image + '" class="tooltipAnchor" width="240" height="160"/>'; }
        }
      }   
      else
         { return '<img id="img_display_' + property_id + '" src="' + getSrcFromThumbSrc(arrThumbs[0]) + '" class="tooltipAnchor" width="240" height="160"/>'; }
    }
    else
      return '<div style="width:240; height:160;" ><div align="center" valign="middle">No Image</div></div>';        
  }
  
  function templateInit()
  {     
    template = new Ext.XTemplate(
        '<tpl for=".">',
            
            '<div id="div_property_summary_{property_id}">',
              '<table border="0">',
	              '<tr>',
		              '<td class="default_image" valign="top" rowspan="2">',
		                '<div class="border-default" id="div_default_image">',		                
		                  '<a href="javascript:AV.tpl_unit.toggleDetails(\'div_{property_id}\');" title="Click to View Details">',
		                    '<img border="0" class="{[AV.tpl_unit.setToolTipCssClass(values.DefaultImage)]}" src="{DefaultImage}"/>',
		                  '</a>',
		                '</div>',
		              '</td>',
	              '</tr>',	  
	              '<tr>',	             
	                '<td valign="top" style="padding-left:10px;padding-right:2px;">',
	                  '<a title="Map It!" href="javascript:AV.Rental.Map.showRentalMap(\'{Address}\', \'{City}\', \'{State}\', \'{Zip}\', \'{Rent}\', \'{Status}\', \'{Beds}\', \'{Baths}\', \'{SquareFeet}\', \'{UnitType}\', \'{YearBuilt}\', \'{SecurityDesposit}\')" map="{Address}">',
	                    '<img style="margin-top:3px;" width="15" height="15" src="images/map.png"/>',
	                  '</a>',
	                '</td>',
		              '<td class="" valign="top" style="width: 50%;">',
		              '<div class="clsInstructions">',
			              '{Address} <br />',
			              '{City}, {State} {Zip}',
			            '</div>',				            			                 		            			              			            			              
		              '</td>',
		              '<td class="" valign="top" style="white-space: nowrap; width: 25%;">',
		                '<table>',
			                '<tr>',
				                '<td>',
				                  '<div class="clsInstructions" style="white-space: nowrap;">',
					                  '<b>Rent:</b> {Rent} <br />',
					                  '<b>Bedrooms:</b> {Beds} <br />',
					                  '<b>Bathrooms:</b> {Baths} <br />',
				                  '</div>',				                  				                  
				                '</td>',
			                '</tr>',
		                '</table>',
		              '</td>',
	              '</tr>',	              
	              '<tr>',	                
		              '<td valign="bottom" align="right" colspan="4">',
		              '<a id="a_div_{property_id}" href="javascript:AV.tpl_unit.toggleDetails(\'div_{property_id}\');">View Details</a>',
		              		              
		              '{[getDemoBrochureLink()]}',
		              '{[getDemoApplicationLink("a_div_" + values.property_id)]}',
		              '{[AV.Print.getPrintLink(values.property_id)]}',
		              '{[AV.Print.getEmailLink(values.property_id)]}',
		              '{[AV.Rental.Contact.getContactEmailLinkAsPropertyMenuItem(values.property_id, values.Address + " " + values.City + ", " + values.State + "  " + values.Zip)]}',
		              
		              
		              '</td>',
	              '</tr>',
              '</table>',
            '</div>',                    
            '<div id="div_{property_id}" align="center" style="display:none;">',    
              '<table border="0">',
                '<tr valign="top">',                  
                  '<td>',
                    '<div class="border-display" id="div_img_display_{property_id}" >',         

                        '{[AV.tpl_unit.getOrigDisplayImage(values.property_id, values.Thumbs, values.DefaultImage)]}',

		                '</div>',
		                 '<div id="div_thumb_rotator_{property_id}">',
		                    '<table border="0"><tr>{[AV.tpl_unit.splitThumbs(values.Thumbs, "img_display_" + values.property_id, values.property_id)]}</tr></table>',
		                    '<input id="thumbs_{property_id}" type="hidden" value="{Thumbs}"></input>',
		                 '</div>',
		                 '<div align="center">{[AV.tpl_unit.getUploadButton(values.property_id, values.Unit, values.Building, values.FloorPlan)]}</div>',
                  '</td>',
                  '<td width="50%" align="right" valign="top" rowspan="2">',
                    '<div class="clsInstructions" style="white-space: nowrap;">',
                      '<table border="0" width="95%">',
                      
                        '<tr>',
                          '<td class="clsInstructions" nowrap="" width="40%" style="padding: 0px 10px 0px 0px;"><b>Rent</b></td><td class="clsInstructions">{Rent}</td>',
                        '</tr>',
                        '<tr>',
                          '<td class="clsInstructions" nowrap="" style="padding: 0px 10px 0px 0px;"><b>Bed</b></td><td class="clsInstructions">{Beds}</td>',
                        '</tr>',
                        '<tr>',
                          '<td class="clsInstructions" nowrap="" style="padding: 0px 10px 0px 0px;"><b>Bath</b></td><td class="clsInstructions">{Baths}</td>',
                        '</tr>',
                        '{[AV.tpl_unit.showArea(values.Area)]}',
                        '<tr>',
                          '<td class="clsInstructions" nowrap="" style="padding: 0px 10px 0px 0px;"><b>Sq Feet</b></td><td class="clsInstructions">{SquareFeet}</td>',
                        '</tr>',
                        '<tr>',
                          '<td class="clsInstructions" nowrap="" style="padding: 0px 10px 0px 0px;"><b>Type</b></td><td class="clsInstructions">{UnitType}</td>',
                        '</tr>',
                        '<tr>',
                          '<td class="clsInstructions" nowrap="" style="padding: 0px 10px 0px 0px;"><b>Year</b></td><td class="clsInstructions">{YearBuilt}</td>',
                        '</tr>',
                        '<tr>',
                          '<td class="clsInstructions" nowrap="" style="padding: 0px 10px 0px 0px;"><b>Deposit</b></td><td class="clsInstructions" nowrap="">{SecurityDeposit}</td>',
                        '</tr>',                                                                                      
                        
                      '</table>',                          
	
		                '</div>',
                  '</td>',                  
                '</tr>',
                '<tr>',
	                '<td colspan="4" class="clsInstructions" style="padding: 10px 15px 0px 15px;">',
	                  '<div id="div_description_{values.property_id}" style="line-height: 14px;">',
	                    '{[values.Description.replace(/\n/g, "<br/>")]}',                  
	                  '</div>',
	                '</td>',
	              '</tr>',
	              '<tr>',
	                '<td colspan="2" align="center" class="clsInstructions" style="padding-top: 5px;">',
                    '{[AV.Rental.Contact.getContactEmailLink(values.property_id, values.Address + " " + values.City + ", " + values.State + "  " + values.Zip)]}',
			            '</td>',
	              '</tr>',
                '<tr>',
                  '<td colspan="2" align="center" style="padding: 10px 10px 0px 30px; border-top: solid;">',
                    '<table border="0">',
                      '{[AV.AdditionalFeatures.getAdditionalFeatures(values)]}',
                    '</table>',
                  '</td>',
                '</tr>',
              '</table>',              
            '</div>',
            '<hr/>',
               
        '</tpl>',
        '<div class="x-clear"></div>'               
        
      );            
  }
  
  function getSrcFromThumbSrc(thumb_src) { return thumb_src.replace("/thumbs/", "/").replace("_thumb.", "."); }
  
  //replace the src of a property's image
  function GetNewSrc(img_id, src) { Ext.get(img_id).dom.src = getSrcFromThumbSrc(src); }

  //Create the thumbnail images for each property
  function SplitThumbs(strThumbs, img_display_property_id, property_id)
  {
    var returnVar = '';
    var image_count = 0;  
    
    if(strThumbs != "")
    {          
      var arrThumbs = strThumbs.split(","); 
      
      var i;
      for(i = 0; i < arrThumbs.length; i++)
      {            
        if(arrThumbs[i] != "")
        {
          image_count = i+1;
          
          //only display the first "thumb_display_number" of images
          if(image_count > thumb_display_number) 
            { returnVar += "<td class=\"border-thumb\" style=\"display:none\" id=\"td_thumb_" + img_display_property_id + "_" + image_count + "\" ><a href=\"javascript:AV.tpl_unit.getNewSrc('" + img_display_property_id + "','" + arrThumbs[i] + "')\" onClick=\"AV.tpl_unit.thumbSelected( 'td_thumb_" + img_display_property_id + "'," + arrThumbs.length + "," + image_count + " )\"><img width=\"60\" height=\"40\" src=\"" + arrThumbs[i] + "\"/></a></td>"; }
          else
            { returnVar += "<td class=\"border-thumb\" id=\"td_thumb_" + img_display_property_id + "_" + image_count + "\" ><a href=\"javascript:AV.tpl_unit.getNewSrc('" + img_display_property_id + "','" + arrThumbs[i] + "')\" onClick=\"AV.tpl_unit.thumbSelected( 'td_thumb_" + img_display_property_id + "'," + arrThumbs.length + "," + image_count + " )\" ><img width=\"60\" height=\"40\" src=\"" + arrThumbs[i] + "\"/></a></td>"; }
        }
      }
      //add left button --automatically with disabled image, as the first (left to right) images are originally displayed
      returnVar = "<td id=\"td_"+ img_display_property_id + "_left_button\"><a href=\"javascript:AV.tpl_unit.rotateThumbs('" + property_id + "'," + image_count + "," + thumb_display_number + ",'" + img_display_property_id + "', 'left');\" style=\"cursor:default\"><img id=\"img_"+ img_display_property_id + "_left_button\" width=\"20\" alt=\"<<\" src=\"images/arrow-previous-disabled.png\"></img></a></td>" + returnVar; 
      
      //add right button
      //if there are fewer images than the thumb_display_number, hide it
      if(image_count <= thumb_display_number)
        { returnVar += "<td id=\"td_"+ img_display_property_id + "_right_button\"><a href=\"javascript:AV.tpl_unit.rotateThumbs('" + property_id + "'," + image_count + "," + thumb_display_number + ",'" + img_display_property_id + "', 'right');\" style=\"cursor:default\"><img id=\"img_"+ img_display_property_id + "_right_button\" width=\"20\" alt=\">>\"src=\"images/arrow-next-disabled.png\"></img></a></td>"; }
      else
        { returnVar += "<td id=\"td_"+ img_display_property_id + "_right_button\"><a href=\"javascript:AV.tpl_unit.rotateThumbs('" + property_id + "'," + image_count + "," + thumb_display_number + ",'" + img_display_property_id + "', 'right');\" style=\"cursor:pointer\"><img id=\"img_"+ img_display_property_id + "_right_button\" width=\"20\" alt=\">>\"src=\"images/arrow-next.png\"></img></a></td>"; }
    }
    
    return returnVar;      
  }
  
  function GetUploadButton(property_id, unit, building, floor_plan)
  {  
    var show_upload = false;
    if(Ext.get("div_upload_images")){ show_upload = true; }
    
    if(show_upload == true)
      { return "<a id=\"a_manage_images_" + property_id + "\" class=\"clsButton\" href=\"javascript:ShowUploadImagePanel('" + property_id + "','" + unit + "','" + building + "','" + floor_plan + "','a_manage_images_" + property_id + "')\">Manage Images</a>"; }
    else
      { return "<span></span>"; }
  }
  
  //Highlight the selected thumbnail
  function ThumbSelected(td_thumb_img_display_property_id, thumb_count, selected_thumb_number)
  {
    Ext.get(td_thumb_img_display_property_id + "_" + selected_thumb_number).dom.style.border = "1px solid black";
    
    var i;
    for(i = 1; i < thumb_count; i++)
    {    
      //un-highlight all other thumbs
      if(i != selected_thumb_number)
        { Ext.get(td_thumb_img_display_property_id + "_" + i).dom.style.border = "1px solid transparent"; }
    }  
  }

  function shiftThumbs(thumb_count, thumb_display_number, img_display_property_id, direction)
  {
    var td_thumb_id = 'td_thumb_' + img_display_property_id;
    //for now only scroll to the end or beginning...do not wrap
    
    var lastThumb = Ext.get(td_thumb_id + "_" + thumb_count);
    
    var firstThumb = Ext.get(td_thumb_id + "_1");
    
    //go through each thumbnail and find the highest displayed 
    var lastDisplayedNum = 0;
    
    for(var i = 0; i < thumb_count; i++)
    { 
      var count = i+1
      var td_id = td_thumb_id + "_" + count;
      
      if(Ext.get(td_id).dom.style.display == "") { lastDisplayedNum = count; }        
    }      
    
    //Calculate other positions
    var firstDisplayedNum = lastDisplayedNum - thumb_display_number + 1;
    var firstToDisplayNum = firstDisplayedNum - 1;
    var lastToDisplayNum = lastDisplayedNum + 1;
    
    var firstThumbDisplayed = Ext.get(td_thumb_id + "_" + firstDisplayedNum);
    var lastThumbDisplayed = Ext.get(td_thumb_id + "_" + lastDisplayedNum);
    
    var firstThumbToDisplay = Ext.get(td_thumb_id + "_" + firstToDisplayNum);      
    var lastThumbToDisplay = Ext.get(td_thumb_id + "_" + lastToDisplayNum);
    
    var leftButton = Ext.get("img_" + img_display_property_id + "_left_button");
    var rightButton = Ext.get("img_" + img_display_property_id + "_right_button");
          
    if( direction == "left" )
    {
      if( firstThumb.dom.style.display != "" )    //if the left most icon is displayed, do not process
      {            
        //going left -- > hide the farthest on the right, and display the first on the left
        lastThumbDisplayed.dom.style.display = "none";
        firstThumbToDisplay.dom.style.display = "";
      }
      
      //now, check the firstThumb again...if it is displayed, disabled the button
      if(firstThumb.dom.style.display == "")
      {    
        leftButton.dom.src = "images/arrow-previous-disabled.png";
        leftButton.dom.parentNode.style.cursor = "default";
      }
        
      //display the right button if the last thumb is not yet visible
      if(lastThumb.dom.style.display != "")
      {
        rightButton.dom.src = "images/arrow-next.png";
        rightButton.dom.parentNode.style.cursor = "pointer";
      }
        
    }
    
    if(direction == "right")
    {
      if(lastThumb.dom.style.display != "" )
      {           
        //going right -- > hide the farthest on the left, and display the first on the right              
        firstThumbDisplayed.dom.style.display = "none";
        lastThumbToDisplay.dom.style.display = "";       
     
      }
      
      //now, check the lastThumb again...if it is displayed, disabled the button
      if(lastThumb.dom.style.display == "")
      {
        rightButton.dom.src = "images/arrow-next-disabled.png";
        rightButton.dom.parentNode.style.cursor = "default";
      }
        
      //display the left button if the first thumb is not visible
      if(firstThumb.dom.style.display != "")
      {
        leftButton.dom.src = "images/arrow-previous.png";
        leftButton.dom.parentNode.style.cursor = "pointer";
      }
    } 
  }

  function RotateThumbs(property_id, thumb_count, thumb_display_number, img_display_property_id, direction)
  {
    var div_thumb_rotator = Ext.get("div_thumb_rotator_" + property_id);
    
    div_thumb_rotator.shift({
      duration: .2,
      opacity: .5,
      callback: function (){
        var div_thumb_rotator_temp = Ext.get("div_thumb_rotator_" + property_id);
        div_thumb_rotator_temp.shift({duration: .2, opacity: 1, callback:shiftThumbs(thumb_count, thumb_display_number, img_display_property_id, direction)});
      }    
    });      
  }

  
  return{
      
    getTemplate: function(){
    
      if(!template) { templateInit(); }        
      return template;        
    },
    toggleDetails: function(div_id) {
      ToggleDetails(div_id);
    },
    showArea: function(area) {
      return ShowArea(area);
    },
    setToolTipCssClass: function(src) {
      return SetToolTipCssClass(src);
    },
    getOrigDisplayImage: function(property_id, thumbs, default_image) {
      return GetOrigDisplayImage(property_id, thumbs, default_image);
    },
    splitThumbs: function(strThumbs, img_display_property_id, property_id) {
      return SplitThumbs(strThumbs, img_display_property_id, property_id);
    },
    getUploadButton: function(property_id, unit, building, floor_plan) {
      return GetUploadButton(property_id, unit, building, floor_plan);
    },
    getNewSrc: function(img_id, src) {
      GetNewSrc(img_id, src);
    },
    thumbSelected: function(td_thumb_img_display_property_id, thumb_count, selected_thumb_number) {
      ThumbSelected(td_thumb_img_display_property_id, thumb_count, selected_thumb_number);
    },
    rotateThumbs: function(property_id, thumb_count, thumb_display_number, img_display_property_id, direction) {
      RotateThumbs(property_id, thumb_count, thumb_display_number, img_display_property_id, direction);
    }
  }
}


//Update the thumb display 
function updateThumbs(property_id)
{
  var arr_thumbs = new Array();
  
  AV.img_store.getStore().each(function(record){  
    arr_thumbs.push(record.get("thumb_path"));  
  });
  //comma delimited list of thumbs
  var thumbs_list = arr_thumbs.join(",");
  
  //create the inner html for the thumb div
  var thumb_inner_html = '<table border="0"><tr>';
  
  thumb_inner_html += AV.tpl_unit.splitThumbs(thumbs_list, "img_display_" + property_id, property_id);
  thumb_inner_html += '</tr></table>';
  thumb_inner_html += '<input id="thumbs_' + property_id + '" type="hidden" value="' + thumbs_list + '"></input>';
  
  Ext.get("div_thumb_rotator_" + property_id).dom.innerHTML = thumb_inner_html;
}

AV.VisitorInfoLink = new function(){
    
  function saveLinkSuccess(response, options){ Alert.show("Visitor Info Link", response.responseText); }
  
  function saveLinkFail(response, options)
    { Alert.show("Failure", "The Visitor Info Link could not be saved. " + response.responseText + " Please try again."); }
  
  return{
  
    saveVisitorInfoLink: function(btn, text){
  
      if (btn == 'ok')
      {
        if(!isNaN(text))
        {
          var frm = '../forms/formDisplay.asp?frm_id=' + text;
          Ext.Ajax.request({
           url: 'admin.asp?frm=' + frm + '&type=saveVisitorInfoLink&frm_id=' + text,
           success: saveLinkSuccess,
           failure: saveLinkFail
          });  
        }
        else
        {
          var obj = new Object();
          obj.responseText = "This is not a valid frm id. ";
          saveLinkFail(obj);
        }
      }
    }
          
  }
}

AV.results_panel = new function(){
  
  var panel;
  
  function panelInit(){
     panel = new Ext.Panel({
          id:'results_panel',
          frame:true,
          //autoWidth:true,
          width: 450,
          autoHeight:true,
          layout:'fit',
          header: false,
          renderTo:'div_search_results',
          items: AV.dataview_property.getDataview()
      });
      
       //Henderson does not want this displayed for What Would My Property Rent for
      if(assnId == '11297' && Ext.get("div_market_analysis_results"))
      {
        panel.hide();    
        Ext.get("market_rent_disclaimer").dom.style.display = '';
      }
  }
  
  return{
    
    getPanel: function(){
      if(panel) { panel.destroy(); }   //if the panel already exists, destroy it so it can be recreated with the new search
                
      //initialize a new panel each time
      panelInit();             
      return panel;
    }  
  }
}      

AV.dataview_property = new function(){
  
  var dataview;
  
  function dataviewInit(){
  
    dataview = new Ext.DataView({
      id: "data_view_properties",
      store: AV.results_store.getStore(),
      tpl: AV.tpl_unit.getTemplate(),                
      autoHeight:true,
      itemSelector:'div.property-wrap',
      emptyText: 'Search returned no properties',
      loadingText: 'Loading Results',
      prepareData:  function(data){
                      data.Rent = doMoney(data.Rent);
                      
                      if(!isNaN(data.SecurityDeposit)) { //4/23/2009 *DA* added NaN check
                        data.SecurityDeposit = doMoney(data.SecurityDeposit);
                      }
                      return data;
                    }
    })
  }
  
  return{
    
    getDataview: function(){
      //reinitialize dataview each time
      dataviewInit();        
      return dataview;
    }
  }
}      


var image_tabs = new function(){

  var image_panel;
  var unit_tab;
  var building_tab;
  var floor_plan_tab;
  var main_listing_image_id = '0';
  
  function SetDefaultImage()
  {
    var c = getAbditus();
    if( c == "") { return; }
    
    Ext.Ajax.request({
     url: 'put_property_images.aspx?action=setDefault&image_id=' + main_listing_image_id + '&c=' + c,
     success: defaultImageSet,
     failure: defaultImageFailed            
    });
  }
  
  function defaultImageSet(response, options){
    Alert.show('Success', 'Main Listing Image set successfully.  It will be displayed the next time the property is loaded.');
  }

  function defaultImageFailed(response, options){
    Ext.MessageBox.alert('setting the main listing image failed', response.responseText);
  }
  
  function confirmImageAsDefault(btn)
  {
    if(btn == 'yes') { SetDefaultImage(); }
  }
  
  return{
	        init : function(){ 
	        	        	        
	            // Panel for the center
              image_panel = new Ext.TabPanel({
                  id: 'pics_panel',
                  title: 'Pictures',
                  region: 'center',
                  autoScroll: true,
                  split: true,
                  width: 200,
                  margins:'3 0 3 3',
                  cmargins:'3 3 3 3'                  
              });
              
          },
              
          createTabs: function() {
            
            var show_tabs = false;
            if(Ext.get("div_upload_images")){ show_tabs = true}
  
            var unit_images_exist = AV.img_store.getStore().find("image_category", unit_category) != -1;
            var building_images_exist = AV.img_store.getStore().find("image_category", building_category) != -1;
            var floor_plan_images_exist = AV.img_store.getStore().find("image_category", floor_plan_category) != -1;
  
	          //Create display templates for Property, Building, and Unit Type specific images
	          
	          //if property images exist or the user has privs, display tab
	          if(unit_images_exist == true || show_tabs == true)
	          {
              var img_tpl_unit = new Ext.XTemplate(
                '<tpl for=".">',
                  '<tpl if="image_category == unit_category">',            
                    '<div class="thumb-wrap" id="{image_name}" image_id="{image_id}" thumb_path="{thumb_path}">',
                      '<div class="thumb"><img src="{thumb_path}" title="{image_name}"></div>',
                      '<span class="x-editable">{shortName}</span>',
                    '</div>',  
                  '</tpl>',    
                '</tpl>',
                '<div class="x-clear"></div>'
              );
              
              unit_tab = new Ext.DataView({
                  id: "data_view_property_images",
                  store: AV.img_store.getStore(),
                  tpl: img_tpl_unit,
                  title: "Property Images",
                  autoHeight:true,
                  multiSelect: true,
                  overClass:'x-view-over',
                  itemSelector:'div.thumb-wrap',
                  emptyText: 'No property images to display',
                  loadingText: 'Loading images',
                  listeners:  {
                                'selectionchange' : {
                                  fn: image_tabs.onSelectionChange
                                },
                                'beforehide' : {
                                  fn: function() {
                                   this.clearSelections();
                                  }                          
                                },
                                'dblclick' : {
                                  fn: image_tabs.showFullImage
                                }         
                  },

                  prepareData: function(data){
                      data.shortName = Ext.util.Format.ellipsis(data.name, 15);
                      //data.sizeString = Ext.util.Format.fileSize(data.size);
                      //data.dateString = data.lastmod.format("m/d/Y g:i a");
                      return data;
                  }
                })
            
              image_panel.add(unit_tab);
            
            }
            else { unit_tab = null; }
            
            //if building images exist or the user has privs, display tab
            if(building_images_exist == true || show_tabs == true)
            {
               var img_tpl_building = new Ext.XTemplate(
                '<tpl for=".">',
                  '<tpl if="image_category == building_category">',            
                    '<div class="thumb-wrap" id="{image_name}" image_id="{image_id}" thumb_path="{thumb_path}">',
                      '<div class="thumb"><img src="{thumb_path}" title="{image_name}"></div>',
                      '<span class="x-editable">{shortName}</span>',
                    '</div>',  
                  '</tpl>',    
                '</tpl>',
                '<div class="x-clear"></div>'
              );
              
              building_tab = new Ext.DataView({
                  id: "data_view_building_images",
                  store: AV.img_store.getStore(),
                  tpl: img_tpl_building,
                  title: "Building Images",
                  autoHeight:true,
                  multiSelect: true,
                  overClass:'x-view-over',
                  itemSelector:'div.thumb-wrap',
                  emptyText: 'No building images to display',
                  loadingText: 'Loading images',
                  listeners:  {
                                'selectionchange' : {
                                  fn: image_tabs.onSelectionChange
                                },
                                'beforehide' : {
                                  fn: function() {
                                   this.clearSelections();
                                  }                          
                                },
                                'dblclick' : {
                                  fn: image_tabs.showFullImage
                                }       
                  },

                  prepareData: function(data){
                      data.shortName = Ext.util.Format.ellipsis(data.name, 15);
                      return data;
                  }
              })
                
             image_panel.add(building_tab);
            
            }
            else { building_tab = null; }
                    
            //if floor_plan images exist or the user has privs display tab
            if(floor_plan_images_exist == true || show_tabs == true)
            {
              var img_tpl_unit_type = new Ext.XTemplate(
                '<tpl for=".">',
                  '<tpl if="image_category == floor_plan_category">',            
                    '<div class="thumb-wrap" id="{image_name}" image_id="{image_id}" thumb_path="{thumb_path}">',
                      '<div class="thumb"><img src="{thumb_path}" title="{image_name}"></div>',
                      '<span class="x-editable">{shortName}</span>',
                    '</div>',  
                  '</tpl>',    
                '</tpl>',
                '<div class="x-clear"></div>'
              );
              
              floor_plan_tab = new Ext.DataView({
                  id: "data_view_floor_plan_images",
                  store: AV.img_store.getStore(),
                  tpl: img_tpl_unit_type,
                  title: "Floor Plan Images",
                  autoHeight:true,
                  multiSelect: true,
                  overClass:'x-view-over',
                  itemSelector:'div.thumb-wrap',
                  emptyText: 'No floor plan images to display',
                  loadingText: 'Loading images',
                  listeners:  {
                                'selectionchange' : {
                                  fn: image_tabs.onSelectionChange
                                },
                                'beforehide' : {
                                  fn: function() {
                                   this.clearSelections();
                                  }                          
                                },
                                'dblclick' : {
                                  fn: image_tabs.showFullImage
                                }       
                  },

                  prepareData: function(data){
                      data.shortName = Ext.util.Format.ellipsis(data.name, 15);
                      return data;
                  }
              })
             
              image_panel.add(floor_plan_tab);
                              
           }      
           else { floor_plan_tab = null; }       
           
           
           //activate tab
           if(unit_tab) { image_panel.activate(unit_tab); }     
           else if (building_tab){ image_panel.activate(building_tab); }
           else if (floor_plan_tab) { image_panel.activate(floor_plan_tab); }     
           else {image_panel.getEl().update('<div style="width:100%;" class="x-panel-body">No Pictures Available</div>');}                                                  
        	        
        },                
        
        getPanel: function(){ return image_panel; },        
        
        showFullImage: function(data_view, index, node, e) {
          //set the panels content, based on the path for the full sized image
          //must create the div that is the contentEl dynamically, because when it is closed, it is destroyed.  													
          Ext.get("div_full_image_panel").dom.innerHTML = '<div id="div_full_image"><img id="full_image" src="' + node.attributes["thumb_path"].value.replace("/thumbs/", "/").replace("_thumb.", ".") + '"></img></div>';
          
          var winFullImage = new Ext.Window({
              title: 'Full Image',
              closable:true,
              width:600,
              height:400,
              plain:true,
              contentEl: "div_full_image"
          });
          
          winFullImage.show();          
        },

        //Called when an image is selected/deselected
        onSelectionChange: function( data_view, arrSelections ) {   
          var btn_delete = Ext.getCmp("btn_delete_image");
          
          if(arrSelections.length > 0) 
          { 
            if(btn_delete) { btn_delete.enable(); }
            //set first selected image (for saving the default display image
            main_listing_image_id = arrSelections[0].attributes['image_id'].value;
          }
          else 
          {         
            if(btn_delete) { btn_delete.disable();}    
            main_listing_image_id = '0';
          }
        },

        deleteImage: function(btn) {

          if( btn == "yes" )    //if the user clicked the yes button, delete image
          { 
            var activeTabId = image_tabs.getPanel().getActiveTab().getId();    //the id of the dataview currently being displayed 
            var current_data_view = Ext.getCmp(activeTabId);
           
           //Cant just use .getSelectedRecords(), because the selector gets confused when using multiple DataViews with one DataStore.
            var arrSelectedNodes = current_data_view.getSelectedNodes();
            var arrDeleteImages = new Array();
            
            var i;
            for(i = 0; i< arrSelectedNodes.length; i++)
            { 
              arrDeleteImages.push(arrSelectedNodes[i].attributes["image_id"].value);
            }
            
            var delete_images = arrDeleteImages.join(",");
            
            var c = getAbditus();
            if( c == "") { return; }
            
            Ext.Ajax.request({
             url: 'put_property_images.aspx?action=delete&c=' + c,
             success: image_tabs.imagesDeleted,
             failure: image_tabs.imageDeletingFailed,             
             params: {               
                        delete_images: delete_images                        
                     }
            });
          }         
        },
                        
        setDefaultImage: function(){
        
          if(main_listing_image_id == '0') { Alert.show('No image selected', 'Please Select an image.'); }
          else
          {                                    
            //IF a Building image has been selected, notify user that all property level default images will be reset and the building image will be the default
            //IF a Floor Plan image has been selected, notify user that all floor plan level default images will be reset and the floor plan image will be the default            
            switch(image_panel.getActiveTab().getId())
            {
              case 'data_view_building_images':
                Ext.MessageBox.confirm('Confirm', 'Selecting a building image as a main listing image (re)sets the main listing image for all properties in the building.  Do you want to proceed?', confirmImageAsDefault);
                break;
                
              case 'data_view_floor_plan_images':
                Ext.MessageBox.confirm('Confirm', 'Selecting a floor plan image as a main listing image (re)sets the main listing image for all properties for this building with this floorplan.  Do you want to proceed?', confirmImageAsDefault);
                break;
                
              case 'data_view_property_images':
                SetDefaultImage();
                break;
            }                                   
          }
        },
                
        imagesDeleted: function(response, options){
          AV.img_store.loadStore();
        },

        imageDeletingFailed: function(response, options){
          Ext.MessageBox.alert('Delete Failed', response.responseText);
        },                
        
        openUpload: function()
        {
          //determine which tab the user is viewing
           var activeTab = image_tabs.getPanel().getActiveTab();    
           winUpload.setUploadDirectory(activeTab);
           
           winUpload.show('btn_add_image');  
        },
        
        imagesSaved: function(response, options){
          AV.img_store.loadStore();
        },

        imageSavingFailed: function(response, options){
          alert(response.responseText);
        }
                        
    }

}();

var image_details_south = new function(){

  var image_panel;
  
  function getHtml()
    { return '<div style="padding: 8px;">To choose the main listing image to display, select the desired image and click <a href="javascript:image_tabs.setDefaultImage();">Select Default Image</a></span>'; }
  
  return{
	        init : function(){ 
	        	        	        
	            // Panel for the south
              image_panel = new Ext.Panel({
                  id: 'pics_panel_south',
                  region: 'south',
                  //title: 'Pictures',
                  autoScroll: false,
                  split: false,
                  //width: 200,
                  height: 30,
                  //split: true,
                  margins:'3 0 3 3',                  
                  collapsible: true,
                  animCollapse: true,
                  //header: true,
                  html: getHtml()            
              });              
          },              
        
          getPanel: function() { return image_panel; }
    }
}();


AV.img_store = new function() {

  var store;
  var current_building;
  var current_unit;
  var current_floor_plan;
    
  return{
  
    initStore: function(unit, building, floor_plan, c){
    
      //save current unit information
      current_unit = unit;
      current_building = building;
      current_floor_plan = floor_plan;
    
      //Create the store for the property's images
      store = new Ext.data.JsonStore({
        url: 'get_property_images.aspx?Building=' + current_building + '&Unit=' + current_unit + '&FloorPlan=' + current_floor_plan + '&c=' + c,
        root: 'images',    
        fields: ['image_id','image_name', 'image_path', 'thumb_path', 'image_category']
      });
    },
    getStore: function(){
    
      if(store)
        return store;
      
    },
    loadStore: function(config){
      if(store)
      {
        if(config) { store.load(config); }
        else { store.load(); }
      }
    },
    getCurrentUnit: function(){
      return current_unit;
    },
    getCurrentBuilding: function(){
      return current_building;
    },
    getCurrentFloorPlan: function(){
      return current_floor_plan;
    }
  
  } 
}


function getAbditus()
{
  var a = Ext.get("abditus");
  if(a) { return a.dom.value; } else { return ""; }
}

function ShowUploadImagePanel(property_id, unit, building, floor_plan, animLink)
{      
  var c = getAbditus();
  if( c == "") { return; }
    
  image_tabs.init();
  image_details_south.init();
        
  //Create the store for the property's images
  AV.img_store.initStore(unit, building, floor_plan, c);
  AV.img_store.loadStore({callback: image_tabs.createTabs});

  var win = new Ext.Window({
      title: 'Image Details',
      closable:true,
      width:550,
      height:450,
      plain:true,
      modal: true,
      layout: 'border',

      items: [image_tabs.getPanel(), image_details_south.getPanel()]
  });
  
  //if this div exists, add buttons
  if(Ext.get("div_upload_images"))
  {
    var btn_add_image = new Ext.Button({
      id: "btn_add_image",
      text: "Add Image",
      handler: image_tabs.openUpload
    });
    
    var btn_delete_image = new Ext.Button({
      id: "btn_delete_image",
      text: "Delete Image",
      handler:   function() {
                              Ext.MessageBox.confirm('Confirm', 'Do you want to delete the selected images?', image_tabs.deleteImage);       
                            }        
    });
    
    var btn_cancel = new Ext.Button({
      id: "btn_cancel",
      text: "Cancel",
      handler: function(){
        win.hide(Ext.get(animLink));
      }
    });
    
     var btn_ok = new Ext.Button({
      id: "btn_ok",
      text: "OK",
      handler: function(){
        updateThumbs(property_id);
        win.hide(Ext.get(animLink));
      }
    });
    
    win.addButton(btn_ok);
    win.addButton(btn_cancel);
    win.addButton(btn_add_image);   
    win.addButton(btn_delete_image);  
  }  
  
  win.show(Ext.get(animLink));
  
}   

function doMoney(v, metadata, record, rowIndex, colIndex, store)
{
  //borrowed this function from Ext.  The only change is that decimals are not displayed
  v = (Math.round((v-0)*100))/100;
  v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
  v = String(v);
  var ps = v.split('.');
  var whole = ps[0];
  var sub = ps[1] ? '.'+ ps[1] : '.00';
  var r = /(\d+)(\d{3})/;
  while (r.test(whole)) { whole = whole.replace(r, '$1' + ',' + '$2'); }
  
  //v = whole + sub;
  v = whole;
  
  if(v.charAt(0) == '-'){ return '-$' + v.substr(1); }
  
  return "$" +  v;

}

//sort function used to sort arrays by numeric values
function sortNumber(a,b) { return a - b; }

//Callback function for loading the results grid
function resultsLoaded(response, options)
{  
  //reset message each time
  if(Ext.get("div_results_message"))
  {
    Ext.get("div_results_message").dom.innerHTML = "";
    Ext.get("div_results_message").hide();
  }

  AV.results_panel.getPanel();            
  
  //Hide the message box after the results have loaded
  Ext.MessageBox.hide();          
  
  Ext.get('div_search_results_img').dom.style.display = 'none';
  
  //display message
  if(AV.results_store.getStore().getCount() < 1 && Ext.get("div_results_message"))
  {
    if(!Ext.get("div_market_analysis_results"))
    {
      Ext.get("div_results_message").dom.innerHTML = "There are no listings at this time that match your search criteria.";
      Ext.get("div_results_message").show();
    }
  }
  
  //load tool tips
  var avTip = new AV.NFTip({targets:"img.tooltipAnchor", getContentFn:generateContent});
    
  //toggle "map all" button (Also, Hide it For Henderson's WWMPRF page
  if(AV.results_store.getStore().getCount() > 0 && (assnId != '11297' || !Ext.get('div_market_analysis_results')))       
    document.getElementById("map_all").style.display = "";  
  else
    document.getElementById("map_all").style.display = "none";    
    
  if(AV.results_store.getStore().getCount() > 99)
    Alert.show('Limit Your Search', 'Only the first 100 results have been displayed.  To view different results, please limit your search.');
  
  var high_rent = 0;
  var low_rent = 0;
  var avg_rent = 0;
  var total_rent = 0;
  var arr_rents = new Array();

  //if showing the rental comparison page, calculate the analysis results
  if( document.getElementById("div_market_analysis_results") )
  {        
    //Show analysis div
    document.getElementById("div_market_analysis").style.visibility="visible";
    
    //loop through each record, calculate summary values, and create a json record 
    AV.results_store.getStore().each(function(record){
      var rent = record.get("Rent").replace("$", "").replace(",", ""); 
      if(rent)
      {                       
        if(!isNaN(rent))  //if the rent is not a number, don't include it
        {         
          if(rent > 0)
          {                                              
            arr_rents.push(parseFloat(rent));
            total_rent += parseFloat(rent);
          }
        }
      }
    });    
    
    if(arr_rents.length > 0)
    {
      arr_rents.sort(sortNumber);
            
      low_rent = arr_rents[0];
      high_rent = arr_rents[arr_rents.length -1];
      avg_rent = Math.ceil((total_rent / (arr_rents.length)));    
      
      var summary = "<table style=\"margin:10px\"><tr><td>Based on the information you’ve entered and the market information currently available, the current market rent ranges from "
      
      summary += "<b>$" + low_rent + "</b>";
      summary += " to <b>$" + high_rent + "</b>";
      summary += ", with the average rent within this range being <b>$" + avg_rent + "</b>.</td>";
      summary +- "<td>To view the rental properties that match your criteria, please feel free to browse the listings below.";
      summary += "</td></tr></table>";
            
      Ext.get("div_market_analysis_results").dom.innerHTML = summary;           
    }
    else
    {
      Ext.get("div_market_analysis_results").dom.innerHTML = '<span class="clsLabelMand">Rent data is not available based on the search criteria entered.</span>';
    }
  }
  else { document.getElementById("div_results").style.visibility="visible"; }  //show results div       
}

function clearSearch()
{
  document.getElementById('search_city').value = "";
  document.getElementById('search_state_id').value = 0;
  document.getElementById('search_zip').value = "";
  document.getElementById('search_area_id').value = 0;
  document.getElementById('search_min_rent_id').value = 0;
  document.getElementById('search_max_rent_id').value = 0;        
  document.getElementById('search_bed_id').value = 0;
  document.getElementById('search_bath_id').value = 0;
  document.getElementById('search_min_sqfeet_id').value = 0;
  document.getElementById('search_max_sqfeet_id').value = 0;
  document.getElementById('search_unittype_id').value = 0;
  document.getElementById('search_age_id').value = 0;
}

function getSearchQueryStringArray()
{
  var q_string_array = new Array();
      
  q_string_array.push('action=search');

  //the management company var is created in the xsl
  q_string_array.push('mgmt_company=' + mgmt_company);

  //Search info
  q_string_array.push('s_city=' + document.getElementById('search_city').value);
  q_string_array.push('s_state=' + document.getElementById('search_state_id').value);
  q_string_array.push('s_zip=' + document.getElementById('search_zip').value);
  q_string_array.push('s_area=' + document.getElementById('search_area_id').value);

  q_string_array.push('s_minrent=' + document.getElementById('search_min_rent_id').value);
  q_string_array.push('s_maxrent=' + document.getElementById('search_max_rent_id').value);      
  q_string_array.push('s_status=' + document.getElementById('search_status_id').value);
  q_string_array.push('s_beds=' + document.getElementById('search_bed_id').value);
  q_string_array.push('s_baths=' + document.getElementById('search_bath_id').value);
  //Concatenate min and max sqfeet into format "1000||2000"
  q_string_array.push('s_sqfeet=' + document.getElementById('search_min_sqfeet_id').value + '||'+ document.getElementById('search_max_sqfeet_id').value);
  q_string_array.push('s_unittype=' + document.getElementById('search_unittype_id').value);
  q_string_array.push('s_age=' + document.getElementById('search_age_id').value);

  return q_string_array;
}

function doSearch()
{  
  if(Ext.isReady == true)
  {  
    if(Ext.get("div_search_results"))
    {       
      if(checkSearchCriteria() == true)
      {
        //Show the searching dialog
        dlgProgress.show();                                        
        
        var q_string = getSearchQueryStringArray().join('&');
       
        //Create Results        
        AV.results_store.createStore(q_string);         
        AV.results_store.getStore().load({callback: resultsLoaded});                                         
      }      
      else
      {
        //What would my property rent for specific message for Henderson
        if(assnId == '11297' && Ext.get('div_market_analysis_results'))
          { Alert.show('Select Criteria','You must specify a property type and a zip code to perform a rental analysis.'); }
        else
          { Alert.show('Select Search Criteria','You must specify at least one search criterion to perform a search.'); }
      }
    }    
  }
}

function checkSearchCriteria()
{
  //What would my property rent for Required fields for Henderson
  if(assnId == '11297' && Ext.get('div_market_analysis_results'))
  {
    if( Ext.get('search_zip').dom.value == "") {return false};
    //if( Ext.get('search_bed_id').dom.value == 0) {return false};
    //if( Ext.get('search_min_sqfeet_id').dom.value == 0 && Ext.get('search_max_sqfeet_id').dom.value == 0) {return false};
    if( Ext.get('search_unittype_id').dom.value == 0) {return false};   
    
    //return true;
  }
  /*
  else
  {
    if( Ext.get('search_city').dom.value != "") {return true};
    if( Ext.get('search_state_id').dom.value != 0) {return true};
    if( Ext.get('search_zip').dom.value != "") {return true};
    if( Ext.get('search_area_id').dom.value != 0) {return true};
    if( Ext.get('search_min_rent_id').dom.value != 0) {return true};
    if( Ext.get('search_max_rent_id').dom.value != 0) {return true};  
    if( Ext.get('search_bed_id').dom.value != 0) {return true};
    if( Ext.get('search_bath_id').dom.value != 0) {return true};
    if( Ext.get('search_min_sqfeet_id').dom.value != 0) {return true};
    if( Ext.get('search_max_sqfeet_id').dom.value != 0) {return true};
    if( Ext.get('search_unittype_id').dom.value != 0) {return true};
    if( Ext.get('search_age_id').dom.value != 0) {return true};
  }
 
  return false;
  */
  
  return true;
}


AV.defaultQuery = new function(){
    
  function saveQuerySuccess(response, options)
  {
     Alert.show("Default Query", response.responseText);
  }
  
  function saveQueryFail(response, options)
  {
    Alert.show("Failure", "The default query could not be saved.  Please try again.");
  }
  
  return{
  
    saveDefaultQuery: function(){
    
      //var q_string = getSearchQueryStringArray().join('~and~').replace('=', '~equals~') + '&type=saveDefaultQuery';
      var q_string = escape(getSearchQueryStringArray().join('&')) + '&type=saveDefaultQuery';
  
      Ext.Ajax.request({
       url: 'admin.asp?q=' + q_string,
       success: saveQuerySuccess,
       failure: saveQueryFail
      });  
    
    }          
  }
}

AV.Rental.Map = {

  showRentalMap : function (address, city, state, zip, rent, status, beds, baths, square_feet, unit_type, year_built, security_deposit)
  {    
    if(state && state != "")   //add comma
      state += ",";

    //these value will be retrieved from the child map page
    mapAddress = address + ' ' + city + ' ' + state + ' ' + zip;
    mapAddressDescription = this.createAddressDescription(address, city, state, zip, rent, status, beds, baths, square_feet, unit_type, year_built, security_deposit);

    var strURL = "MicrosoftMaps.htm?map_type=single";
	  var map_win = window.open(strURL,null,"height=400,width=600, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=yes");
  },

  showRentalMap_AllProperties : function()
  {      
    arrResults = new Array();
    
    AV.results_store.getStore().each(function(record){
       
      var address = record.get("Address");
      var city = record.get("City");
      var state = record.get("State");
      var zip = record.get("Zip");    

      //Filter out addresses that are invalid
      if((address && address != ""))    //if no address exists, do not display on map
      {
        if((city && city != "" && state && state != "") || (zip && zip != ""))  // if the city and state dont exist or the zip doesnt exist, dont display
        {
          if(state && state != "")   //add comma
            state += ",";

          var map_address =  address + ' ' + city + ' ' + state + ' ' + zip;                
          
          var objAddress = new Object();
          objAddress.address = map_address;
          objAddress.description = AV.Rental.Map.createAddressDescription(address, city, state, zip, record.get("Rent"), record.get("Status"), record.get("Beds"), record.get("Baths"), record.get("SquareFeet"), record.get("UnitType"), record.get("YearBuilt"), record.get("SecurityDeposit"));

          arrResults.push(objAddress);            
        }             
      }
    });
    
	  var map_win = window.open("MicrosoftMaps.htm?map_type=multiple",null,"height=400,width=600, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=yes");  	
  },

  createAddressDescription : function(address, city, state, zip, rent, status, beds, baths, square_feet, unit_type, year_built, security_deposit)
  {
     var addressDescription = '<table cellspacing="5">';
      addressDescription += this.createAddressDescriptionRecord('Address', address);           
      addressDescription += this.createAddressDescriptionRecord('City', city); 
      addressDescription += this.createAddressDescriptionRecord('State', state); 
      addressDescription += this.createAddressDescriptionRecord('Zip', zip); 
      addressDescription += this.createAddressDescriptionRecord('Rent', rent); 
      //addressDescription += this.createAddressDescriptionRecord('Status', status); 
      addressDescription += this.createAddressDescriptionRecord('Beds', beds); 
      addressDescription += this.createAddressDescriptionRecord('Baths', baths); 
      addressDescription += this.createAddressDescriptionRecord('Sq Feet', square_feet); 
      addressDescription += this.createAddressDescriptionRecord('Unit Type', unit_type); 
      addressDescription += this.createAddressDescriptionRecord('Year Built', year_built); 
      addressDescription += this.createAddressDescriptionRecord('Deposit', security_deposit); 
      addressDescription += '</table>';
    
    return addressDescription;
  },

  createAddressDescriptionRecord : function (strLabel, strValue)
  {
    return '<tr><td style="font-size: 10px;">' + strLabel + ':</td><td style="font-size: 8px;">' + strValue + '</td></tr>';          
  }

};






          
   