/**
 * Created by Achim on 01.12.14.
 */
function WindowManagement(){
  var frameId;
  
  function keepWindowAlive()
  {
    var time = new Date().getTime();
    localStorage["windowIdActive" + windowId] = time;
    setTimeout(keepWindowAlive, 1000);
    $.each(localStorage, function(windowIdWidthPefix, lastActiveTime) {
      if ( windowIdWidthPefix.indexOf("windowIdActive") == 0 )
      {
        if ( lastActiveTime < time - 10000 )
        {
          ajaxEngine.sendServerCommand("removeWindow", { idToRemove: windowIdWidthPefix.split("windowIdActive")[1] }, true);
          delete localStorage[windowIdWidthPefix];
        }
      }
    })
  }
  
  function init()
  {
    if (typeof windowId == 'undefined')
      return;

    frameId = "default";
    var fallbackWindowId = "00000000-0000-0000-0000-000000000000";
    var storageAvailable = webcore.isStorageAvailable();

    if ( parent.window != window ) {//is in iFrame
      try {
        var $parent = $(parent.window.document);//check if iframe is accesible (cross domain isn't valid)
        var $iFrames = $parent.find("iframe");
        $.each( $iFrames, function( i, iFrame ) {
          if ( $(iFrame).contents()[0] == document )
          {
            frameId = iFrame.id || i;
            if( !storageAvailable )
            {
              var idString = (i + 1).toString();
              fallbackWindowId = fallbackWindowId.substring( 0, fallbackWindowId.length - idString.length - 1 ) + idString;
            }
          }
        });
      }
      catch ( e ) {
        //in case of cross domain access the id will be "default"
      }
    } else
      frameId = "main";

    if ( !storageAvailable || ( sessionStorage["frame-" + frameId] && sessionStorage["frame-" + frameId] != windowId ) ) {
      var oldId = windowId;
      windowId = storageAvailable ? sessionStorage["frame-" + frameId] : windowId;
      updateWindowId( oldId );
    }
    else
    {
      sessionStorage["frame-" + frameId] = windowId;
      if ( typeof initPhase !== 'undefined' && initPhase === true )
        updateWindowId( windowId ); //just to send device details
      else
        ajaxEngine.sendServerCommand("processCommandQueue");
        // $(document).trigger("initdone");
    }
    if ( storageAvailable )
      keepWindowAlive();
  }

  function updateWindowId( oldId )
  {
    $.ajax(
        {
            url: applicationServletPath + "ajaxCommandServlet",
        data:{command: "updateWindowId", oldId:oldId},
          cache: false,
        async: false,
        success : function()
        {
          $(document).trigger("initdone");
        }
      }
    );
  }
  //http://stackoverflow.com/questions/20879714/how-to-prevent-sessionstorage-being-inherited-when-using-target-blank-window
  function removeWindowId()
  {
    if( webcore.isStorageAvailable() )
      sessionStorage.removeItem("frame-" + frameId);
  }
  
  function restoreWindowId()
  {
    if( webcore.isStorageAvailable() )
      sessionStorage["frame-" + frameId] = windowId;
  }

  return {
    init: init,
    removeWindowId: removeWindowId,
    restoreWindowId: restoreWindowId
  }
}

var windowManagement = new WindowManagement();
$(document).ready( function() {
  windowManagement.init();
});
