(function() {

  var proxyUrl, relayUrl;

  function init(xdProxyUrl, xdRelayUrl) {
    proxyUrl = xdProxyUrl;
    relayUrl = xdRelayUrl || findXdRelayUrl();
  }

  var token;

  function connect(params) {
    sendMessage({
      message : { site_url : relayUrl },
      success : function(t) {
        token = t;
        params.success();
      },
      error : params.error
    });
  }

  function request(params) {
    if (!token) {
      connect({
        success : function() { request(params); },
        error : params.error
      });
    } else {
      sendMessage({
        message : {
          url : params.url,
          method : params.method,
          data : params.data,
          token : token
        },
        success : function(res) {
          if (res.status==200) {
            params.success(res.body, res.status);
          } else {
            params.error(res);
          }
        },
        error : params.errror
      });
    }
  }

  function sendMessage(params) {
    var ifr = document.createElement('iframe');
    ifr.frameBorder = ifr.width = ifr.height = 0;
    ifr.style.visibility = 'hidden';
    document.body.appendChild(ifr);
    ifr.contentWindow.name = JSON.stringify(params.message);
    ifr.contentWindow.location.href = proxyUrl + '#' + encodeURIComponent(relayUrl);
    // Wait until the iframe url redirected back to same domain.
    var PID = window.setInterval(function() {
      try {
        var ret = ifr.contentWindow.location.href.split('#');
        if (ret[0] == relayUrl) {
          window.clearInterval(PID);
          var response = ret[1] ? ret[1] : JSON.parse(ifr.contentWindow.name);
          ifr.parentNode.removeChild(ifr);
          params.success(response);
        }
      } catch(e) { }
    }, 100);
  }

  function findXdRelayUrl() {
    var domainUrl = getDomainUrl(location.href);
    var imageUrl;
    var imgs =  document.getElementsByTagName('img');
    for (var i=0; i<imgs.length; i++) {
      var img = imgs[i];
      if (getDomainUrl(img.src) == domainUrl) {
        imageUrl = img.src;
        break;
      }
    }
    return imageUrl || location.href;
  }

  function getDomainUrl(url) {
    if (/^https?:/.test(url)) return url.split('/').slice(0, 3).join('/');
    else if (url.indexOf('/')==0) return location.href.split('/').slice(0, 3) + url;
    else return location.href.split('/').slice(0, -1) + url;
  }

  window.XdOAuth = {
    init : init,
    request : request
  }

})();
