//==============================================================================
//== REQUIRED METHODS, part of streeteasy_required.js ==========================
//==============================================================================
//-- Search field message clearing and restoring -------------------------------
function ClearOnFocus(obj) {
  if (obj.preFocusValue == null) {
    obj.preFocusValue = obj.value
    obj.value = ""
  }
}

function RestoreOnBlur(obj) {
  if (obj.value == "") {
    obj.value = obj.preFocusValue
    obj.preFocusValue = null
  }
}

//-- Help Tooltips -------------------------------------------------------------
var ActiveHelpTip = null

function ActivateHelpTip(event, help_id, trigger_id) {
  var trigger = $(trigger_id)
  var help = $(help_id)

  if ((ActiveHelpTip != null) && (ActiveHelpTip != help)) {
    ActiveHelpTip.style.visibility = 'hidden'
  }
  
  if (Element.getStyle(help, "visibility") == "hidden") {
    var help_width = parseInt(Element.getStyle(help, "width"))
    var window_width = window.innerWidth || document.body.scrollWidth
    var trigger_coords = Position.cumulativeOffset(trigger)
    var container_coords = Position.cumulativeOffset(help.offsetParent)
    
    //alert("Trigger: " + trigger_coords + " parent: " + container_coords)
    style = {}
    style.visibility = "visible"
    if (trigger_coords[0] > (window_width - help_width - 50)) { // Right aligned
      style.top = (trigger_coords[1] - container_coords[1]) + "px"
      style.left = (trigger_coords[0] - container_coords[0] - help_width + trigger.offsetWidth) + "px"
      help.className = "help_tip popup_right_aligned"
    }
    else { // Left aligned
      style.top = (trigger_coords[1] - container_coords[1]) + "px"
      style.left = (trigger_coords[0] - container_coords[0]) + "px"
      help.className = "help_tip popup_left_aligned"
    }

    Element.setStyle(help, style);
    ActiveHelpTip = help
  }
  else {
    help.style.visibility = 'hidden'
    ActiveHelpTip = null
  }
}

//==============================================================================
//== END OF REQUIRED METHODS ===================================================
//==============================================================================


function ajaxLoading(form) {
  submits = Form.getInputs(form, 'submit')
  for (var i = 0; i < submits.length; i++) {
    submits[i].disabled = true
  }   
}

function ajaxComplete(form, success) {         
  elements = Form.getElements(form)
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i]
    switch(element.tagName.toLowerCase()) {
      case "input":
        if (element.type.toLowerCase() == 'submit') {
          element.disabled = false
        }
        else if (element.type.toLowerCase() == 'text') {
          if (success) element.value = ""
        }
        break
      case "textarea":
        if (success) element.value = ""
        break
    }       
  }
}

Array.prototype.contains = function(object) {
  for(var i = 0; i < this.length; i++) {
    if (object == this[i]) return true
  }

  return false
}  

function blindToggle(element) {
  element = $(element)
  
  if (element.style.display == 'none')
    Effect.BlindDown(element)
  else
    Effect.BlindUp(element)
}

function toggleComment(comment_id) {
  comment = $("comment_inner_" + comment_id)
  link_element = $("show_link_" + comment_id)
  ignore_verb_element = $("ignore_verb_" + comment_id)

  if (comment.style.display == 'none') {
    Effect.BlindDown(comment)
    link_element.update("Click here to hide it")
    ignore_verb_element.update("Revealing")
  } else {
    Effect.BlindUp(comment)
    link_element.update("Click here to reveal it")
    ignore_verb_element.update("Ignoring")
  }
}
function submitAndDisable(button, message) {
  message = message || "Processing..."
  button.disabled = true
  button.value = message
  button.form.submit();
}

//-- Talk ----------------------------------------------------------------------
// Don't use any prototype functions in here because it is also used on the frontpage!

function toggleComments(id, linkElement) {
  if (linkElement) {
    if (/Expand/.test(linkElement.innerHTML)) linkElement.innerHTML = linkElement.innerHTML.replace(/Expand/, "Collapse")
    else linkElement.innerHTML = linkElement.innerHTML.replace(/Collapse/, "Expand")
  }

  var element = document.getElementById(id)
  element.style.display = element.style.display != 'block' ? 'block' : 'none'
}

//-- Email Obfuscating ---------------------------------------------------------
// Unobfuscates e-mail addresses and writes out the link
function linkToEmail(obfuscatedAddress, title) {
  var letterArray = obfuscatedAddress.split("-").reverse()
  var address = ""

  for (var i = 0; i < letterArray.length; i++) {
    address += String.fromCharCode(letterArray[i])
  }
  document.write("<a href='mailto:" + address + "'>" + (title || address) + "</a>")
}

//-- Colorize ------------------------------------------------------------------
if (window.Effect) {
  Effect.Colorize = Class.create();
  Object.extend(Object.extend(Effect.Colorize.prototype, Effect.Base.prototype), {
    initialize: function(element) {
      var options = Object.extend({ restore: true }, arguments[1] || {});
    
      this.element = $(element);
      this.start(options);
    },
    setup: function() {
      // Prevent executing on elements not in the layout flow
      if(Element.getStyle(this.element, 'display')=='none') { this.cancel(); return; }

      if(!this.options.endcolor)
        this.options.endcolor = Element.getStyle(this.element, 'color').parseColor('#ffffff');
      if(!this.options.startcolor)
        this.options.startcolor = Element.getStyle(this.element, 'color').parseColor('#000000');
      if(!this.options.restorecolor)
        this.options.restorecolor = Element.getStyle(this.element, 'color');
      // init color calculations
      this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
      this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
    },
    update: function(position) {
      Element.setStyle(this.element,{color: $R(0,2).inject('#',function(m,v,i){
        return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
    },
    finish: function() {
      if(this.options.restore ) {
        Element.setStyle(this.element, Object.extend(this.oldStyle, {
          color: this.options.restorecolor
        }));
      }
    }
  });
}

function ShowHiddenInput(prefix, id) {   //  editLabel(prefix, id) {
  var displayElement = $(prefix + '_' + id)
  var editElement = $(prefix + '_edit_' + id)
  var inputElement = $(prefix + '_input_' + id)

  Element.hide(displayElement)
  Element.show(editElement)
  inputElement.focus()
  Event.observe(inputElement, 'keydown', function(event) {
    if (event.keyCode == 27) {
      HideHiddenInput(prefix, id)
    }
  }, true);
}

function HideHiddenInput(prefix, id) {
  var displayElement = $(prefix + '_' + id)
  var editElement = $(prefix + '_edit_' + id)
  var inputElement = $(prefix + '_input_' + id)

  inputElement.blur()
  Element.show(displayElement)
  Element.hide(editElement)  
}

function HideProblematicElements() {
  selects = document.getElementsByTagName("select");
  for (i = 0; i != selects.length; i++) {
    if (selects[i].className == "do_not_hide") {
    }
    else {
      selects[i].originalVisibility = selects[i].style.visibility;
      selects[i].style.visibility = "hidden";
    }
  }
}

function RestoreProblematicElements() {
  try {
    selects = document.getElementsByTagName("select");
    for (i = 0; i != selects.length; i++) {
      if (selects[i].className == "do_not_hide") {
      }
      else {
        selects[i].style.visibility = selects[i].originalVisibility;
      }
    }
  }
  catch(e) {
    // Sometimes this fails in IE
  }
}

function ShowDialog(width) {
  var dialogContainer = $('dialog_container')
  var dialogBackground = $('dialog_background')
  var dialogBox = $('dialog_box')
  var dialogContent = $('dialog_content')

  var dialogWidth = width ? width : 400
  
  dialogBackground.style.height = Element.getDimensions(document.body).height  + "px"
  dialogBox.style.width = dialogWidth + "px"
  dialogBox.style.top =  (((document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop) + 100) + "px"
  dialogBox.style.left = ((Element.getDimensions(document.body).width - dialogWidth) / 2) + "px"
  
  // Close Events
  dialogBackground.onclick = function() {HideDialog()}

  HideProblematicElements()
  Element.show(dialogContainer)
}

function ShowDialogURL(url, width) {
  $('dialog_content').innerHTML = "<div style=\'text-align: center; padding: 20px\'><img src=/images/misc/loading.gif /></div>"
  ShowDialog()
  
  new Ajax.Updater('dialog_content', url, {
    asynchronous:true, 
    evalScripts:true
  }); 
}

function ShowDialogHTML(html, width) {
  $('dialog_content').innerHTML = html
  ShowDialog(width)
}

function ShowDialogDOM(id) {
  $('dialog_content').innerHTML = $(id).innerHTML
  ShowDialog()
}

function HideDialog() {
  Element.hide('dialog_container')
  RestoreProblematicElements()
  window.setTimeout(function() {$('dialog_content').innerHTML = ""}, 0)
}

function LoadingOverlay(id) {
  var target = $(id)
  var positioning = ""
  positioning += "position: absolute; "
  positioning += "top: " + target.offsetTop + "px; "
  positioning += "left: " + target.offsetLeft + "px; "
  positioning += "width: " + target.offsetWidth + "px; "
  positioning += "height: " + target.offsetHeight + "px; "
  
  var html = ""
  html += "<div style=\'"
  html += positioning
  html += "background-color: black; "
  html += "opacity: .30; filter:alpha(opacity=30); "
  html += "z-index: 5000; "
  html += "\'>&nbsp;</div>"

  html += "<div style=\'"
  html += positioning
  html += "padding-top: " + ((target.offsetHeight / 2) - 15) + "px; "
  html += "text-align: center; "
  html += "z-index: 5001; "
  html += "\'><img src=/images/misc/loading.gif /></div>"

  var div = document.createElement("div")
  div.innerHTML = html
  target.appendChild(div)
}

//==============================================================================
// EditableElementWatcher class for doing Flickr/Ajax.InPlaceEditor-like in-
// place editing
//==============================================================================

var EditableElementWatcher = Class.create()
EditableElementWatcher.prototype = {
  initialize: function(prefix, id) {
    this.prefix = prefix
    this.id = id
    this.element = $(prefix + '_' + id)
    
    this.onclickListener    = this.showAlert.bindAsEventListener(this)
    this.mouseoverListener  = this.highlightBackground.bindAsEventListener(this)
    this.mouseoutListener   = this.unhighlightBackground.bindAsEventListener(this)
    
    Event.observe(this.element, 'click', this.onclickListener)
    Event.observe(this.element, 'mouseover', this.mouseoverListener)
    Event.observe(this.element, 'mouseout', this.mouseoutListener)
  },

  showAlert: function(evt) {
    ShowHiddenInput(this.prefix, this.id)
  },
  
  highlightBackground: function(evt) {
    this.element.style.backgroundColor = Ajax.InPlaceEditor.defaultHighlightColor
  },
  
  unhighlightBackground: function(evt) {
    this.element.style.backgroundColor = "#FFFFFF"
  }
};

// These functions are called from compacts so they are needed everywhere
function clearMouseoverListings() {
  if (!window.googleMaps || !googleMaps.map) return
  
  var markersLayer = googleMaps.map._layers["markers"]
  if (!markersLayer) return
  
  for(var i = 0; i < markersLayer.length; i++) {
    var listing = markersLayer[i]
    listing.setImage(listing.getIcon().image)
  }
}

function mouseoverLayer(id) {
  if (!window.googleMaps || !googleMaps.map) return
  clearMouseoverListings()
  
  var layer = googleMaps.map._layers[id]
  if (!layer) return
  for(var i = 0; i < layer.length; i++) {
    var listing = layer[i]
    image = listing.getIcon().mouseover_image
    if(image) {
      listing.setImage(image)
    }
  }
}

function mouseoverMarker(id) {
  if (!window.googleMaps || !googleMaps.map) return
  clearMouseoverListings()
  
  var marker = googleMaps.map._overlays[id]
  if (!marker) return
  image = marker.getIcon().mouseover_image
  if (image) marker.setImage(image)
}

function toggle_anonymity(type) {
  $('from_address_expose').toggle();
  $('from_address_anon').toggle(); 
}

// These are for fancy pagination stuff
function observe_pagination_jumping() {
  $$('.pagination_jump').each(function(element) {
    Event.observe(element, 'keypress', function(event) {
      if(event.keyCode == Event.KEY_RETURN) {
        page_number = element.value.gsub(',','');
        
        if(page_number.match(/[^\d]/)) {
          alert("You can only jump to a page number!");
        } else {
          document.location = jump_url_for_page(page_number);
        }
      }
    })
  })
}

function jump_url_for_page(page_number) {
  url = document.location.href
  
  if(url.match(/page=\d+/)) {
    url = url.gsub(/page=\d+/, 'page=' + page_number)
  } else if(url.match(/\?.*/)) {
    url = url.gsub(/\?/,'?page=' + page_number + '&')
  } else {
    url = url + '?page=' + page_number
  }
  
  return url
}

// =============================================================================
// Copy to Clipboard                                                         
// From http://www.jeffothy.com/weblog/clipboard-copy/ 
// =============================================================================
function SendToClipboard(data) {
  var flashcopier = 'flashcopier';
  if(!document.getElementById(flashcopier)) {
    var divholder = document.createElement('div');
    divholder.id = flashcopier;
    document.body.appendChild(divholder);
  }
  document.getElementById(flashcopier).innerHTML = '';
  var divinfo = '<embed src="/flash/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(data)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
  document.getElementById(flashcopier).innerHTML = divinfo;
}


//==============================================================================
// Shamelessly jacked this code from the Scriptaculous wiki -JD
//   http://wiki.script.aculo.us/scriptaculous/show/Cookie
//==============================================================================
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  }
};

function updateAreaId(element, selectedArea) {
  $('listing_area_id').value = selectedArea.id;
}

function updateUserId(element, selectedUser) {
  $('contact_user_id').value = selectedUser.id;
}

function highlightRow(element) {
  $$('.highlightable_row').each(function(el) { $(el).removeClassName('highlighted_row')})
  $(element).addClassName('highlighted_row')
}

//== ADMIN RELATED ====
function unlockAttribute(url, attribute, icon) {
  new Ajax.Request(url, {
    failure : "alert('Error unlocking attribute " + attribute + "')"
  })
  
  Element.remove(icon)
}

function addField(parent, html) {
  var element = document.createElement("div")
  element.innerHTML = html

  $(parent).appendChild(element)
}

function swapDateFields(linkEl) {
  linkEl = typeof(linkEl) != 'undefined' ? linkEl : "date_field_link";

  // range is hidden, show it and hide the 'since'
  if ( Element.getStyle("date_range", "display") == "none" ) {
    $("dated_since").value = "";
    $("dated_since").hide();
    $("date_range").show();
    if ( $(linkEl) ) $(linkEl).update("(search period)")

  // since is hidden, show it and hide the 'range'
  } else {
    $("dated_since").value = "<60";

    $("date_range").hide();
    $("dated_since").show();

    if ( $(linkEl) ) $(linkEl).update("(search range)")
  }

}

function ClearMouseEvents(element) {
  element = $(element)
  if (element.onclick) {
    element.onclick = null;
  }

  for(var i = 0; i < element.childNodes.length; i++) {
    ClearMouseEvents(element.childNodes[i]); 
  }
}


function buildMessageUrl(message_id) {
  url = document.location.href
  show_url = url.replace(/messages(.*?)$/, "messages/show/" + message_id)
  return show_url
}

function FacebookSharerPopup(url) {
  window.open(url,'sharer','toolbar=0,status=0,width=626,height=436');
  return false;
}
