

/*global window */
// Set up URL of proxy document residing in VW CMS
var vwd4_proxyURL = 'http://it.volkswagen.com/it/guida_all_acquisto/usato_first_classtest/stock_locator.e16_page_proxy.html';

// Create iframe to hold proxy document
document.write('<iframe id="vwd4_parentProxy" width="10px" height="10px" frameborder="0" src="' + vwd4_proxyURL + '" style="position: relative; left: -1550px; top: 0px"></iframe>');
// Check for browser
var vwd4_userAgent = navigator.userAgent.toLowerCase();
// Set if window has been loaded in IE or Safari
var vwd4_loaded;
var vwd4_resized;

/**
 * Send message to iFrame
 * @param {Object} message
 */
function vwd4_sendMessageToiFrame(message){
  var elem = document.getElementById('vwd4_parentProxy');
  elem.contentWindow.location = vwd4_proxyURL + "#" + message;
  // toggle the iFrame's size to indicate there is a message ready to be read
  elem.width = elem.width > 50 ? 50 : 100;
}

/**
 * Inform the parent page that the <body> size has changed
 */
function vwd4_bodySizeChanged(){
  var message = "height=";
  // read required document height
  if (vwd4_userAgent.indexOf("msie") != -1) {
    message = message + Number(document.body.scrollHeight);
  }
  else {
    message = message + Number(document.body.offsetHeight);
  }
  // Send a message to the parent via the proxy
  vwd4_sendMessageToiFrame(message);
}

// Attach listener to <body> to capture changes in size
window.onload = function(){
  // reset iFrame height to 10px to prevent wrong height in Safari
  if (vwd4_userAgent.indexOf("safari") != -1) {
    vwd4_sendMessageToiFrame("height=10");
  }
  else {
    // store info about resize cause by onload event in MSIE
    if (vwd4_userAgent.indexOf("msie") != -1) {
      vwd4_loaded = true;
    }
    vwd4_bodySizeChanged();
  }
};
window.onresize = function(){
  // check if resize is actually caused by onload event and ignore it
  if (vwd4_loaded) {
    vwd4_loaded = false;
  }
  else {
    if (vwd4_userAgent.indexOf("safari") != -1) {
      /*
       * check if resize was triggered before
       * this prevents infinite loop caused by resize in Safari
       */
      if (vwd4_resized) {
        // ignore double resize action
        vwd4_resized = false;
      }
      else {
        // store resize action and check for new height
        vwd4_resized = true;
        setTimeout(function(){
          vwd4_bodySizeChanged();
        }, 0);
      }
    }
    else {
      // all other browsers proceed normally
      vwd4_bodySizeChanged();
    }
  }
};
