/**
 * CRFrameManager v0.1
 * 
 * Publishes frame height to parent frame via anchor hash
 * 
 * @author Kazi Manzur Rashid Amit (kazimanzurrashid at gmail dot com)
 * @author Erling Limm (eibon.dott at gmail dot com)    
 */
var CRFrameManager = {
  currentFrameId: '',
  currentFrameHeight: 0,
  lastFrameId: '',
  lastFrameHeight: 0,
  resizeTimerId: null,
  CHECK_INTERVAL: 50,

  init: function() {
    if (!!window.postMessage) {
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', CRFrameManager.onmessage, false);
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', CRFrameManager.onmessage);
      }
    } else {
      if (CRFrameManager.resizeTimerId == null) {
        CRFrameManager.resizeTimerId = window.setInterval(CRFrameManager.resizeFrames,
                                                          CRFrameManager.CHECK_INTERVAL);
      }
    }
  },

  resizeFrames: function() {
    if (!window.postMessage) { // only if !html5
      CRFrameManager.retrieveFrameIdAndHeight();
    }

    if ((CRFrameManager.currentFrameId != CRFrameManager.lastFrameId) ||
        (CRFrameManager.currentFrameHeight != CRFrameManager.lastFrameHeight)) {

      if (CRFrameManager.currentFrameHeight == 0) // Keeps from updating first time when body is 0px
        return;
            
      var iframe = document.getElementById(CRFrameManager.currentFrameId.toString());

      if (iframe == null)
        return;

      //console.log("iframe id: " + iframe.id);
      //console.log("iframe pre-ht: " + iframe.style.height);

      iframe.style.height = CRFrameManager.currentFrameHeight.toString() + "px";

      //console.log("iframe post-ht: " + iframe.style.height);

      CRFrameManager.lastFrameId = CRFrameManager.currentFrameId;
      CRFrameManager.lastFrameHeight = CRFrameManager.currentFrameHeight;
      
      if (!window.postMessage) { // only if !html5
        window.location.hash = '';
      }
    }
  },

  onmessage: function(e) {
    var data = e.data;
    var origin = e.origin;
    var pair = data.split('=');
    if ((pair != null) && (pair.length > 0)) {
      if (pair[0] == 'h') {
        var height = parseInt(pair[1]);
        if (!isNaN(height)) {
          CRFrameManager.currentFrameHeight = height;
          CRFrameManager.currentFrameHeight += 15;
          CRFrameManager.resizeFrames();
        }
      }
    }
  },

  listenToSource: function() {
    var iframe = document.getElementById(CRFrameManager.currentFrameId.toString());
    if (iframe != null) {
      //console.log('    CRFrameManager.lastSource: ' + CRFrameManager.lastSource);
      //console.log('iframe.contentWindow.location: ' + iframe.contentWindow.location);
      if (CRFrameManager.lastSource != iframe.contentWindow.location) {
        iframe.contentWindow.location = CRFrameManager.lastSource = iframe.contentWindow.location + '&id=' + iframe.id + '#' + location.href;
        //console.log('source has changed -> reinit!');
        //CRFrameManager.registerFrame(iframe);
      }
    }/* else {
      console.log('listenToSource -> iframe is null');
    }*/

  },

  retrieveFrameIdAndHeight: function() {
    if (window.location.hash.length == 0)
      return;

    var hashValue = window.location.hash.substring(1);

    if ((hashValue == null) || (hashValue.length == 0))
      return;

    var pairs = hashValue.split('&');

    if ((pairs != null) && (pairs.length > 0)) {
      for(var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');

        if ((pair != null) && (pair.length > 0)) {
          if (pair[0] == 'id') {
            if ((pair[1] != null) && (pair[1].length > 0)) {
              CRFrameManager.currentFrameId = pair[1];
            }
          } else if (pair[0] == 'ht') {
            var height = parseInt(pair[1]);

            if (!isNaN(height)) {
              CRFrameManager.currentFrameHeight = height;
              CRFrameManager.currentFrameHeight += 15;
            }
          }
        }
      }
    }
  },

  registerFrame: function(frame) {

    if (!!window.postMessage) {
      CRFrameManager.currentFrameId = frame.id;
    } else {
      var currentLocation = location.href;
      var hashIndex = currentLocation.indexOf('#');

      if (hashIndex > -1)
        currentLocation = currentLocation.substring(0, hashIndex);

      frame.contentWindow.location = frame.src + (frame.src.indexOf("?") != -1 ? "&" : "?") + 'id=' + frame.id + '#' + currentLocation;
    }


    //if (!CRFrameManager.reRegister) {
      ////frame.contentWindow.location = frame.src + (frame.src.indexOf("?") != -1 ? "&" : "?") + 'id=' + frame.id + '#' + currentLocation;
    //} else {
    //  frame.contentWindow.location = CRFrameManager.lastSource =
    //    frame.contentWindow.location + (frame.contentWindow.location.indexOf("?") != -1 ? "&" : "?") + 'id=' + frame.id + '#' + currentLocation;
    //}
  }
};
