
var SearchListings = {
  setup: function() {
    $('#searchButton').click(function() {
      $('#search').submit();
      return false;
    });

    // Nav
    var populate_neighborhoods = function(borough_id) {
      var neighborhood_options = $('#neighborhoodOptions');
      var neighborhood_dropdown = $('#neighborhoodDropdown');
      if(borough_id == "0") {
        neighborhood_dropdown.unbind('click');
        neighborhood_dropdown.find('.selected').html('&nbsp;');
        neighborhood_options.html('');
        $('#nids').val('');
        return false;
      }

      neighborhood_options_for_fancy_select(borough_id, function(html){
        neighborhood_options.html(html);
        neighborhood_dropdown.fancyDropdown({multiple:true});
      });
    };

    $('#boroughDropdown').fancyDropdown({afterSelect: function(id, parent) {
      $('#nids').val('');
      populate_neighborhoods(id);
    }});
    // on page load...
    populate_neighborhoods($('#bid').val());
    $('.fancyDropdownMultiple').fancyDropdown({multiple:true});
    $('.fancyDropdown').fancyDropdown();

    this.listingsMap();
  },
  listingsMap: function() {
    var self = this;  
    var elm_id = 'listingsMap';
    var el = $('#' + elm_id);
    // ignore if listingMap isn't present
    if(el.length == 0) {
      return false;
    }
    // allow map to follow scrolling
    var elpos_original = el.offset().top;
    $(window).scroll(function(){
        var elpos = el.offset().top;
        var windowpos = $(window).scrollTop();
        var finaldestination = windowpos;
        if(windowpos<elpos_original) {
            finaldestination = elpos_original;
            el.stop().css({'top':0});
        } else {
            el.stop().animate({'top':finaldestination-elpos_original + 20}, 500, "linear");
        }
    });

    if (GBrowserIsCompatible()) {
      G_PHYSICAL_MAP.getMinimumResolution = function () { return 10 };
      G_NORMAL_MAP.getMinimumResolution = function () { return 10 };
      G_SATELLITE_MAP.getMinimumResolution = function () { return 10 };
      G_HYBRID_MAP.getMinimumResolution = function () { return 10 };

      G_PHYSICAL_MAP.getMaximumResolution = function () { return 15 };
      G_NORMAL_MAP.getMaximumResolution = function () { return 15 };
      G_SATELLITE_MAP.getMaximumResolution = function () { return 15 };
      G_HYBRID_MAP.getMaximumResolution = function () { return 15 }; 
      map = new GMap2(document.getElementById(elm_id));
      // default to NYC for map location
      map.setCenter(new GLatLng(40.77, -73.98), 11);
      geocoder = new GClientGeocoder();
      var mapControl = new GMapTypeControl();
      map.addControl(mapControl);
      map.addControl(new GSmallMapControl());
    } else {
      return false;
    }
    
    var points = [];
    var bounds = new GLatLngBounds();
    
    if (geocoder) {
      // add points to map
      $('.listingRow').each(function(i) {
        var parent = this;
        var latitude = $(this).attr('data-latitude');
        var longitude = $(this).attr('data-longitude');
        var id = $(this).attr('data-id');
        
        var point = new GLatLng(latitude,longitude);
        points.push(point);
        var marker = na_gmaps_marker(point);
        map.addOverlay(marker);
        
        // setup events
        GEvent.bind(marker, "mouseout", this, function() {
          self.highlightRow(parent, false);
        });
        GEvent.bind(marker, "mouseover", this, function() {
          // highlight proper row
          self.highlightRow(parent, true);
        });
        // close event is => infowindowclose
        GEvent.bind(marker, "click", this, function() {
          var infoWindow = marker.openInfoWindowHtml($(parent).find('.mapMarkerHtml').html(), {maxWidth: 250});
        });
        
        $(parent).mouseover(function() {
          self.highlightRow(parent, true);
          if(map.getInfoWindow().getPoint() == point)
            return false;
          marker.openInfoWindowHtml($(parent).find('.mapMarkerHtml').html(), {maxWidth: 250});
        }).mouseout(function(){
          //marker.closeInfoWindow();
          self.highlightRow(parent, false);
        });
      });

      // zoom out and center map
      for (var i=0; i < points.length; i++) {
        bounds.extend(points[i]);
      }
      map.setZoom(map.getBoundsZoomLevel(bounds));
      map.setCenter(bounds.getCenter());
    }
  },
  highlightRow: function(self, is_selected) {
    if(is_selected) {
      $(self).addClass('highlightRow');
    } else {
      $(self).removeClass('highlightRow');
    }
  }
};

var ContactAgent = {
  setup: function() {
    $('#listingDetail #inviteOffer').click(function() {
      var ajax_content = '#TB_ajaxContent';
      $(ajax_content).load(function() {
        var form = '#new_message';
        var setup_ajax_form = function() {
          // need to resetup buttons
          rollover_buttons();
          submit_button(form + ' .submitButton');

          var options = {
            type: 'post',

            beforeSubmit: function() {
              $(ajax_content).html(ajax_loader_centered());
            },
            
            success: function(response) {
              $(ajax_content).html(response);

              if($(form).length > 0) {
                setup_ajax_form();
              } else {
                $('#returnLink').html($('#filters').html());
                var id = $('#contactModal').attr('data-id');
                if(id != '') {
                  $.get('/renter/listings/ajax_contact_actions/' + id, {listing_id: $('#listingDetail #content').attr('data-id')}, function(html){
                    $('#actionsCol .actions').remove();
                    $('#actionsCol').prepend(html);
                  });
                } else {
                  $('#TB_window').unload(function() {
                    refresh_page();
                  });
                }
              }
            }
          };
          $(form).ajaxForm(options);
        };
        setup_ajax_form();
      });
    });
  }
};

var Reviews = {
  setup: function() {
    if($('#reviewPublish').length > 0) {
      this.rating.setup();
      $('#previewReview').click(function() {
        var j_elm = $('#reviewPublish #thanksBoxWide');
        var url = '/renter/reviews/preview';
        if($('.edit_review').length > 0) {
          url = j_elm.attr('action').replace('publish', 'preview');
        }
        j_elm.attr('action', url);
        j_elm.submit();
        return false;
      });
      $('#editReview').click(function() {
        var j_elm = $('#reviewPreview');
        var url = '/renter/reviews/preview';
        if($('.edit_review').length > 0) {
          url = j_elm.attr('action').replace('publish', 'edit');
        }else if($('.new_review').length > 0) {
          url = j_elm.attr('action').replace('publish', 'new');
        }
        j_elm.attr('action', url);
        j_elm.submit();
        return false;
      });
    }      
  },
  rating: {
    setup: function() {
      var self = this;
      // click event
      this.select();
      // set hidden field values
      var hidden_fields = ['overall','honesty','reliability','listings'];
      $.each(hidden_fields, function(i, v) {
        var hf_id = '#review_' + v + '_rating';
        var rating = $(hf_id).val();
        
        if(rating != "") {
          rating = parseInt(rating);
        } else {
          return true;
        }
         
        $(hf_id).siblings('.star-rating').children('li').each(function() {
          var a = $(this).children('a');
          var r = parseInt( a.html() );
          if(r == rating) {
            self.highlight(a);
          }
        });
      });
    },
    select: function() {
      var self = this;
      $('.star-rating li a').click(function() {
        self.highlight(this);
        return false;
      });
    },
    highlight: function(parent) {
      var rating = parseInt($(parent).html());
      
      $(parent).parent('li').siblings('li').each(function() {
        var r = parseInt($(this).children('a').html());
        $(this).removeClass('current-rating');
        if(r <= rating) {
          $(this).addClass('current-rating');
        }
      });
      $(parent).parent('li').addClass('current-rating');
      // add value to hidden field
      $(parent).parent('li').parent('ul').parent('.row').find('input').val(rating);
    }
  }
};

var RenterProfile = {
  setup: function() {
    if($('#renter_signup').length > 0) {
      this.neccessityRating.setup();
      this.signup();
      this.credit_check();
    }
    
    if($('#renter_profile, #preferences').length > 0) {
      this.neccessityRating.setup();
      
      var survey_elm = $('#emailNotificationsSurvery');
      $('#user_notify_by_email_false').click(function() {
        if($(this).is(':checked')) survey_elm.show();
      });
      
      $('#user_notify_by_email_true').click(function() {
        if($(this).is(':checked')) survey_elm.hide();
      });
    } 
  },
  agree_to_terms: function(elm) {
    // have they agreed to the terms?
    if($('#agreeToTerms').attr('checked') == false) {
      alert('You must agree to the Naked Apartments Terms of Service before continuing.');
      return false;
    }
  },
  signup: function() {
    // credit karma link tracking
    $('#creditKarmaAd').click(function() {
      ga_track_pageview('/click/renter-signup-creditkarma');
    })
    
    // once this is added to broker side, need to move to global function
    var other = $('#renter_user_referral_other');
    var dropdown = $('#userReferralOption');
    // setup event
    dropdown.change(function() {
      if($(this).val() == "999") {
        other.show();
      } else {
        other.hide();
      }
    });

    if(dropdown.val() == "999") {
      other.show();
    }

    var after_submit = function(elm) {
        $('.formActions').html(ajax_loader_centered());
    };

//    submit_button('#renterSignupCreditCheck', {
////      before_submit: function() {
////        $('#credit_check_type').val('zip');
////      },
//      after_submit: after_submit
//    });

    submit_button('#renterSignupSelfReport', {
//      before_submit: function() {
//        $('#credit_check_type').val('self');
//      },
      before_submit: this.agree_to_terms,
      after_submit: after_submit
    });
  },
  credit_check: function() {
    // self report
    submit_button('#submitRenterSelfReport', {
      before_submit: this.agree_to_terms,
      after_submit: function(elm) {
        $('.formActions').html(ajax_loader());
      }
    });

    // credit check through ZIP
    submit_button('#submitRenterCreditCheck', {
      before_submit: this.agree_to_terms,
      after_submit: function(elm) {
        $(elm).after(ajax_loader());
        $(elm).hide();
      }
    });
    
    // auto tab
    $('#dob_month, #dob_day, #dob_year').autotab_magic();
    $('#credit_check_ssn_1, #credit_check_ssn_2, #credit_check_ssn_3').autotab_magic();
  },
  neccessityRating: {
    setup: function() {
      var rating_elm = $('#renter_necessity_rating');
      $('#necessityRatingSlider').slider({
        value: rating_elm.val(),
        min: 1,
        max: 10,
        step: 1,
        slide: function(event, ui) {
          rating_elm.val(ui.value);
        }
      });
    }
  }
};

var RenterHomepage = {
  setup: function() {
    $('.modsub ul li').naSimpleTabs();
    
    $('#home .invitedOffer a').click(function() {
      var self = this;
      $('#TB_window').unload(function() {
        if($('#suggestedListings tr').length == 1) {
          refresh_page();
          return false;
        }
        // fade out + remove row
        $(self).parents('tr').fadeOut('fast').remove();
      });
      return false;
    });

    // city move ad
    $('#cityMoveAd').click(function() {
      ga_track_pageview('/out/citymove/');
    });
  }
};

(function($) {
  /**
   * Listing Favorites Buttons
   */
  $.fn.listingFavoriteButtons = function(callback) {
    var sel = this;
    $(sel).children('a').click(function() {
      var elm = this;
      // ajax request
      var listing_id = $(elm).parent('span').attr('data-id');
      var type = ($(elm).attr('href').search('add_') != -1) ? 'add' : 'delete'

      $.getJSON($(elm).attr('href') + '.json', function(data) {
        if(data.success) {
         if(typeof callback == 'function')
          callback(listing_id, type);
        }
      });
      // update button
      if(type == 'add') {
        $(elm).attr('href', $(elm).attr('href').replace('add_', 'delete_')).html('Remove');
        $(elm).parent().addClass('favorited');
        ga_track_pageview('/click/add-favorite/' + listing_id);
      } else {
        $(elm).attr('href', $(elm).attr('href').replace('delete_', 'add_')).html('Favorite');
        $(elm).parent().removeClass('favorited');
      }

      return false;
    });
  };

})(jQuery);


/*
-------------------------------------------------------------------
HELPER FUNCTIONS EXTENDED *****************************************
-------------------------------------------------------------------
*/


/*
-------------------------------------------------------------------
AJAX HELPER FUNCTIONS EXTENDED ************************************
-------------------------------------------------------------------
*/

Ajax = $.extend(Ajax, {
  get_broker_profile: function(id, elm) {
    if($(elm).html() == '') {
      $(elm).html(ajax_loader_centered());

      // ajax request
      $.get('/renter/broker-profile/' + id, {partial:1}, function(html) {
        $(elm).html(html);
      });
    }
  }
});


$(document).ready(function() {
  try {
    SearchNav.setup();
  } catch(e) {}
  SearchListings.setup();
  ContactAgent.setup();
  Reviews.setup();
  RenterProfile.setup();
  RenterHomepage.setup();

  $('#listingDetail .favorite').listingFavoriteButtons();
  $('#listingSERPOuter .favorite').listingFavoriteButtons(function(listing_id, type) {
    if(type == 'delete') {
      $('#listing_' + listing_id + '_row1, #listing_' + listing_id + '_row2').remove();
      if($('#listingSERPTable tbody tr').length == 0)
        refresh_page();
    }
  });
  $('#favoritedListings .favorite').listingFavoriteButtons(function(listing_id, type) {
    if(type == 'delete') {
      $('#listing_favorite_' + listing_id).remove();
      if($('#favoritedListings tbody tr').length == 0)
        refresh_page();
    }
  });
});
