/**
 * Created by dagan on 07/04/2014.
 */
'use strict';
/* global console, XdUtils */
window.xdLocalStorage = window.xdLocalStorage || (function () {
  var MESSAGE_NAMESPACE = 'cross-domain-local-message';
  var options = {
    iframeId: 'cross-domain-iframe',
    iframeUrl: undefined,
    initCallback: function () {}
  };
  var requestId = -1;
  var iframe;
  var requests = {};
  var wasInit = false;
  var iframeReady = false;
  var messageCache = [];

  function applyCallback(data) {
    if (requests[data.id]) {
      requests[data.id](data);
      delete requests[data.id];
    }
  }

  function receiveMessage(event) {
    var data;
    try {
      data = JSON.parse(event.data);
    } catch (err) {
      //not our message, can ignore
    }
    if (data && data.namespace === MESSAGE_NAMESPACE) {
      if (data.id === 'iframe-ready') {
        iframeReady = true;
        options.initCallback();
        messageCache.forEach(function (data) {
            iframe.contentWindow.postMessage(JSON.stringify(data), '*');
          });
        messageCache.length = 0;
      } else {
        applyCallback(data);
      }
    }
  }

  function buildMessage(action, key, value, callback) {
    requestId++;
    requests[requestId] = callback;
    var data = {
      namespace: MESSAGE_NAMESPACE,
      id: requestId,
      action: action,
      key: key,
      value: value
    };
    if (iframeReady) {
      iframe.contentWindow.postMessage(JSON.stringify(data), '*');
    } else {
      messageCache.push(data);
    }
  }
  function init(customOptions) {
    if (wasInit) {
      console.log('xdLocalStorage was already initialized!');
      return;
    }
    wasInit = true;
    options = XdUtils.extend(customOptions, options);
    var temp = document.createDocumentFragment();

    if (window.addEventListener) {
      window.addEventListener('message', receiveMessage, false);
    } else {
      window.attachEvent('onmessage', receiveMessage);
    }

    iframe = temp.ownerDocument.createElement('iframe');
    iframe.id = options.iframeId;
    iframe.src = options.iframeUrl;
    temp.appendChild(iframe);
    document.body.appendChild(temp);
  }

  function isApiReady() {
    if (!wasInit) {
      console.log('You must call xdLocalStorage.init() before using it.');
      return false;
    }
    return true;
  }

  return {
    //callback is optional for cases you use the api before window load.
    init: function (customOptions) {
      if (!customOptions.iframeUrl) {
        throw 'You must specify iframeUrl';
      }
      init(customOptions);
    },
    setItem: function (key, value, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('set', key, value, callback);
    },

    getItem: function (key, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('get', key,  null, callback);
    },
    removeItem: function (key, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('remove', key,  null, callback);
    },
    key: function (index, callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('key', index,  null, callback);
    },
    clear: function (callback) {
      if (!isApiReady()) {
        return;
      }
      buildMessage('clear', null,  null, callback);
    }
  };
})();
@@ -423,38 +423,12 @@
 y = 
-false;%0A  var messageCache = %5B%5D
+true
 ;%0A%0A 
@@ -880,175 +880,8 @@
 ();%0A
-        messageCache.forEach(function (data) %7B%0A            iframe.contentWindow.postMessage(JSON.stringify(data), '*');%0A          %7D);%0A        messageCache.length = 0;%0A
     
@@ -1190,33 +1190,8 @@
  %7D;%0A
-    if (iframeReady) %7B%0A  
     
@@ -1255,58 +1255,8 @@
 ');%0A
-    %7D else %7B%0A      messageCache.push(data);%0A    %7D%0A
   %7D%0A
@@ -1497,25 +1497,21 @@
 eate
-DocumentFragment(
+Element('div'
 );%0A%0A
@@ -1693,76 +1693,41 @@
     
-iframe = temp.ownerDocument.createElement('iframe');%0A    
+temp.innerHTML = '%3C
 iframe
-.
+ 
 id
- 
 =
+%22' +
  opt
@@ -1743,74 +1743,77 @@
 meId
-;%0A    iframe.src = options.iframeUrl;%0A    temp.appendChild(
+ + '%22 src=' + options.iframeUrl + ' style=%22display: none;%22%3E%3C/
 iframe
-)
+%3E'
 ;%0A  
@@ -1847,16 +1847,72 @@
 (temp);%0A
+    iframe = document.getElementById(options.iframeId);%0A
   %7D%0A%0A  f
@@ -2051,24 +2051,157 @@
 alse;%0A    %7D%0A
+    if (!iframeReady) %7B%0A      console.log('You must wait for iframe ready message before using the api.');%0A      return false;%0A    %7D%0A
     return t
@@ -2432,27 +2432,180 @@
    i
-nit(customOptions);
+f (document.readyState === 'complete') %7B%0A        init(customOptions);%0A      %7D else %7B%0A        window.onload = function () %7B%0A          init(customOptions);%0A        %7D;%0A      %7D
 %0A   

revert merge for message cache. it was not tested and had bugs