/*
 * Copyright (c) OutWit Technologies 2007-2017.
 * All rights reserved.
 */

/**
 *
 *
 *
 *
 */

var ZoomManager = {
  get _prefBranch() {
    delete this._prefBranch;
    return this._prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
                                        .getService(Components.interfaces.nsIPrefBranch);
  },

  get MIN() {
    delete this.MIN;
    return this.MIN = this._prefBranch.getIntPref("zoom.minPercent") / 100;
  },

  get MAX() {
    delete this.MAX;
    return this.MAX = this._prefBranch.getIntPref("zoom.maxPercent") / 100;
  },

  snap: function(aVal) {
    var values = this.zoomValues;
    for (var i = 0; i < values.length; i++) {
      if (values[i] >= aVal) {
        if (i > 0 && aVal - values[i - 1] < values[i] - aVal)
          i--;
        return values[i];
      }
    }
    return values[i - 1];
  },

  _zoom:1,
  
  get zoom(){
    return this._zoom;
  },


  get zoomValues() {
    var zoomValues = this._prefBranch.getCharPref("toolkit.zoomManager.zoomValues").split(",").map(parseFloat);
    zoomValues.sort();

    while (zoomValues[0] < this.MIN)
      zoomValues.shift();

    while (zoomValues[zoomValues.length - 1] > this.MAX)
      zoomValues.pop();

    delete this.zoomValues;
    return this.zoomValues = zoomValues;
  },

  set zoom(aVal){
    if (aVal < this.MIN || aVal > this.MAX)
      throw Components.results.NS_ERROR_INVALID_ARG;

    this._zoom = aVal;


    var listMarkupDocumentViewer  = gContainer.listview.browser.markupDocumentViewer;
    listMarkupDocumentViewer.textZoom = 1;
    listMarkupDocumentViewer.fullZoom = aVal;

    var iconsMarkupDocumentViewer = gContainer.iconsview.browser.markupDocumentViewer;
    iconsMarkupDocumentViewer.textZoom = 1;
    iconsMarkupDocumentViewer.fullZoom = aVal;
      
    this._prefBranch.setCharPref("extensions.outwit.oWDocs.zoom", ZoomManager.zoom);
    this.syncWithUI();
  },


  reduce: function(){
    var i = this.zoomValues.indexOf(this.snap(this.zoom)) - 1;
    if (i >= 0)
      this.zoom = this.zoomValues[i];
  },

  enlarge: function(){
    var i = this.zoomValues.indexOf(this.snap(this.zoom)) + 1;
    if (i < this.zoomValues.length)
      this.zoom = this.zoomValues[i];
  },

  reset: function(){
    this.zoom = 1;
  },
  
  syncWithUI: function(){
    var zoomField = document.getElementById('zoomNormal');
    var zoomLevel = parseInt(ZoomManager.zoom * 100);
    zoomField.setAttribute('label', zoomLevel + '%');
  }
};

