(function(win, doc) {
  var device = navigator.userAgent.toLowerCase();
  if (!/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile|mobile/.test(device)) {
    return;
  }

  var metaEl = doc.querySelector('meta[name="viewport"]');
  var tid;
  if (!metaEl) {
    metaEl = doc.createElement("meta");
    metaEl.setAttribute("name", "viewport");
  }
  var fresh = function() {
    var availWidth;
    if (window.orientation === 180 || window.orientation === 0) { 
      availWidth = Math.min(window.screen.availWidth, window.screen.availHeight);
    };
    if (window.orientation === 90 || window.orientation === -90 ){ 
      availWidth = Math.max(window.screen.availWidth, window.screen.availHeight);
    } 
    var mobileScale = availWidth / 1400;
    metaEl.setAttribute( "content", "initial-scale=" + mobileScale + ", minimum-scale=" + mobileScale + ", minimum-scale=" + mobileScale);
  };
  doc.addEventListener("DOMContentLoaded", function() {
    setTimeout(fresh, 1000);
  }, false);
  win.addEventListener('resize', function() {
      clearTimeout(tid);
      tid = setTimeout(fresh, 300);
  }, false);
  win.addEventListener('pageshow', function(e) {
      if (e.persisted) {
          clearTimeout(tid);
          tid = setTimeout(fresh, 300);
      }
  }, false);
})(window, document);
