Posting = {
  VALID_EMAIL: /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9\"]{2,4})+$/,
  
  sendToHTML: '<div id="send_to" class="overlay" style="display: none"><div class="tab">Send to&nbsp;<img src="/images/icons/down_arrow_link.png" alt="" /></div><div class="content">' +
    '<form>' +
      '<div class="emails">' +
        '<label><input type="checkbox" name="my_email">My e-mail</label>&nbsp;&nbsp;&nbsp;' +
        '<label class="mobile"><input type="checkbox" name="my_mobile">My mobile</label>&nbsp;&nbsp;&nbsp;' +
        '<label><input type="checkbox" name="other_emails">This e-mail&nbsp;</label>&nbsp;' +
        '<input class="email_address" name="other_emails_text" style="font-family: lucida grande, arial;">' +
        '<h3 style="border-top: 1px dotted #aaa; margin-top: 8px;">Send to these Corkboard contacts</h3>' +
      '</div>' +
      '<div class="these_contacts">' +
        '<div class="private" style="display: none"><p>This is a private Posting.</p><p>To send this to others, please <a href="#">update the Sharing level</a>.</p></div>' +
		'<div class="for_contacts" style="display: none"><strong>Since this Posting is Private, it can be shared with your Corkboard contacts only if you add it to your Corkboard.</strong></div>' +
        '<div class="contacts"><img src="/images/loading.gif" style="display: block; margin: 0 auto;"></div>' +
      '</div>' +
      '<div class="message" style="margin-left: 0px; padding-left: 2px;">' +
        '<div style="padding-bottom: 2px;">Add a custom message* or just click <strong>Send</strong></div>' +
        '<textarea name="message" style="font-family: lucida grande, arial;"></textarea>' +
      '</div>' +
      '<div class="buttons" style="padding-top: 5px; float: left;">' +
        '<a href="#" class="button send">Send</a>' +
        '<a href="#" class="cancel" style="float: left; margin-left: 5px; padding-top: 1px;">Cancel</a>' +
      '</div>' +
      '<div class="redText" style="float: right; padding-top: 6px;">*Custom message not sent to mobile devices.</div>' +
    '</form>' +
    '<div class="sending" style="display: none"><img src="/images/loading.gif" style="vertical-align: middle;"> Sending</div>' +
    '<div class="sent" style="display: none;"><img src="/images/icons/checkmark.png" /> Posting sent</span></div>' +
  '</div></div>',
  
  sendToInfoHTML: '<div id="send_to"><div class="tab">Send to&nbsp;<img src="/images/icons/down_arrow_link.png" alt="" /></div><div class="content">' +
    '<form>' +
      '<h3>Send to</h3>' +
      '<div class="emails">' +
        '<p>This feature lets you send Postings directly to an e-mail address, your mobile device or any of your Corkboard contacts. To use this feature, please <a class="login">log in</a> to your account. Not a member? <a class="register">Get a free account now</a>.</p>' +
      '</div>' +
      '<div class="buttons">' +
        '<a href="#" class="button cancel">Close</a>' +
      '</div>' +
    '</form>' +
  '</div></div>',
  
  sendTo: function(relativeTo, postingId, urls, loggedIn, options) {
    options = options || {};
    
    var overlay = $('send_to');
    
    if (!overlay) {
      overlay = new Element('div').update(Posting[!loggedIn ? 'sendToInfoHTML' : 'sendToHTML']).firstChild;
      
      document.body.appendChild(overlay);
      
      $(overlay);
      
      overlay.hideOverlay = function() {
        var posting;
        if ((posting = overlay.up('.posting')) && posting.dragDrop) posting.dragDrop.unlock();
        overlay.hide();
      };
      
      if (!loggedIn) {
        overlay.down('.login').href = urls.login + '?return_to=' + encodeURIComponent(location.pathname);
        overlay.down('.register').href = urls.register;
      } else {
        var contactsHTML = '';
        
        new Ajax.Request(urls.contacts, {
          method: 'get',
          onSuccess: function(res) {
            contacts = eval('(' + res.responseText + ')');
            contacts.each(function(c) {
              contactsHTML += '<label><input type="checkbox" value="' + c.id + '" name="contacts_ids[]">' + c.name + '</label>';
            });
            overlay.down('.contacts').innerHTML = contactsHTML;
          }
        });
        		
        if (urls.profile) {
          var mobile = overlay.down('label.mobile');
          mobile.down('input').disabled = true;
          var link = new Element('a', {
            href: urls.profile,
            title: 'Please add and confirm your mobile number'
          }).update('My mobile');
          mobile.replaceChild(link, mobile.childNodes[1]);
        }
      }
      
      overlay.down('.tab').onclick = overlay.down('.cancel').onclick = function() {
        //overlay.hide();
        overlay.hideOverlay();
        return false;
      };
    }
    
    if (loggedIn) {
	    var myEmail = overlay.down('input[name=my_email]'),
	        myMobile = overlay.down('input[name=my_mobile]'),
	        otherEmails = overlay.down('input[name=other_emails]'),
	        otherAddress = overlay.down('input[name=other_emails_text]'),
	        message = overlay.down('textarea[name=message]');
	    
	    myEmail.checked = myMobile.checked = otherEmails.checked = false;
	    otherAddress.value = message.value = '';
	    
	    if (urls.postingDetails) {
	      overlay.down('.contacts').hide();
	      overlay.down('.private').show().down('a').href = urls.postingDetails;
	      overlay.down('[name=other_emails]').onclick = function() {
	        if (this.checked) {
	          alert("Just a head's up: this Posting is Private. So if you're sending this to someone else, please update the Sharing level by clicking the Edit link.");
	        }
	      };
	    }
		else if (urls.for_contacts)
		{
			overlay.down('.contacts').hide();
			overlay.down('.for_contacts').show()
			overlay.down('.email_address').disable();
			overlay.down('[name=other_emails]').disable();
		}
		 else {
	      overlay.down('.contacts').show();
	      overlay.down('.private').hide();
	      otherEmails.onclick = null;
	    }
      
      overlay.down('.send').onclick = function() {
        //Validate email
        var email = otherAddress.value;
        if ((email == '' && otherEmails.checked) || (email != '' && !email.match(Posting.VALID_EMAIL))) {
          alert('Please enter a valid e-mail address');
          return false;
        } else if (email != '' && email.match(Posting.VALID_EMAIL)) {
          otherAddress.checked = true;
        }
        
        //Validate at least one selection
        var selectedContacts = false;
        contacts = overlay.down('form').getInputs('checkbox', 'contacts_ids[]').map(function(c) {
          selectedContacts |= c.checked;
        });
        
        if (!myEmail.checked && !myMobile.checked && !otherEmails.checked && !selectedContacts) {
          alert('Please choose where - or to whom - you\'d like to send this');
          return false;
        }
        
        overlay.down('.sending').show();
        
        new Ajax.Request(urls.send, {
          parameters: 'posting_id=' + postingId + '&' + Form.serialize(overlay.down('form')),
          
          onSuccess: function(res) {
            if (res.responseText == 'ok') { 
              overlay.down('.sending').hide();
              var sent = overlay.down('.sent').show();

              setTimeout(function() {
                new Effect.Fade(overlay, {
                  beforeStart: function() {
                    sent.hide();
                  },
                  
                  afterFinish: function() {
                    overlay.hideOverlay();
                  }
                });
              }, 1000);

            } else {
              alert('Oops. It looks like you\'re logged out of your account. Please log in and you\'ll be able to use this feature.');
            }
          },
          
          onFailure: function() {
            alert('Oops. Something you entered didn\'t go down so well. Please try again.');
          }
        });
        
        return false;
      };
    }
    
    // IE doesn't play nice with z-index, so we need to place the overlay
    // at document level in order to have it appear on top
    if (options.attachToOffsetParent && !Prototype.Browser.IE) $(relativeTo).getOffsetParent().appendChild(overlay);
    
    var posting;
    if ((posting = overlay.up('.posting')) && posting.dragDrop) {
      posting.dragDrop.lock();
    }
    
    overlay.clonePosition(relativeTo, {
      setWidth: false,
      setHeight: false,
      offsetLeft: options.offsetLeft || -200
    });
    
    setOverlay(overlay);
    
    overlay.show();
  }
}
