(function() {
  var jQuery;
  var serverFQDN = 'http://shortmail.com';
  var timeoutId, options, container;

  if (!window.Shortmail) window.Shortmail = {};
  Shortmail.ComposeWidget = function(opts) {
    //console.log('ComposeWidget constructed:');
    //console.dir(opts);
    options = opts;
    if (!options.timeout) {
      options.timeout = 5 * 1000;
    }
    if (!options.type) {
      options.type = 'button';
    }
    container = '.shortmail-compose-widget';
  };

  function init() {
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.6.4') {
      //console.log('we need to load jQuery');
      var script_tag = document.createElement('script');
      script_tag.setAttribute("type","text/javascript");
      script_tag.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js");
      (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
      if (script_tag.attachEvent) {
        //console.log('oh cool, this is IE');
        script_tag.onreadystatechange = function() { // for IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') {
            this.onreadystatechange = null;
            scriptLoadHandler();
          }
        };
      } else {
        script_tag.onload = scriptLoadHandler;
      }
    } else {
      jQuery = window.jQuery;
      //console.log('jQuery already exists on page');
      main();
    }
  }

  function scriptLoadHandler() {
    jQuery = window.jQuery.noConflict();
    //console.log('jQuery is now loaded');
    main();
  }
  
  function main() {
    jQuery(document).ready(function() {
      //console.log('adding stylesheets');
      jQuery('head').append('<link href="' + serverFQDN + '/widgets/cleanslate.css" rel="stylesheet" type="text/css">');
      jQuery('head').append('<link href="' + serverFQDN + '/widgets/compose-widget.css" rel="stylesheet" type="text/css">');
      jQuery.getScript(serverFQDN + '/javascripts/vendor/json2.js');

      if (jQuery(container).size() === 0) {
        //console.log('div shortmail-compose-widget does not exist, building it');
        jQuery('body').append('<div class="shortmail-compose-widget"></div>');
        //todo build where script tag is
      }
      jQuery(container).addClass('cleanslate');
      
      render();
      attachEvents();
    });
  }
  
  function render() {
    //console.log('building widget markup');
    var markup = '';
    if (options.type === 'button') {
      markup = markup + '<div class="shortmail-compose-widget-window" style="display:none !important;">';
    }
    markup = markup + '<div class="wrapper"><p class="title">Send a Shortmail to <a href="' + serverFQDN + '/' + options.screenName + '" target="_blank">' + options.screenName + '</a></p>\
      <input class="from" type="text" placeholder="Your return email address"></input>\
      <textarea class="text" placeholder="Your message"></textarea>\
      <div class="charCount"><span>500</span> chars</div>\
      <button class="send-shortmail">Send Shortmail</button>\
      <button class="cancel">Cancel</button></div>\
    ';
    if (options.type === 'button') {
      markup = markup + '</div>';
    }
    jQuery(container).append(markup);
  }
  
  function attachEvents() {
    //console.log('attaching events');
    jQuery(container + ' textarea.text').keyup(updateCharCount(500)).keyup();
    jQuery(container + ' .send-shortmail').click(sendMessage);
    jQuery(container + ' .cancel').click(cancel);
    // responses from the server come from the iframe as postMessages
    jQuery.getScript(serverFQDN + '/widgets/jquery.ba-postmessage.min.js', function() {
      jQuery.receiveMessage(serverResponse, serverFQDN);
    });
    if (options.type === 'button') {
      jQuery(container + ' button.shortmail-me').click(Shortmail.showWindow);
      jQuery(container + ' .cancel').click(hideWindow);
    }
  }
  
  Shortmail.showWindow = function() {
    jQuery(container + ' button.send-shortmail').removeAttr('disabled');
    var el = jQuery(container + ' .shortmail-compose-widget-window');
    if (jQuery("#shortmail-compose-widget-overlay").length === 0) {
      jQuery(document.body).append("<div id='shortmail-compose-widget-overlay'></div>");
      jQuery("#shortmail-compose-widget-overlay").click(cancel);
      jQuery("#shortmail-compose-widget-overlay").click(hideWindow);
    }
    jQuery("#shortmail-compose-widget-overlay").attr('style','display:block !important');
    el.attr('style','display:block !important');
    return false;
  }
  function hideWindow() {
    jQuery(container + ' .shortmail-compose-widget-window, #shortmail-compose-widget-overlay').attr('style','display:none !important');
  }
  Shortmail.hideWindow = function() {
    hideWindow();
    $('#message-sent').remove();
  }

  function updateCharCount(max) {
    return function() {
      var tag = jQuery(this).siblings('.charCount').has('span');
      if (tag) {
        var left = max - jQuery(this).val().length;
        tag.find('span').html(left);
        if (left < 0) {
          tag.addClass('over-limit');
        } else {
          tag.removeClass('over-limit');
        }
      }
    };
  }
  
  function sendMessage() {
    jQuery(this).attr('disabled', 'disabled');
    var from = jQuery(this).siblings('input.from').val();
    var text = jQuery(this).siblings('textarea.text').val();
    if (isValid(from, text)) {
      clearStatus();
      //console.log('sending message from "' + from + '": "' + text + '"');
      var iframesrc = serverFQDN + '/widgets/compose-widget-receiver' + 
        '?from=' + encodeURIComponent(from) + 
        '&to=' + encodeURIComponent(options.screenName) +
        '&text=' + encodeURIComponent(text) +
        '&host_page=' + encodeURIComponent(document.location.href);
      jQuery(container).after('<iframe class="shortmail-compose-widget-receiver" src="' + 
        iframesrc + '" width="0" height="0" frameborder="0" scrolling="no"></iframe>');
      //todo show a spinner
      timeoutId = setTimeout(function() {
        //console.log('timeout');
        //it succeeded, the iframe could not communicate back to us
        cleanUp({"success": true, "message": ""});
      }, options.timeout);
    }
  }
  
  function isValid(from, text) {
    if (from && text) {
      if (from.match(/\S+\@\S+\.\S+/)) {
        if (text.length <= 500) {
          return true;
        } else {
          updateStatus('Message must be less than 500 chars long');
          return false;
        }
      } else {
        updateStatus('Your return email does not look like an email address');
        return false;
      }
    } else {
      if (!text) updateStatus('Please enter a message');
      if (!from) updateStatus('Your return email is required');
      return false;
    }
  }
  
  function cancel() {
    jQuery(this).siblings('input.from').val('');
    jQuery(this).siblings('textarea.text').val('').keyup();
    clearStatus();
  }
  
  function serverResponse(e) {
    if (e.origin !== serverFQDN) return;
    //console.log('we got a response:');
    var result = JSON.parse(e.data);
    //console.dir(result);
    clearTimeout(timeoutId);
    cleanUp(result);
  }
  
  function cleanUp(result) {
    jQuery('iframe.shortmail-compose-widget-receiver').remove();
    //todo hide spinner
    jQuery(container + ' button.send-shortmail').removeAttr('disabled');
    if (result.success) {
      //console.log('success!');
      cancel.apply(jQuery(container + ' .send-shortmail'));
      if (options.type === 'button') {
        $('.shortmail-compose-widget-window .title').append('<div id="message-sent">Message sent!</div>');
        setTimeout('Shortmail.hideWindow()', 2000) 
        //todo show success
      } else {
        updateStatus('<span class="success-message">Shortmail sent!</span>');
      }
    } else {
      updateStatus('Send failed: ' + result.message);
    }
  }
  
  function clearStatus() {
    jQuery(container + ' .shortmail-message').remove();
  }

  function updateStatus(msg) {
    if (jQuery(container + ' .shortmail-message').length === 0) {
      jQuery(container + ' .wrapper').append('<p class="shortmail-message"></p>');
    }
    jQuery(container + ' .shortmail-message').html(msg);
  }
    
  init();
  
})();
