
/**** Broker: Add / Edit Listing *****/
var EditListing = {
  li_id_prefix: '#listing_image_',
  setup: function() {
    var self = this;
    // ignore if not correct page...
    if($('#listingEdit').length == 0)
      return false;
      
    $('.submitListing').click(function() {
      $('.edit_listing').submit();
      return false;
    });
    
    // listing location
    self.location.setup();
    
    // upload image(s)
    this.images.setupEvents();
  },
  images: {
    setupEvents: function() {
      var self = this;
      $('#uploadImages').click(function() {
        $('#new_listing_image').submit();
        return false;
      });

      $('#addImage').click(function() {
        self.addBrowse();
        return false;
      });

      // setup AJAX upload form...
      var options = {
        beforeSubmit:  function() {
          if($('#listing_image_image').val() == "")
            return false;

          $('#imageActions .block').hide();
          $('#imageActions').append(ajax_loader_centered());
        },
        success: function(json) {
          if(json.result == 'success' || json.result == 'partial-success') {
            $.each(json.images, function() {
              self.addImage(this);
            });
            
            // if first image, set to primary
            if($('#listingImages ul li').length > 0 && json.images.length > 0) {
              self.primaryImage(json.images[0].id);
            }
            // remove extra browse fields
            $('.browseFiles').remove();

            if(json.result  == 'partial-success')
              alert(json.error_count + ' image(s) failed to upload. Please try again.');
          } else {
            alert('Error uploading image(s). Please try again.');
          }
          
          $('#imageActions .block').show();
          $('#imageActions div.center').remove();
        },
        dataType:  'json',
        clearForm: true,
        resetForm: true
      };
      // bind form using 'ajaxForm'
      $('#new_listing_image').ajaxForm(options);


      /*** Image Management ***/
      self.imageManagementEvents();
    },
    imageManagementEvents: function() {
      var self = this;
      $('#listingImages .delete').click(function() {
        self.deleteImage( $(this).attr('data-id') );
        return false;
      });
      $('#listingImages .makePrimary').click(function() {
        self.primaryImage( $(this).attr('data-id') );
        return false;
      });
    },
    deleteImage: function(id) {
      // check to make sure they want it deleted
      if(!confirm("Are you sure you want to delete this image?")) {
        return false;
      }
      // check to see if primary image has been deleted...
      if($('#primaryListingImage img').attr('src') == $(EditListing.li_id_prefix + id).attr('data-image-normal'))
        $('#primaryListingImage img').attr('src', $('#primaryListingImage img').attr('data-default-src'))
      // hide from user
      $(EditListing.li_id_prefix + id).remove();
      // send request to server to delete image
      $.get('/broker/listings/delete_image/' + id);
    },
    primaryImage: function(id) {
      var listing_id = $('#listing_image_listing_id').val();
      var image_normal = $(EditListing.li_id_prefix + id).attr('data-image-normal');
      $('#primaryListingImage img').attr('src', image_normal);
      $.get('/broker/listings/primary_image/' + id, {'listing_id': listing_id});
    },
    addImage: function(image) {
      var html = '<li id="listing_image_' + image.id + '" data-image-normal="' + image.normal + '">';
      html += '<div><img src="' + image.thumbnail + '" /></div>';
      html += '<a class="makePrimary" href="#" data-id="' + image.id + '">Make primary</a> <br />';
      html += '<a class="delete" href="#" data-id="' + image.id + '">Delete</a>';
      html += '</li>';
      $('#listingImages ul').append(html);
      // must re-setup events
      this.imageManagementEvents();
    },
    addBrowse: function() {
      var html = '<div class="row browseFiles"><span class="floatLeft">';
      html += $('#firstBrowseFile').html();
      html += '</span><span class="floatLeft padLeft5">'
      html += '<span class="removeBtn"><a href="#">Remove</a></span>';
      html += '</span><div class="clear"></div></div>';
      $('#imageActions').before(html);
      // remove button event
      $('.browseFiles a').unbind('click').click(function() {
        $(this).parents('.browseFiles').remove();
        return false;
      });
    }
  },
  location: {
    setup: function() {
      var self = this;
      var borough_elm = $('#listing_borough_id');
      // todo: must refactor this into code for use site wide...
      borough_elm.change(function() {
        var id = $(this).val();
        self.getNeighborhood(id);
      });
      // if borough was selected, but not neighborhood
      if(borough_elm.val() != '' && $('#listing_neighborhood_id').val() == '') {
        self.getNeighborhood( borough_elm.val() );
      }
    },
    getNeighborhood: function(borough_id) {
      var html = '<option value="">Please select</option>';
      var n_elm = $('#listing_neighborhood_id');
      if(borough_id == '') {
        n_elm.html(html).attr('disabled', true);
        return false;
      }
      Ajax.get_neighborhoods_by_borough_id(borough_id, function(json) {
        $.each(json.neighborhoods, function(i, n) {
          html += '<option value="' + n.neighborhood.id + '">' + n.neighborhood.name + '</option>';
        });
        n_elm.html(html).attr('disabled', false);
      });
    }
  }
};

var BrokerProfile = {
  setup: function() {
    // Brokerage Firm Dropdown   
    this.BrokerageFirmDropDown();
    this.isLandlord();
  },
  isLandlord: function() {    
    // setup event
    $('#broker_is_landlord').change(function() {
      var details_elm = $('#brokerProfileDetails');
      var bio_elm = $('#brokerBioPhoto');
      if($(this).attr('checked')) {
        details_elm.fadeOut();
        bio_elm.fadeOut();
      } else {
        details_elm.fadeIn();
        bio_elm.fadeIn();
      }
    });
  },
  BrokerageFirmDropDown: function() {
    var other = $('#broker_brokerage_firm_other');
    var dropdown = $('#brokerageFirm');
    // setup event
    dropdown.change(function() {
      if($(this).val() == "999") {
        other.show();
      } else {
        other.hide();
      }
    });
    
    if(dropdown.val() == "999") {
      other.show();
    }
  }
};

SearchNav = $.extend(SearchNav, {
  setup: function() {
    var self = this;
    if($('#searchWrapperOuter').length > 0) {
      // Borough Dropdown
      this.boroughDropDown.setup();
      // Neighborhood Dropdown
      this.neighborhoodDropdown.setup();
      // Apartment Size Dropdown
      this.apartmentSizeDropdown.setup();
      // Credit Score Dropdown
      this.creditScoreDropdown.setup();
      // Move Date Range Dropdown
      this.moveDateRangeDropdown.setup();
      // Activity Dropdown
      this.activityDropdown.setup();
      // Activity Rating Dropdown
      this.activityRatingDropdown.setup();
      // Motivation Rating Dropdown
      this.motivationRatingDropdown.setup();

      $('#searchButton').click(function() {
        $('#search').submit();
        return false;      
      });
    }
  },
  creditScoreDropdown: {
    id: '#creditScoreDropdown',
    form_id: '#credit_score',
    setup: function() {
      var self = this;
      SearchNav.dropdown.single.events(self);
      // setup previous state
      SearchNav.dropdown.single.previousState(self);
    }
  },
  moveDateRangeDropdown: {
    id: '#moveDateRangeDropdown',
    form_id: '#md_range',
    setup: function() {
      var self = this;
      SearchNav.dropdown.single.events(self);
      // setup previous state
      SearchNav.dropdown.single.previousState(self);
    }
  },
  activityDropdown: {
    id: '#activityDropDown',
    form_id: '#ua',
    setup: function() {
      var self = this;
      SearchNav.dropdown.single.events(self);
      // setup previous state
      SearchNav.dropdown.single.previousState(self);
    }
  },
  activityRatingDropdown: {
    id: '#activityRatingDropDown',
    form_id: '#arating',
    setup: function() {
      var self = this;
      SearchNav.dropdown.single.events(self);
      // setup previous state
      SearchNav.dropdown.single.previousState(self);
    }
  },
  motivationRatingDropdown: {
    id: '#motivationRatingDropDown',
    form_id: '#mrating',
    setup: function() {
      var self = this;
      SearchNav.dropdown.single.events(self);
      // setup previous state
      SearchNav.dropdown.single.previousState(self);
    }
  }
});

var PurchaseCredits = {
  paymentOptions: {
    setup: function() {
      var self = this;
      // on page load, select value of hidden field
      var payment_option_id = $('#payment_option_id').val();
      self.select(payment_option_id);
      
      // .submitButton not working for IE 6/7, so using .specialButton
      $('.specialButton').unbind('click').click(function() {
        $('#new_billing_information').submit();
        return false;
      });

      $('.offerPaymentOption').click(function() {
        var id = $(this).attr('data-id');
        self.select(id);
        return false;
      });

      // autofill
      $('#user_autofill_selected').click(function() {
        var options = $('#autofillAmounts');
        var save_info = $('#save_information');
        if($(this).is(':checked')) {
          options.show();
          save_info.attr('checked', true).attr('DISABLED', true);
        } else {
          options.hide();
          save_info.attr('checked', false).removeAttr('DISABLED');
        }
      });
    },
    select: function(id) {
      var elm = null;
      // reset
      $('#purchaseBids .block').each(function() {
        $(this).removeClass('highlight');
        $(this).children('img').remove();
        if(id == $(this).children('.offerPaymentOption').attr('data-id')) {
          elm = $(this).children('.offerPaymentOption');
        }
      });
      // select new option
      $(elm).parent('.block').addClass('highlight');
      $(elm).parent('.block').prepend('<img src="/images/icons/bid_check.gif"/>');
      //highlight
      var amount = $(elm).children('.price').html();
      $('#payment_option_id').val(id);
      $('#orderTotal').html(amount);
    }
  }
};


var MyOffers = {
  setup: function() { 
    // offers made popup, found in offer inboxes/serp
    this.offersMade();    
  },   
  offersMade: function() {
    $('.showOffersMadePopup').click(function() {
      var renter_id = $(this).attr('data-id');
      // hide existing popups
      $('.offersMadePopup').fadeOut('fast');
      // add html container for ajax call
      var popup_id = 'offers_made_' + renter_id;
      if($('#' + popup_id).length == 0) {
        $(this).after('<div id="' + popup_id + '" class="offersMadePopup" style="display:none;"></div>');
      }
      var popup_elm = $('#' + popup_id);
      // ajax call for info
      popup_elm.html('<div class="center">' + ajax_loader() + '</div>').fadeIn('fast');
      $.get('/broker/contacts/get_contacts_made/' + renter_id, function(html){
        popup_elm.html(html);
        // setup close button event
        popup_elm.children('.close').click(function() {
          popup_elm.fadeOut('fast');
          return false;
        });
      });
      return false;    
    });    
  }
};

var RenterSearchResults = {
  setup: function() {
    if($('#SERP').length > 0) {
      this.offerPopup();
    }
  },
  offerPopup: function() {
    $('#SERP .showOfferPopup').click(function() {
      // make sure all other popups are closed
      $('#SERP .offerPopup').each(function() {
        $(this).hide();
      });
      $(this).siblings('.offerPopup').fadeIn('fast'); 
      return false;
    });
    $('#SERP .close').click(function() {
      $(this).parent('.offerPopup').fadeOut('fast');
      return false;
    });
  }
};

var Reviews = {
  setup: function() {
    // Request Reviews
    $('#profile .requestReview a').click(function(){
      var elm_id = '#' + $(this).parents('div').attr('id');
      $('#TB_window').unload(function() {
        $(elm_id).fadeOut('fast');
      });
    });

    $('#contactDetails .requestReview a').click(function(){
      var elm = $(this).parents('.reviewPrompt');
      $('#TB_window').unload(function() {
        elm.fadeOut('fast');
      });
    });
  }
};

var Homepage = {
  setup: function() {
    // Request Reviews
    $('#home .requestReview a').click(function(){
      var elm_id = '#' + $(this).parents('tr').attr('id');
      $('#TB_window').unload(function() {
        $(elm_id).fadeOut('fast');
      });
    });
    this.requestReviews.setup();
  },
  requestReviews: {
    setup: function() {
      var self = this;
      // pagination buttons
      $('#home #requestReviews .resultsPagination a').click(function() {
        var url = $(this).attr('href');
        self.getReviewRequests(url);
        return false;
      });
    },
    getReviewRequests: function(url) {
      var self = this;
      var params = Ajax.parse_url_params(url);
      $.get('/broker/dashboard/get_review_requests?' + params, function(data) {
        $('#home #requestReviews').html(data);
        self.setup();
      });
    }  
  }
};

/*
 *  AJAX HELPER FUNCTIONS
 *
*/
$.extend(Ajax, {
  get_renter_profile: function(id, elm) {
    if($(elm).html() == '') {
      $(elm).html('<div class="center">' + ajax_loader() + '</div>');

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


$(document).ready(function() {
  // Setup Events for each page.
  EditListing.setup();
  BrokerProfile.setup();
  SearchNav.setup();
  RenterSearchResults.setup();
  MyOffers.setup();
  Reviews.setup();
  Homepage.setup();
  PurchaseCredits.paymentOptions.setup();
  
  $('.deleteListingsButton').click(function() {
    $('#deleteListings').submit();
    return false;
  });
  
  if($('#broker_signup').length > 0) {
    submit_button('#submitBrokerSignup', {
      after_submit: function(elm) {
        $(elm).after(ajax_loader());
        $(elm).hide();
        $('.cancel').hide();
      }
    });
  }
    
});

