﻿Ext.namespace('Mapping.Ext.Esri');

Ext.data.Types.ESRIPOINT = {
  convert: function(v, data) {
    if(data.result != null) { 
      return new esri.geometry.Point(
        data.result.x, 
        data.result.y, 
        new esri.SpatialReference(data.result.spatialReference));
    } else { 
      return null;
    }
  },
  sortType: function(v) {
    return v.y;
  },
  type: 'EsriPoint'
};

Mapping.Ext.Esri.Bookmarks = function() {

  var bookmarkData, bookmarkStore, bookmarkTemplate, bookmarkDataView, bookmarkWindow, currentMarker;
  var defaultText = '';
  
  // Load store data from cookie
  function loadBookmarkData() {
    if (Ext.util.Cookies.get(bookmarkCookieName) != null) {
      bookmarkData = Ext.util.JSON.decode(Ext.util.Cookies.get(bookmarkCookieName));
    }
    bookmarkStore.loadData(bookmarkData);
  }

  // Saves data to cookie
  function saveBookmarkData() {
    Ext.util.Cookies.set(
        bookmarkCookieName,
        Ext.util.JSON.encode(bookmarkData),
        cookieExpirationDate
    );
  }

  // Reload store data and update cookie for persistence
  function reloadBookmarkData() {
    bookmarkStore.loadData(bookmarkData);
    saveBookmarkData();
  }

  // Prompts user for a bookmark name and saves with current extent
  function createNewBookmark() {
    Ext.MessageBox.prompt('Bookmark Name', 'Please enter a name for your bookmark.', function(btn, text) {
      if (btn == 'ok') {
        //var currentMarker = currentClick;
        var currExtent = map.extent;
        bookmarkData.bookmarks.push(
          {
            id: Math.random(),
            name: text,
            xmin: currExtent.xmin.toFixed(4),
            ymin: currExtent.ymin.toFixed(4),
            xmax: currExtent.xmax.toFixed(4),
            ymax: currExtent.ymax.toFixed(4),
            result: currentMarker
          }
        );
        reloadBookmarkData();
      }
    }, this, false, defaultText);
  }

  // Delete store data and update cookie for persistence
  function deleteBookmarks() {
    var toDelete = bookmarkDataView.getSelectedIndexes();
    for (i = 0; i < toDelete.length; i++) {
      bookmarkData.bookmarks.splice(toDelete[i], 1);
    }
    reloadBookmarkData();
  }

  //  // Reposition the window when displayed
  //  bookmarkWindow.on('show',function(){
  //    var xOffset = Ext.getCmp('masterViewport').getBox().width - bookmarkWindow.width - 5;
  //    var yOffset = 245;
  //    bookmarkWindow.setPosition(
  //      [parseInt(xOffset),yOffset]
  //    );
  //    bookmarkWindow.setActive(true);
  //  });  

  var isInit = false;

  return {

    isInitialized: isInit,

    /// Set the current marker so if the user saves a bookmark, they will get the marker
    /// @param {point} esri.geometry.Point The current point
    setLocation: function(point) {
      currentMarker = point;
    },

    setDefaultText: function(text) {
      defaultText = text;
    },

    // Show bookmark window, initialize first if it's not initialized
    show: function() {
      if (!isInit) {
        this.init();
      }
      bookmarkWindow.show();
    },

    init: function() {
      if(isInit) { return; }
      isInit = true;

      bookmarkData = {
        bookmarks: []
      };

      bookmarkStore = new Ext.data.JsonStore({
        storeId: 'bookmarkStore',
        root: 'bookmarks',
        idProperty: 'id',
        fields: [
          'id',
          'name',
          { name: 'xmin', type: 'float' },
          { name: 'ymin', type: 'float' },
          { name: 'xmax', type: 'float' },
          { name: 'ymax', type: 'float' },
          { name: 'result', type: Ext.data.Types.ESRIPOINT }
        ]
      });

      bookmarkTemplate = new Ext.XTemplate(
        '<tpl for=".">',
          '<table class="bookmark-item-selector">',
            '<tr>',
              '<td rowspan="2" width="50"><img src="images/icons/large/i_bookmark.png"/></td>',
              '<td width="220">{name}</td>',
            '</tr>',
          '</table>',
        '</tpl>'
      );

      bookmarkDataView = new Ext.DataView({
        store: bookmarkStore,
        tpl: bookmarkTemplate,
        autoHeight: true,
        trackOver: true,
        multiSelect: true,
        itemSelector: 'table.bookmark-item-selector',
        overClass: 'dataview-over',
        selectedClass: 'dataview-selected',
        emptyText: 'No bookmarks found.',
        autoScroll: true,
        listeners: {
          click: {
            fn: function(dataview, index, node, e) {
              // Get the associated record for the click event
              var selectedExtent = bookmarkStore.getAt(index).data;
              // If there is a marker, we need to recreate it
              if (selectedExtent.result != null) {
                Mapping.Ext.Esri.Marker.reset().setTitle(selectedExtent.name);
                //showLocation(selectedExtent.result);
                findParcelByPoint(selectedExtent.result);
              } else if (Mapping.Ext.Esri.Marker != null) {
                Mapping.Ext.Esri.Marker.reset();
              }

              var esriExtent = new esri.geometry.Extent(
  			        selectedExtent.xmin,
  			        selectedExtent.ymin,
  			        selectedExtent.xmax,
  			        selectedExtent.ymax,
  			        defaultSpatialReference
  			      );
              map.setExtent(esriExtent);
            }
          },
          afterRender: {
            fn: function(dataview) {
              loadBookmarkData();
            }
          }
        }
      });

      bookmarkWindow = new Ext.Window({
        header: true,
        title: 'Bookmarks',
        closable: true,
        closeAction: 'hide',
        collapsible: true,
        id: 'bookmarkWindow',
        width: 283,
        height: 160,
        plain: false,
        frame: true,
        shadow: false,
        autoScroll: true,
        bbar: [
	          '->',
            {
              tooltip: 'New Bookmark',
              iconCls: 'bookmarkButton',
              scale: 'medium',
              handler: createNewBookmark
            },
            '-',
            {
              tooltip: 'Delete Selected',
              iconCls: 'deleteButton',
              scale: 'medium',
              handler: deleteBookmarks
            }
	        ],
        items: bookmarkDataView
      });

      // Reposition the window when displayed
      bookmarkWindow.on('show', function() {
        var xOffset = Ext.getCmp('masterViewport').getBox().width - bookmarkWindow.width - 5; // 8; 
        var yOffset = 305; // Ext.getCmp('masterViewport').getBox().height - bookmarkWindow.height - 33; 
        bookmarkWindow.setPosition(
          [parseInt(xOffset), yOffset]
        );
        bookmarkWindow.setActive(true);
      });
    }
  };
} ();


