var GhostText = function () {}

GhostText.prototype.init = function(input) {
  var el = $(input)
  GhostText.prototype.blur.call(el)
  
  el.focus(GhostText.prototype.focus)
  el.blur(GhostText.prototype.blur)
  
  // pre-submit scraper
  el.parents('form').submit(function(evt) {
    if(el.is('.ghosttext')) {
      el.val('')
      return true;
    }
  })
}

// scope is input element
GhostText.prototype.focus = function(evt) {
  var input = $(this)
  if(input.is('.ghosttext')) {
    input.val('')
    input.toggleClass('ghosttext')
  }
}

// scope is input element
GhostText.prototype.blur = function(evt) {
  var input = $(this)
  // show ghost text if input is empty
  if(jQuery.trim(input.val()).length == 0) {
    var name = "virtual_"+input.attr('name')
    
    // create a virtual input box in place of the password text
    // otherwise password title will show up as '*****', which is confusing
    if(input.attr('type') == 'password') {
      
      // if virtual password element doesn't already exist, create it
      if($('#'+name).length == 0) {
        var passEl = jQuery('<input id="'+name+'" type="text" value="Password" class="virtual_password" name="'+name+'" />')
        
        // on focus, hide virtual element, show real password and give it focus
        passEl.focus(function() {
          passEl.hide()
          input.show().focus()
        })

        // now hide the actual password element and insert the virtual
        input.hide().before(passEl)
      }
      // otherwise, password field is empty, hide real and show virtual again
      else {
        input.hide()
        $('#'+name).show()
      }
    }
    else {
      input.toggleClass('ghosttext')
      input.val(input.attr('title'))
    }
  }
}

var ghostTextBinder = new GhostText()