
/**
 * @file
 * Layer handler for XYZ layers
 */

/**
 * Openlayer layer handler for XYZ layer
 */
Drupal.openlayers.layer.xyz = function(title, map, options) {
  var styleMap = Drupal.openlayers.getStyleMap(map, options.drupalID);
  if (options.maxExtent !== undefined) {
    options.maxExtent = new OpenLayers.Bounds.fromArray(options.maxExtent) || new OpenLayers.Bounds(-20037508.34, -20037508.34, 20037508.34, 20037508.34);
  }
  options.projection = 'EPSG:' + options.projection;
  
  // Server resolutions are very particular in OL 2.11
  var r = options.serverResolutions;
  if (r == null || typeof r == 'undefined' || r.length == 0) {
    options.serverResolutions = null;
  }
  
  // Wrap Date Line does not seem to work for 2.10.  This may
  // have something to do with our extent definitions.
  if (OpenLayers.VERSION_NUMBER.indexOf('2.10') >= 0) {
    options.wrapDateLine = null;
  }

  var layer = new OpenLayers.Layer.XYZ(title, options.url, options);
  layer.styleMap = styleMap;
  return layer;
};;

/**
 * @file
 * Layer handler for TMS layers
 */

/**
 * Openlayer layer handler for TMS layer
 */
Drupal.openlayers.layer.tms = function(title, map, options) {
  var styleMap = Drupal.openlayers.getStyleMap(map, options.drupalID);
  options.isBaseLayer = options.baselayer;
    if (options.maxExtent !== undefined) {
      options.maxExtent = new OpenLayers.Bounds.fromArray(options.maxExtent);
    }
    options.projection = 'EPSG:' + options.projection;
    var layer = new OpenLayers.Layer.TMS(title, options.base_url, options);
    layer.styleMap = styleMap;
    return layer;
};
;

/**
 * OpenLayers Views Vector Layer Handler
 */
Drupal.openlayers.layer.openlayers_views_vector = function(title, map, options) {
  // Note, so that we do not pass all the features along to the Layer
  // options, we use the options.options to give to Layer
  options.options.drupalID = options.drupalID;
  
  // Create projection
  options.projection = new OpenLayers.Projection('EPSG:'+options.projection);
  // Get style map
  options.options.styleMap = Drupal.openlayers.getStyleMap(map, options.drupalID);
  // Create layer object
  var layer = new OpenLayers.Layer.Vector(title, options.options);
  
  // Add fetures if there are any
  if (options.features) {
    Drupal.openlayers.addFeatures(map, layer, options.features);
  }
  
  return layer;
};
;
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */

/**
 * ZoomPanel Behavior
 */
Drupal.openlayers.addBehavior('openlayers_behavior_zoompanel', function (data, options) {
  Drupal.openlayers.addControl(data.openlayers, 'ZoomPanel');
});
;
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */

/**
 * Navigation Behavior
 */
Drupal.openlayers.addBehavior('openlayers_behavior_navigation', function (data, options) {
  options.documentDrag = !!options.documentDrag;
  Drupal.openlayers.addControl(data.openlayers, 'Navigation', options);
});
;
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */
 
/**
 * ArgParser Behavior.  Implements the ArgParser OpenLayers
 * Control.
 */
Drupal.openlayers.addBehavior('openlayers_behavior_argparser', function (data, options) {
  Drupal.openlayers.addControl(data.openlayers, 'ArgParser');
});
;
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */

/**
 * Javascript Drupal Theming function for inside of Popups
 *
 * To override
 *
 * @param feature
 *  OpenLayers feature object.
 * @return
 *  Formatted HTML.
 */
Drupal.theme.prototype.openlayersPopup = function(feature) {
  var output = '';
  
  if (feature.attributes.name) {
    output += '<div class="openlayers-popup openlayers-tooltip-name">' + feature.attributes.name + '</div>';
  }
  if (feature.attributes.description) {
    output += '<div class="openlayers-popup openlayers-tooltip-description">' + feature.attributes.description + '</div>';
  }
  
  return output;
};

// Make sure the namespace exists
Drupal.openlayers.popup = Drupal.openlayers.popup || {};

/**
 * OpenLayers Popup Behavior
 */
Drupal.openlayers.addBehavior('openlayers_behavior_popup', function (data, options) {
  var map = data.openlayers;
  var layers = [];

  // For backwards compatiability, if layers is not
  // defined, then include all vector layers
  if (typeof options.layers == 'undefined' || options.layers.length == 0) {
    layers = map.getLayersByClass('OpenLayers.Layer.Vector');
  }
  else {
    for (var i in options.layers) {
      var selectedLayer = map.getLayersBy('drupalID', options.layers[i]);
      if (typeof selectedLayer[0] != 'undefined') {
        layers.push(selectedLayer[0]);
      }
    }
  }

  var popupSelect = new OpenLayers.Control.SelectFeature(layers,
    {
      onSelect: function(feature) {
        // Create FramedCloud popup.
        popup = new OpenLayers.Popup.FramedCloud(
          'popup',
          feature.geometry.getBounds().getCenterLonLat(),
          null,
          Drupal.theme('openlayersPopup', feature),
          null,
          true,
          function(evt) {
            Drupal.openlayers.popup.popupSelect.unselect(
              Drupal.openlayers.popup.selectedFeature
            );
          }
        );

        // Assign popup to feature and map.
        feature.popup = popup;
        feature.layer.map.addPopup(popup);
        Drupal.attachBehaviors();
        Drupal.openlayers.popup.selectedFeature = feature;
      },
      onUnselect: function(feature) {
        // Remove popup if feature is unselected.
        feature.layer.map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
      }
    }
  );

  map.addControl(popupSelect);
  popupSelect.activate();
  Drupal.openlayers.popup.popupSelect = popupSelect;
});
;
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */

/**
 * Z Maps OL Behavior: Auto Popup
 */
(function($) {
  Drupal.behaviors.zmaps_auto_popup = {
    'attach': function(context, settings) {
      var data = $(context).data('openlayers');
      if (data && data.map.behaviors['zmaps_auto_popup']) {
        var options = data.map.behaviors['zmaps_auto_popup'];
        var map = data.openlayers;

        // Find select control
        var control = map.getControlsByClass('OpenLayers.Control.SelectFeature');
        control = (control.length > 0) ? control[0] : null;

        // Get the selected layers
        for (var i in options.layers) {
          if (options.layers[i]) {
            var selectedLayer = map.getLayersBy('drupalID', i);
            if (typeof selectedLayer[0] != 'undefined' && 
              typeof selectedLayer[0].features != 'undefined') {
              
              // Clone features and get the last one.
              var features = $.extend(true, [], selectedLayer[0].features);
              if (features.length > 0) {
                var feature = features.pop();
                
                if (control) {
                  map.zoomTo(parseFloat(options.zoom));
                  map.setCenter(feature.geometry.getBounds().getCenterLonLat());
                  map.moveByPx(parseFloat(options.offset_x), parseFloat(options.offset_y));
                  control.unselectAll();
                  control.clickFeature(feature);

                  // For zoom changer, call custom event.  Unfortunately
                  // the behavior is added after this because it is
                  // alphabetically before it in the file system.  :(
                  var t = setTimeout(function() {
                    $(map.div).trigger('zmap_zoom_change');
                  }, 500);
                }
              }
            }
          }
        }
      }
    },
  };
})(jQuery);
;


// Sorry...

/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.6
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

if ($.event.fixHooks) {
    for ( var i=types.length; i; ) {
        $.event.fixHooks[ types[--i] ] = $.event.mouseHooks;
    }
}

$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },
    
    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};

$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },
    
    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});


function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    
    // Old school scrollwheel delta
    if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta/120; }
    if ( orgEvent.detail     ) { delta = -orgEvent.detail/3; }
    
    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;
    
    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }
    
    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
    
    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);
    
    return ($.event.dispatch || $.event.handle).apply(this, args);
}

})(jQuery);




/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */
(function($) {

/**
 * Zoom Layer Changer
 */
Drupal.openlayers.addBehavior('zmaps_zoom_layer_changer', function (data, options) {
  var olMap = data.openlayers;

  // Function to change base layer
  changeBase = function(event, timeout) {
    timeout = parseInt(timeout) || 500;
  
    // Yay, more hacks.  We have to wait a moment
    // as this often gets fired before the map
    // updates its zoom level.
    var t = setTimeout(function() {
      var zoom = olMap.getZoom();
      var center = olMap.getCenter();
      
      if (typeof options.zooms[olMap.zoom] != 'undefined') {
        var layers = olMap.getLayersBy('drupalID', options.zooms[olMap.zoom]);
  
        if (typeof layers[0] != 'undefined' && layers[0] != olMap.baseLayer) {
          olMap.setBaseLayer(layers[0]);
          olMap.setCenter(center, zoom);
        }
      }
    }, timeout);
  };

  // We utilize jQuery events :(.  Unfortunately
  // setting the base layer calls a re-center which would call
  // a zoomend again (infinite loop), so we cant use that and
  // there is no real other way, as the OL library doesn't
  // seem to allow for events like mousewheel.
  //
  // Also add custom event for those edge cases.
  $(olMap.div).bind({
    mousewheel: changeBase,
    dblclick: changeBase,
    click: changeBase,
    zmap_zoom_change: changeBase
  });
  $('.olControlZoomInItemInactive, ' + 
    '.olControlZoomToMaxExtentItemInactive, ' +
    '.olControlZoomOutItemInactive').bind({
    dblclick: changeBase,
    click: changeBase
  });
});

})(jQuery);;
/**
 * @file
 * JS Implementation of OpenLayers behavior.
 */

/**
 * Z Maps OL Behavior: Feature Highlighter
 */
(function($) {
  Drupal.behaviors.zmaps_feature_highlight = {
    'attach': function(context, settings) {
      var data = $(context).data('openlayers');
      if (data && data.map.behaviors['zmaps_feature_highlight']) {
        var options = data.map.behaviors['zmaps_feature_highlight'];
        var map = data.openlayers;
        var layers = [];
        var idCount = 0;
        
        // Find select control
        var control = map.getControlsByClass('OpenLayers.Control.SelectFeature');
        control = (control.length > 0) ? control[0] : null;

        // Get the selected layers
        for (var i in options.layers) {
          if (options.layers[i].enabled) {
            var selectedLayer = map.getLayersBy('drupalID', i);
            if (typeof selectedLayer[0] != 'undefined') {
              
              // Now, add the link between items and feature
              $(options.layers[i].container).each(function() {
                var $container = $(this);
                var sendData = jQuery.extend({}, options.layers[i]);;
                idCount++;
                
                // Get and Attach data to element
                sendData.containerClass = 'zmapsHighligher-' + idCount;
                sendData.toMatch = $container.find(sendData.feature_search).html();
                sendData.feature = selectedLayer[0].getFeaturesByAttribute(sendData.attribute, sendData.toMatch);
                sendData.feature = (sendData.feature) ? sendData.feature[0] : null;
                $container.addClass(sendData.containerClass);
                $container.find(sendData.link).data('zmapsOLFeature', sendData);
                
                // Click event
                $container.find(sendData.link).click(function(e) {
                  // Make sure we are not taken anywhere.
                  e.preventDefault();
                  
                  // Add class incase some styling is needed.  Also, take away any
                  // other styling
                  $('.zmaps-feature-highlight-link-activated')
                    .removeClass('zmaps-feature-highlight-link-activated');
                  $(this).addClass('zmaps-feature-highlight-link-activated');
                  
                  // Handle opening up popup
                  var elementData = $(this).data('zmapsOLFeature');
                  if (typeof elementData.feature != 'undefined' && elementData.feature) {
                    if (control) {
                      map.zoomTo(parseFloat(elementData.zoom));
                      //map.panTo(elementData.feature.geometry.getBounds().getCenterLonLat());
                      map.setCenter(elementData.feature.geometry.getBounds().getCenterLonLat());
                      map.moveByPx(parseFloat(elementData.offset_x), parseFloat(elementData.offset_y));
                      control.unselectAll();
                      control.clickFeature(elementData.feature);
                      
                      // For zoom changer, call custom event.
                      $(map.div).trigger('zmap_zoom_change');
                    }
                  }
                });
              });
              
            }
          }
        }
      }
    },
  };
})(jQuery);
;
(function ($) {

$(document).ready(function() {

  // Accepts a string; returns the string with regex metacharacters escaped. The returned string
  // can safely be used at any point within a regex to match the provided literal string. Escaped
  // characters are [ ] { } ( ) * + ? - . , \ ^ $ # and whitespace. The character | is excluded
  // in this function as it's used to separate the domains names.
  RegExp.escapeDomains = function(text) {
    return (text) ? text.replace(/[-[\]{}()*+?.,\\^$#\s]/g, "\\$&") : '';
  }

  // Attach onclick event to document only and catch clicks on all elements.
  $(document.body).click(function(event) {
    // Catch the closest surrounding link of a clicked element.
    $(event.target).closest("a,area").each(function() {

      var ga = Drupal.settings.googleanalytics;
      // Expression to check for absolute internal links.
      var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
      // Expression to check for special links like gotwo.module /go/* links.
      var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
      // Expression to check for download links.
      var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
      // Expression to check for the sites cross domains.
      var isCrossDomain = new RegExp("^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\/.*(" + RegExp.escapeDomains(ga.trackCrossDomains) + ")", "i");

      // Is the clicked URL internal?
      if (isInternal.test(this.href)) {
        // Is download tracking activated and the file extension configured for download tracking?
        if (ga.trackDownload && isDownload.test(this.href)) {
          // Download link clicked.
          var extension = isDownload.exec(this.href);
          _gaq.push(["_trackEvent", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
        }
        else if (isInternalSpecial.test(this.href)) {
          // Keep the internal URL for Google Analytics website overlay intact.
          _gaq.push(["_trackPageview", this.href.replace(isInternal, '')]);
        }
      }
      else {
        if (ga.trackMailto && $(this).is("a[href^=mailto:],area[href^=mailto:]")) {
          // Mailto link clicked.
          _gaq.push(["_trackEvent", "Mails", "Click", this.href.substring(7)]);
        }
        else if (ga.trackOutbound && this.href) {
          if (ga.trackDomainMode == 2 && isCrossDomain.test(this.href)) {
            // Top-level cross domain clicked. document.location is handled by _link internally.
            _gaq.push(["_link", this.href]);
          }
          else if (ga.trackOutboundAsPageview) {
            // Track all external links as page views after URL cleanup.
            // Currently required, if click should be tracked as goal.
            _gaq.push(["_trackPageview", '/outbound/' + this.href.replace(/^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\//i, '').split('/').join('--')]);
          }
          else {
            // External link clicked.
            _gaq.push(["_trackEvent", "Outbound links", "Click", this.href]);
          }
        }
      }
    });
  });
});

})(jQuery);
;

