(function(){
  var listingView, overlayView;

  $.fn.rmListingButton = function() {
    return this.each(function() {
      var $el, $span, iconName, $icon, buttonInner, buttonText;
      $el = $(this);
      $el.addClass('rm-vl-bigbtn special-color');
      
      buttonInner = document.createElement("span");
      buttonInner.className = 'rm-vl-bigbtn-inner';
      
      buttonText = document.createElement("span");
      buttonText.className = 'rm-vl-bigbtn-text special-color';
      
      buttonInner.appendChild( buttonText );
      
      iconName = $el.data('icon');
      while ( this.firstChild ) {
        buttonText.appendChild( this.firstChild );
      }
      if (iconName) {
        $el.addClass('rm-vl-bigbtn-icon-left ')
        $icon = $('<span />', {
          'class': 'special rm-vl-icon'
        });
        $icon.addClass('rm-vl-icon-' + iconName);
        $(buttonInner).append($icon);
      }
      $el.append(buttonInner);
    });
  };
  listingView = Backbone.View.extend({
    events: {
      "click [data-overlay]": 'openOverlay'
    },
    initialize: function() {
      this.views = {
        overlay: new overlayView()
      };
      $('.vl-button-group a, [data-role="big-button"]', this.el).rmListingButton();
      return this;
    },
    buildOverlay: function(name, $target) {
      var $overlay = $('.vlOverlayContent', this.views.overlay.el);
      var self = this;
      var builders = {
        '360': function() {
          var $iframe, url;
          $overlay.html("");
          url = "/login_tour.php?tour_id=" + $target.data('tour-id');
          $iframe = $("<iframe />", {
            scrolling: 'auto',
            height: '100%',
            width: '100%',
            border: '0',
            src: url
          });
          $overlay.append($iframe);
          return self;
        },
        'floor plan': function(){
          var $image, path, height, width;
          $overlay.html("");
          path = $target.attr('data-image-path');
          $image = $('<img />', {
            src: path
          });
          $overlay.append($image);
          return self;
        },
        'video': function() {
          $overlay.html("");
          var embed = $target.attr('data-video-embed');
          if (embed) {
            var $div = $("<div />", {
              'class': 'video',
              'html': embed
            });
            $overlay.append($div);
          } else {
            var url = $target.attr('data-video-url');
            popUpWindow('ListVideo', url, 750, 500, 'scrollbars=yes');
            return false;
          }
        },
        'walkscore': function() {
          var lat, lon, url;
          $overlay.html("");
          lat = $target.data('lat');
          lon = $target.data('lon');
          if (lat && lon) {
            url = "/walkscore.php?&w=490&h=387" + "&lat=" + lat + "&lon=" + lon;
            var $iframe = $("<iframe />", {
              scrolling: 'auto',
              height: '100%',
              width: '100%',
              border: '0',
              src: url
            });
            $overlay.append($iframe);
            return self;
          }
          return false;
        }
      }
      if (_.isFunction(builders[name])) {
        return builders[name]();
      }
      $overlay.html(name);
      return this;
    },
    openOverlay: function(event) {
      event.preventDefault();
      $target = $(event.currentTarget);
      overlayTarget = $target.attr('data-overlay');
      if (this.buildOverlay(overlayTarget, $target) !== false) {
        this.views.overlay.open();
      }
      return this;
    }
  });
  overlayView = Backbone.View.extend({
    width: 640,
    height: 480,
    initialize: function() {
      var $listingContainer;
      this.makeOverlay();
      // if the function argument is given to overlay,
      // it is assumed to be the onBeforeLoad event listener
      $listingContainer = $('#listingContainer');
      this.overlay = $(this.el).overlay({
        target: '#vlOverlay',
        mask: {
          color: '#000',
          loadSpeed: 200,
          opacity: 0.5
        },
        close: "a.close",
        closeOnClick: false,
        closeOnEsc: false,
        onClose: function() {
          var overlay = this.getOverlay();
          $('.vlOverlayContent', overlay).html('');
        }
      }).data('overlay');
      return this;
    },
    makeOverlay: function() {
      var $div;
      $div = $('<div />', {
        'class': 'apple_overlay',
        'id': 'vlOverlay'
      });
      $div.html("<a class='close'></a><div class='vlOverlayContent'></div>");
      $div.appendTo('body');
      this.el = $div.get(0);
      return this;
    },
    open: function(){
      this.overlay.load();
      return this;
    }
  });
  new listingView({el:document.getElementById('listingContainer')})

  // Photos
  var slideshowView = Backbone.View.extend({
    activeClass: 'active',
    maxThumbnailWidth: 550,
    events: {
      "mouseover .thumbWrapper": "updatePhoto",
      "mouseenter .listingThumbnails:not(.expanded)": "expandContainer",
      "mouseenter .vl-nav.active": "expandContainer",
      "mouseleave": "hideContainer",
      "click .vl-nav.active": "navigate"
    },
    initialize: function() {
      var self = this;
      this.$fullsize = $('.listingImage', this.el);
      this.$thumbnailsHolder = $('.listingThumbnailsHolder', this.el);
      this.$thumbnails = $('.thumbWrapper', this.el);
      this.$thumbnails.eq(0).addClass(this.activeClass);
      this.selectPhoto(0);
      $(document).ready(function(){
        self.$thumbnails.each(function(){
          var $el, newpath;
          $el = $(this);
          newpath = $el.attr('data-url');
          var img = new Image();
          $(img)
            .load(function () {
              $(this).css('display','none').addClass('thumbnail35');
              $el.append(this);
              $(this).fadeIn(function(){
                $el.removeClass('loading');
              });
            })
            .error(function () {
              $el.hide();
            })
            .attr('src', newpath);
        });
      });
      return this;
    },
    navigate: function(event) {
      var $target, direction;
      $target = $(event.currentTarget);
      direction = $target.data('direction');
      if (direction === 'next') {
        this.selectPhoto(this.position + 1);
      } else {
        this.selectPhoto(this.position - 1);
      }
      return this;
    },
    toggleNavigation: function(direction, state) {
      if (state === undefined) {
        state = false;
      }
      $('.vl-nav[data-direction="'+direction+'"]', this.el).toggleClass(this.activeClass, state);
      return this;
    },
    expandContainer: function(event) {
      var $container, self, $containerSet;
      $container = $('.listingThumbnails', this.el);
      self = this;
      if (this.container_hide_timeout) {
        clearTimeout(this.container_hide_timeout);
      }
      if ($container.hasClass('expanded') === false) {
        if (!this.original_container_height) {
          this.original_container_height = $container.css('height');
        }
        $containerSet = $('.listingThumbnailsSet', this.el);
        this.container_show_delay = setTimeout(function(){
          $container.animate({'height': $containerSet.height() + 10}).addClass('expanded');
        }, 200);
      }
      return this;
    },
    hideContainer: function(event) {
      if (this.container_show_delay) {
        clearTimeout(this.container_show_delay);
      }
      var $container, self;
      $container = $('.listingThumbnails', this.el);
      self = this;
      if ($container.hasClass('expanded')) {
        this.container_hide_timeout = setTimeout(function(){
          $container.animate({'height':  self.original_container_height}).removeClass('expanded');
        }, 350);
      }
      return this;
    },
    updatePhoto: function(event) {
      var $target, index;
      $target = $(event.currentTarget);
      index = this.$thumbnails.index($target);
      this.selectPhoto(index);
      return this;
    },
    selectPhoto: function(index) {
      var selected, newImagePath;
      selected = this.$thumbnails.eq(index);
      if (selected.length > 0) {
        if (index === 0) {
          this.toggleNavigation('previous', false);
        } else {
          this.toggleNavigation('previous', true);
        }
        if ((index + 1) === this.$thumbnails.length) {
          this.toggleNavigation('next', false);
        } else {
          this.toggleNavigation('next', true);
        }
        this.position = index;
        this.$thumbnails
          .removeClass(this.activeClass);
        selected
          .addClass(this.activeClass);
        newImagePath = selected.attr('data-url');
        this.$fullsize.attr('src', newImagePath);
        return this;
      }
    }
  });
  new slideshowView({
    el: document.getElementById('listingSlideshow')
  });
  var loadInlineStreetView = function() {
    var mapCenter, panoramaOptions, streetViewService, id, $el, lat, lng;
    id = 'inlineStreetView';
    $el = $('#'+id);
    lat = $el.data('lat');
    lng = $el.data('lon');
    mapCenter = new google.maps.LatLng(lat, lng);
    panoramaOptions = {
      position: mapCenter,
      pov: {
        zoom: 1,
        heading: 0,
        pitch: 5
      },
      addressControl: false,
      linksControl: false,
      panControl: false,
      zoomControlOptions: {
       style: google.maps.ZoomControlStyle.SMALL
      },
      enableCloseButton: false,
      visible:true
    }
    streetViewService = new google.maps.StreetViewService();
    streetViewService.getPanoramaByLocation(mapCenter, 50, function(data, status) {
      var panorama;
      if (status == 'OK') {
        if (data.links && data.links[0]) {
          panoramaOptions.pano = data.links[0].pano;
        }
        panorama = new google.maps.StreetViewPanorama(document.getElementById(id), panoramaOptions);
        panorama.setVisible(true);
      }
      else {
        $el.parent().hide();
      }
    });
  };
  var loadInlineGoogleMap = function () {
    var mapCenter, mapOptions, id, $el, lat, lng, map;
    id = 'inlineGoogleMap';
    $el = $('#'+id);
    lat = $el.data('lat');
    lng = $el.data('lon');
    if (lat && lng) {
      mapCenter = new google.maps.LatLng(lat, lng);
      mapOptions = {
        center: mapCenter,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        panControl: false,
        zoomControl: true,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        overviewMapControl: false
      }
      map = new google.maps.Map($el.get(0), mapOptions);
      propertyMarker = new google.maps.Marker({
          position: mapCenter,
          map: map,
          icon: '/community-property-search/images/home_single.png'
      });
    } else {
      $el.parent().hide();
    }
  }
  var loadMapViews = function() {
    loadInlineStreetView();
    loadInlineGoogleMap();
  }
  google.load("maps", "3", {"other_params":"sensor=false", "callback": loadMapViews});
  $("#listingsToolTip a[title], .vl-tooltip[title]").tooltip({tipClass: 'listingsToolTip'});
  $('<div />', {id: 'listingPreviewToolTip'})
    .html($('#TEMPLATE_listingPreviewToolTip').html())
    .appendTo('body');
  $(".vl-listing-preview").tooltip({
    position: 'top center',
    tip: '#listingPreviewToolTip',
    delay: 0,
    onBeforeShow: function() {
      var $trigger, title, info, imgPath, $target;
      $trigger = this.getTrigger();
      imgPath = $trigger.find('img').attr('src');
      $target = $('#listingPreviewToolTip');
      ['headline', 'price', 'community', 'bedroom_count', 'bathroom_count', 'floorspace'].forEach(function(param){
        $target.find('.' + param).text($trigger.attr('data-' + param));
      });
      $target.find('img').attr('src', imgPath);
    }
  });
})();

$(function() {
  var busy = false;
  $('a.saveFavorite, a.removeFavorite').click(function () {
    if (busy) {
      return false;
    }
    busy = true;
    var $this = $(this)
      , href = $this.attr('href');

    $('a.saveFavorite, a.removeFavorite').toggle();
    $.post(
      href,
      {output:'ajax'},
      function (data) {
        busy = false;
      },
      'text'
    );
    return false;
  });
});

$(function () {
  $.tools.validator.fn("#viewListingContactForm input, #viewListingContactForm select", function(el, value) {
    var $el = $(el);
    return $el.val() != $el.attr('data-default') ? true : "Please complete this mandatory field";
  });

  $("#viewListingContactForm").validator({
    effect: 'wall', 
    container: '#errors',
    errorInputEvent: null
  }).submit(function (e)  {
    if (!e.isDefaultPrevented()) {
      var $form = $(this)
        , $spinner = $form.siblings('.spinner')
        , $thankyou = $form.siblings('.thank-you')
        , $message = $('textarea', $form);
      $spinner.fadeIn();
      $form.hide();

      if ($message.val() == $message.attr('data-default')) {
        $message.val('');
      }

      $.post(
        '/contact_agent.json',
        $(this).serialize(),
        function (data) {
          if (!$message.val()) {
            $message.val($message.attr('data-default')); 
          }

          $spinner.hide();
          if (data.errorsHtml) {
            $('#errors').replaceWith(data.errorsHtml)
            $form.fadeIn();
            $.scrollTo('#errors'); //form needs to fadein first
          }
          else {
            if ($('select', $form).val().match('Schedule a Showing')) {
              $('span', $thankyou).hide();
              $('span.schedule-a-showing', $thankyou).show();
            }
            $thankyou.fadeIn();
            $.scrollTo('#viewListingContactForm');
          }
        },
        'json'
      );
      $("#errors").hide();
    }
    return false;
  });

  $('#viewListingContactForm input, #viewListingContactForm textarea').focus(function (){
    var $this = $(this)

    if ($this.val() == $this.attr('data-default')) {
      $this.val('');
    }
  }).blur(function () {
    var $this = $(this);
    if (!$this.val()) {
      $this.val($this.attr('data-default'));
    }
  });
});

