/*!
 * jQuery.blockLink
 *
 * @projectDescription Simple utility which makes hoverable/clickable whole block if contains some link.
 * @author Jiri Prokop
 * @version 0.1
 *
 * @id jQuery.blockLink
 * @id jQuery.fn.blockLink
 * @param {Object} settings Hash of settings, nothing is required.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 */

(function($) {
  var BlockLink = function(element, options) {
    // private fields and shortcuts
    var $elem = $(element);
    var me = this;
    var settings = $.extend({
      blockLinkClass: 'blockLink'
    }, options || {});
    
    // private methods
    var initialize = function() {
      var attrNames = ['id', 'class', 'href', 'target', 'title'];
      var anchorAttrs = {};
      var newAnchorAttrs = {};
      var $a = $elem.find('a:first');
      
      // preparation of attributes for new anchor from the old one
      for (var i = 0; i < attrNames.length; i++) {
        var name = attrNames[i];
        var value = $a.attr(name);
        
        if (typeof value !== 'undefined') {
          anchorAttrs[name] = value;
        }
      }
      
      // removing of all anchors inside because of avoiding conflicts
      $elem.find('a').replaceWith(function() {
        return $(this).contents();
      });

      // what's set in settings have priority 
      $.extend(newAnchorAttrs, anchorAttrs, settings);
      // alt is the same as title but title have to be on original anchor set
      newAnchorAttrs['alt'] = newAnchorAttrs['title'];
      // removing nonexistent attribute used for blockLink (because of styling in CSS)
      delete newAnchorAttrs['blockLinkClass'];
      
      // wrapping whole block with new anchor
      $newAnchor = $('<a>').attr(newAnchorAttrs).addClass(settings.blockLinkClass);
      $elem.wrap($newAnchor);
    };
    
    // initialize
    initialize();
  };

  $.fn.blockLink = function(options) {
    return this.each(function() {
      var $elem = $(this);
      var key = 'blockLink';
      var data = $elem.data(key);
      var instanceExists = false;
      var localOptions = $.extend({}, options);
      
      if (typeof data !== 'undefined' && data instanceof BlockLink) {
        instanceExists = true;
      } else if (typeof data === 'object') {
        // options from html data-element are merged together with options of plugin when initializing
        localOptions = $.extend({}, data, options);
      }
      
      if (!instanceExists) {
        $elem.data(key, new BlockLink(this, localOptions));
      }
    });
  };
})(jQuery);
