/*
 * css and height functions from jCarousel Lite:
 * http://gmarwaha.com/jquery/jcarousellite
 */
function el_css(el, prop) {
    return parseInt($.css(el[0], prop)) || 0;
};
function el_height(el) {
    return el[0].offsetHeight + el_css(el, 'marginTop') + el_css(el, 'marginBottom');
};
function el_width(el) {
    return  el[0].offsetWidth + el_css(el, 'marginLeft') + el_css(el, 'marginRight');
};
$(document).ready(function() {
  // Taken from:
  // http://blog.lawrencepit.com/2008/09/04/unobtrusive-jquery-rails/
  // All non-GET requests will add the authenticity token
  // if not already present in the data packet

  var focused = undefined;
  $('input,select,button').focus(function() {
    focused = $(this);
    $(this).addClass('focused');
  }).blur(function() {
    focused = undefined;
    $(this).removeClass('focused');
  });

  $("body").bind("ajaxSend", function(elm, xhr, s) {
    if (s.type == "GET") return;
    if (s.data && s.data.match(new RegExp("\\b" + window._auth_token_name + "="))) return;
    if (s.data) {
      s.data = s.data + "&";
    } else {
      s.data = "";
      // if there was no data, jQuery didn't set the content-type
      xhr.setRequestHeader("Content-Type", s.contentType);
    }
    s.data = s.data + encodeURIComponent(window._auth_token_name)
                    + "=" + encodeURIComponent(window._auth_token);
  });

  $("a.new-window").bind("click.new-window", function() {
    window.open(this.href);
    return false;
  });

    $("a.trlink").unbind("click.new-window")
        .bind("click.trlink", function() {
            var lnk = this;
            var id = $(this).attr('id');
            if(pageTracker && id) {
                try {
                    pageTracker._trackEvent("trlink", id, this.href);
                } catch(err) {
                    // console.log(err);
                }
            }
            if($(this).hasClass("new-window")) {
                window.open(this.href);
            } else {
                setTimeout(function () {
                    document.location = lnk.href;
                }, 100);
            }
            return false;
        });

  $("div.gallery").each(function() {
    var thumbs = $(this).find(".thumbs a");
    var disp = $(this).find(".display img");
    var spinner = $(this).find(".spinner");

    var galleryBox = $(this).find("div.thumbs");
    var thumbCount = thumbs.length;
    var rowCount = Math.ceil(thumbCount / 2);
    var collapseHeight = 378;
    var galleryHeight = 0;
    if(galleryBox.length > 0) {
      galleryHeight = el_height(galleryBox);// (rowCount * 62) + (rowCount - 1) * 10;
      if(galleryHeight < collapseHeight) {
        galleryHeight = collapseHeight;
      }
      $(galleryBox).css('overflow', 'hidden')
                   .css('height', collapseHeight + 'px')
                   .css('z-index', 5)
                   .css('background', 'white')
                   .hover(function() {
                     $(galleryBox).css('height', galleryHeight + 'px');
                   }, function() {
                     $(galleryBox).css('height', collapseHeight + 'px');
                   });
    }

    var sel_src = disp.attr('src');
    var selected = undefined;
    var cur_idx = -1;
    thumbs.each(function() {
        var src = $(this).attr('href');
        if(src == sel_src) {
          selected = $(this);
        }
    });

    if(selected) {
      selected.addClass("selected");
      cur_idx = thumbs.index(selected);
    }
    var set_selected = function(newsel) {
      var img = new Image();
      spinner.show();
      $(img).load(function() {
        disp.replaceWith(this);
        disp = $(this);
        selected.removeClass('selected');
        selected = newsel.addClass('selected');
        cur_idx = thumbs.index(selected);
        spinner.hide();
      }).attr("src", newsel.attr("href"));
    }

    // handle changing image on mouse hover
    thumbs.bind("mouseenter.gallery", function() {
      var newsel = $(this);
      var timeout = window.setTimeout(function() {
        newsel.unbind("mouseleave.timer");
        set_selected(newsel);
      }, 250);
      newsel.bind("mouseleave.timer", function() {
        window.clearTimeout(timeout);
      });
    });
    thumbs.bind("click.gallery", function() {
      set_selected($(this));
      return false;
    });

    var next_image = function() {
      var idx = cur_idx + 1;
      if(idx >= thumbs.length) idx = 0;
      set_selected($(thumbs.get(idx)));
      return false;
    };
    var prev_image = function() {
      var idx = cur_idx - 1;
      if(idx < 0) idx = thumbs.length - 1;
      set_selected($(thumbs.get(idx)));
      return false;
    };
    $(this).find("a.next_photo").click(next_image);
    $(this).find("a.prev_photo").click(prev_image);
    var handle_key = function(e){
      if(focused == undefined) {
        if(!e.ctrlKey && !e.shiftKey && !e.altKey &&
          !e.metaKey && !e.altGraphKey) {
          switch (e.keyCode) {
          case 37: prev_image(); break;
          case 39: next_image(); break;
          }
        }
      }
    };

    if ($.browser.mozilla) {
      $(document).keypress(handle_key);
    } else {
      $(document).keydown(handle_key);
    }

  });

  setupInteractiveForm();

  $("input.defaultText").focus(function(srcc) {
      if ($(this).val() == $(this)[0].title)
      {
          $(this).removeClass("defaultTextActive");
          $(this).val("");
      }
  }).blur(function() {
      if ($(this).val() == "")
      {
          $(this).addClass("defaultTextActive");
          $(this).val($(this)[0].title);
      }
  }).parents("form").submit(function() {
    $(this).find(".defaultText").each(function(i) {
      if ($(this).val() == $(this)[0].title)
      {
          $(this).val("");
      }
    });
    return true;
  }).end().blur();

  $("form a.selector").click(function(event) {
    event.preventDefault();
    target = $($(this).attr("href"));
    $(this).parent().slideUp("normal", function() {
      target.slideDown();
    });
  });

  /* remove the flash after 10s */
  window.setTimeout(function() {
    $(".notice").hide("slow");
  }, 10000);

  ajaxifyComments();
  ajaxifyRatings();
  setupAjaxDialog();

  $('a.disclosure').each(function() {
    var link = $(this);
    var title = link.html();
    var id = link.attr('href');
    var target = $(id);

    link.toggleClass('closed');
    var toggle_disclosure = function () {
      if(link.hasClass('closed')) {
        target.show();
        link.html("Hide " + title);
        link.removeClass('closed');
        return 1;
      } else {
        target.hide();
        link.html("Show " + title);
        link.addClass('closed');
        return 0;
      }
    };
    toggle_disclosure();

    link.click(function() {
      if(toggle_disclosure()) {
        if(pageTracker != undefined) {
          pageTracker._trackEvent("disclosure", "open", id, 0);
        }
      } else {
        if(pageTracker != undefined) {
          pageTracker._trackEvent("disclosure", "close", id, 0);
        }
      }
      return false;
    });
  });

  $("div.bubble").each(function() {
    var bubble = $(this);
    var parent = bubble.parent();
    parent.hover(function() {
      bubble.show();
    }, function() {
      bubble.hide();
    });
  });

  $("form.validatedForm").each(function() {
    $(this).validate({
      errorElement: 'p',
      errorPlacement: function(error, element) {
        element.before(error);
      }
    });
  });


  $('form.trackedForm').submit(function() {
    var form = $(this);
    var id_spec = form.attr('id');
    if(form.hasClass("validatedForm")) {
      if(!form.valid()) {
        return false;
      }
    }
    if(pageTracker != undefined) {
      pageTracker._trackPageview("/form/" + id_spec + "/submit");
      pageTracker._trackEvent('form', 'submit', id_spec, 0);
    }
  });

  if($('body').hasClass('home')) {
    // Track clicks of home page featured property links
    var home_links = $('body.home .list-info h3 a');
    for(var i = 0; i < home_links.size(); i++) {
      var elt = home_links.eq(i);
      elt.click(function() {
        if(pageTracker != undefined) {
          pageTracker._trackEvent('FeaturedProperty', 'home', 'index_' + i, 0);
        }
        return true;
      });
    }
  }

  // notify google analytics of tracked ids on the page
  if(pageTracker != undefined) {
    $('.track_id').each(function() {
      var id = $(this).attr('id');
      if(id) {
        pageTracker._trackPageview("/tracked_id/" + id);
      }
    });
    if($('#admin_comments').length > 0) {
      pageTracker._setVar('admin_user');
    }
  }
  $('#flash_popup').dialog({
    autoOpen: true,
    buttons: { "Ok": function() { $(this).dialog("close"); }},
    closeOnEscape: true,
    modal: true,
    resizable: false,
    draggable: false
  });
  $('#validationErrs')
    .wrapInner('<div class="inner"/>')
    .prepend('<a href="#">Toggle Vis</a>')
    .find("a")
      .toggle(function() {
          $('#validationErrs .inner').hide();
        },
        function() {
          $('#validationErrs .inner').show();
        }
      );
});

setupInteractiveForm = function() {
  $("form#side_search_form").each(function() {
    var select_tag = $("<select name='add_new' class='add-criteria'><option value=''>Add search criteria...</option></select>");

    $(this)
      .children("fieldset").each(function() {
        var legend = $(this).find("legend");
        var title = legend.attr('title');
        if(title == null) {
          title = legend.html();
        }
        var fixed = $(this).hasClass('fixed') || $(this).hasClass('buttons');
        if(!fixed) {
          var selected = $(this).hasClass('selected');
          var current = $(this);
          var option_tag = $('<option>' + title + '</option>');
          option_tag.data('tag-match', current);
          var removeFun = function() {
            current
              .hide()
              .find(':input').each(function() {
                switch($(this).attr("type")) {
                  case "hidden":
                    break;
                  case "checkbox":
                    $(this).attr("checked", false)
                    break;
                  default:
                    $(this).data('old-value', $(this).val());
                    $(this).val("");
                }
              });
            option_tag.enable();
            return false;
          };
          var rem_link = $("<a href=\"#\" class=\"srm\">(remove)</a>").click(removeFun);

          $(this).prepend(rem_link);
          select_tag.append(option_tag);
          if(selected) {
            option_tag.disable();
          } else {
            option_tag.enable();
            removeFun();
          }
        }
      })
    .end()
    .append(select_tag);
    select_tag.change(function(evt) {
      var selected = $(this).children('option:selected');
      var current = selected.data('tag-match');
      if(current) {
        current
          .show()
          .find(':input').each(function() {
            switch($(this).attr("type")) {
              case "hidden":
                break;
              case "checkbox":
                $(this).attr('checked', true);
                break;
              default:
                var val = $(this).data('old-value');
                if(val) {
                  $(this).val(val);
                }
            }
          });
        selected.disable().attr('selected', false);
        $(this).children(':first').attr('selected', true);
      }
    });
  });
};
function setupAjaxDialog() {
  $(".ajax_dialog").each(function() {
    var d = $(this);
    var id = d.attr("id");
    var button_spec = "." + id + "_button";
    var width = d.width();
    var buttons = new Object();
    var form = d.find('form:first');
    if(form.length > 0) {
      var submit = form.find('input[type="submit"]'); //.hide();
      var submit_str = "Submit";
      if(submit.length > 0) {
        submit_str = submit.val();
      } else {
        submit = form.find('button[type="submit"]');
        submit_str = submit.html();
      }
      submit.hide();
      var validated = form.hasClass("validatedForm");
      var standardSubmit = form.hasClass('standardSubmit');
      var submit_fun = function() {
        if(validated) {
          if(form.valid()) {
          } else {
            return false;
          }
        }
        d.find(".error").remove();
        if(pageTracker != undefined) {
          pageTracker._trackPageview("/dialog/" + id + "/submit");
          // pageTracker._trackEvent('dialog', 'submit', id, 0);
        }
        if(standardSubmit) {
          form.submit();
          d.dialog('close');
        } else {
          var values = form.serialize();
          $.post(form.attr('action'),
            values, function(data, textStatus) {
              if(data.redirect) {
                window.location = data.redirect;
                return false;
              }
              if(data.reload) {
                window.location.reload();
                return false;
              }
              if(data.success) {
                d.dialog('close');
                if(data.notice) {
                  $("#flashcontainer").html(
                    "<div id=\"flash_notice\" class=\"flash notice\">"
                    + data.notice
                    + "</div>"
                  );
                  $("#flash_notice").show();
                  /* remove the flash after 5s */
                  window.setTimeout(function() {
                    $(".notice").hide("slow");
                  }, 5000);
                }
                if(data.iframe) {
                  $("body").append(
                    "<iframe src=\"" + data.iframe + "\" "
                    + "height=\"1\" width=\"1\" frameborder=\"0\" "
                    + "allowtransparency=\"true\" scrolling=\"no\" "
                    + "style=\"visibility:hidden;z-index:9999;position:absolute;top:0;left:0;\""
                    + "></iframe>"
                  );
                }
              } else {
                if(data.error) {
                  // overall error message
                  d.prepend("<div class=\"error\">" + data.error + "</div>");
                }
                if(data.errors) {
                  if(!data.error) {
                    d.prepend("<div class=\"error\">We were unable to process your request. Please correct the errors below and try again.</div>");
                  }
                  var errors = data.errors
                  for(var fld in errors) {
                    if(errors.hasOwnProperty(fld)) {
                      $("#" + fld).after(
                        "<div class=\"error\">" + errors[fld] + "</div>"
                      );
                    }
                  }
                }
              }
            }, "json");
        }
        return false;
      };
      buttons[submit_str] = submit_fun;
      buttons['Cancel'] = function() {
        if(pageTracker != undefined) {
          pageTracker._trackEvent('dialog', 'cancel', id, 0);
        }
        d.dialog('close');
      };
    } else {
      buttons["Close"] = function() {
        if(pageTracker != undefined) {
          pageTracker._trackEvent('dialog', 'close', id, 0);
        }
        d.dialog('close');
      };
    }
    d.dialog({
      modal: false,
      autoOpen: false,
      width: width * 1.1,
      resizable: false,
      draggable: false,
      buttons: buttons,
      beforeclose: function(event, ui) {
        // resign input focus
        d.children().blur();
        true;
      },
      open: function(event, ui) {
        pageTracker._trackPageview("/dialog/" + id + "/open");
        d.find("input:first").focus();
      }
    });
    var button_id_field = $('<input type="hidden" name="button_id" value=""/>');
    form.append(button_id_field);
    $(button_spec).click(function() {
      $('.ajax_dialog').dialog('close');
      var button_id = $(this).attr("id");
      if(button_id) {
        if(pageTracker) {
          pageTracker._setCustomVar(2, "ButtonId", button_id, 3);
        }
        button_id_field.val(button_id);
      }
      d.dialog('open');
      if($.browser.msie) {
        var dialogWidget = d.dialog('widget');
        var dialogTop = dialogWidget.offset().top;
        var dialogHeight = el_height(dialogWidget);
        var windowHeight = $(window).height();
        var scrollOffset = (dialogTop + (dialogHeight/2)) - (windowHeight/2);
        if(scrollOffset < 0) {
          scrollOffset = 0;
        }
        window.scrollTo(0, scrollOffset);
      }
      return false;
    });
  });
};

function addListingMarkers(map, listings, highlight_id, icons) {
  var markers = [];
  for(var i = 0, len = listings.length; i < len; i++) {
    var mkr = buildListingMarker(map, listings[i], highlight_id, icons);
    map.addOverlay(mkr);
  }
  return markers;
}

function buildListingMarker(map, listing, highlight_id, icons) {
  var ltype = listing.property_type.toLowerCase();
  if(listing.id == highlight_id) {
    ltype = "highlight";
  }
  var icon = icons[ltype];
  var position = new GLatLng(listing.latitude, listing.longitude);
  var marker = new GMarker(position, {icon: icon});

  if(listing.description) {
    GEvent.addListener(marker, 'click', function() {
      marker.openInfoWindowHtml(listing.description, {maxWidth: 400});
    });
  }
  return marker;
}

createMap = function(listingMarkers, bounds, highlight_id, interactive) {
  var icons = new Object();

  var protoIcon = new GIcon(G_DEFAULT_ICON);

  protoIcon.iconSize = new GSize(22, 20);
  protoIcon.shadowSize = new GSize(0, 0);
  protoIcon.shadow = null;
  protoIcon.iconAnchor = new GPoint(11, 10);
  protoIcon.infoWindowAnchor = new GPoint(11, 1);
  protoIcon.printShadow = null;

  var imageMaps = {
    'home': [
      4,3, 4,11, 2,11, 4,17, 11,17, 19,11, 16,11, 16,3, 4,3
    ],
    'condo': [
      5,1, 5,18, 16,18, 16,1, 5,1
    ],
    'multi-family': [
      4,1, 4,16, 3,16, 7,19, 8,19, 12,16, 16,16, 18,14, 17,14, 17,1, 4,1
    ],
    'commercial': [
      4,1, 4,8, 6,11, 7,17, 11,19, 14,17, 15,11, 17,7, 17,1, 4,1
    ],
    'land': [
      1,1, 1,5, 4,6, 4,10, 2,12, 2,16, 6,18, 10,15, 9,12, 6,10, 6,7, 20,4, 20,1, 1,1
    ],
    'lot': [
      1,4, 5,9, 9,9, 11,15, 18,16, 20,8, 16,4, 1,4
    ],
    'rental': [
      6,2, 4,8, 4,11, 5,18, 16,18, 17,11, 17,8, 15,2, 6,2
    ]
  };
  var propTypes = ['home', 'condo', 'multi-family', 'commercial', 'land', 'lot', 'rental'];
  for(var pti = 0; pti < propTypes.length; pti += 1) {
    var pt = propTypes[pti];
    var icon = new GIcon(protoIcon);
    icon.image = "/images/icons/" + pt + "_icon_sm.png";
    icon.printImage = "/images/icons/" + pt + "_icon_sm.gif";
    icon.mozPrintImage = "/images/icons/" + pt + "_icon_sm_moz.gif";
    icon.transparent = "/images/icons/" + pt + "_icon_shape.png";
    icon.imageMap = imageMaps[pt];
    icons[pt] = icon;
  }
  icons['highlight'] = new GIcon(protoIcon);
  icons['highlight'].image = "/images/pins/hilight_pin.png";
  icons['highlight'].printImage = "/images/pins/hilight_pin_print.gif";

  var map = new GMap2(document.getElementById("map"));

  var ui = map.getDefaultUI();
  ui.zoom.scrollwheel = false;
  map.setUI(ui);
  var zoom = map.getBoundsZoomLevel(bounds);
  if(zoom > 14) zoom = 14;
  map.setCenter(bounds.getCenter(), zoom);

  var markers = addListingMarkers(map, listingMarkers, highlight_id, icons);
};

showStreetViewIfAvailable = function(lat, lng) {
  var svll = new GLatLng(lat, lng);

  var svc = new GStreetviewClient();

  var panoOptions = {
    latlng: svll
  };

  svc.getNearestPanoramaLatLng(svll, function(ll) {
    if(ll) {
      $("#streetview").show();
      try {
        var pano = new GStreetviewPanorama(
          document.getElementById("streetview"),
          panoOptions);
        GEvent.addListener(pano, "error", function(errorCode) {
          $("#streetview").hide();
          pano.remove();
        });
      } catch (e) {
        $("#streetview").hide();
      }
    }
  });
};

ajaxifyComments = function() {
  var container = $("#comment-form");
  container.prepend("<div class=\"ui-state-error errors\"></div>");
  container.children(".errors").hide();
  var form = container.children("form");

  form.submit(function() {
    var values = $(this).serialize();

    target_url = $(this).attr("action") + ".json";
    $.post(target_url, values, function(data, textStatus) {
      if(data.success) {
        container.children(".errors").hide();
        new_comment = $(data.html);
        $("#comment-container").append(new_comment);
        container.find("form #comment_body").val("");
      } else {
        container.children(".errors").html(data.error).show();
      }
      return false;
    }, "json");
    return false;
  });
};

ajaxifyRatings = function () {
  var clickHandler = function() {
    var container = $(this).parent();
    var url = $(this).attr("href") + ".json";
    var link = $(this);
    container.html("<img src=\"/images/thumb-spinner.gif\" width=\"36\" height=\"36\" alt=\"spinner\"/>");
    $.getJSON(url, "", function (data, textStatus) {
      if(data.success) {
        container.html(data.html);
        switch(data.rating) {
        case -1:
          container.find('a.thumbs_dn').effect("pulsate", { times:2 }, function() {
            container.parents('li.listing').slideUp();
          });
          break;
        case 1:
          container.find('a.thumbs_up').effect("pulsate", { times:2 });
          break;
        default:
          break;
        }
      }
      container.find('a').click(clickHandler);
      if(data.notice) {
        notice = $(
          "<div title=\"Notice\">"
            + data.notice
            + "</div>"
        );
        notice.dialog({
          bgiframe: true,
          modal: true,
          buttons: {
            Ok: function() {
              $(this).dialog('close');
            }
          }
        });
        /* remove the flash after 5s */
        window.setTimeout(function() {
          $(".notice").hide("slow");
        }, 5000);
      }
    });
    return false;
  };
  $('.rating-controls a').click(clickHandler);
};
