/*
 * Plugin - shows a tooltip defined somewhere
 * If 'destinationTooltipContainer' is given the tooltip container will first be moved in the DOM to be appended destination element.
 * Adds a click listener to the 'abbreviationContentSelector' element and guarantees a mutual exclusive visibility of teh tooltips.
 *
 *
 * @author OstrickiDa
*/
(function(){
  // Constructor
  (MoreTooltipHandler = function(element, options) {
    this.rootElement = jQuery(element);
    // Merge options with default values
    this.settings = jQuery.extend({}, this.defaultValues, options || {});
    this.init();
  }).prototype = {

	tooltipContainer : null,
	abbreviationContainer : null,
	destinationTooltipContainer : null,

	instanceId : null,

    defaultValues : {
    	'abbreviationContentSelector' : '.AbbreviationContent',
    	'originalContentSelector' : '.OriginalContent',
		'tooltipContentSelector' : '.TooltipContent',
		'destinationTooltipContainer' : '',

		'position' : {
    		'right' : {
	    		'positionOffsetX' : 40,
	    		'positionOffsetY' : -30
    		},
    		'left' : {
	    		'positionOffsetX' : -40,
	    		'positionOffsetY' : -30
    		}
    	}
    },

    /* ****************************************************************
     * 						initialization
     * ***************************************************************/

    init : function() {
    	this.instanceId = Math.floor((Math.random()*64000)+1);//1-64000

    	this.tooltipContainer = this.lookupUniqueElement(this.rootElement,this.settings['tooltipContentSelector']);
    	this.abbreviationContainer = this.lookupUniqueElement(this.rootElement,this.settings['abbreviationContentSelector']);
    	this.originalContentContainer = this.lookupUniqueElement(this.rootElement,this.settings['originalContentSelector']);

    	this.destinationTooltipContainer = jQuery(this.settings['destinationTooltipContainer']);


    	if(this.tooltipContainer && this.abbreviationContainer){
    		if(this.destinationTooltipContainer){
    			this.destinationTooltipContainer.append(this.tooltipContainer);
    		}
    		this.attachListeners();
    	}
    },


    attachListeners : function () {

    	this.abbreviationContainer.on('click',jQuery.proxy(this.show, this));

    	this.tooltipContainer.on('mousedown mouseup touchstart touchend onmsgesturestart onmsgestureend',
    			jQuery.proxy(function(event){
//		    		this.log('event on tooltip -> stopping propagation '+event.type);
		    		event.stopPropagation();
		  	  	},this));

    	this.tooltipContainer.on('click',
    			jQuery.proxy(function(event){
//		    		this.log('clicked on tooltip -> stopping propagation and hiding '+event.type);
		    		this.hide();
		    		event.stopPropagation();
		  	  	},this));


    	jQuery(document).on('click touchstart onmsgesturestart',  jQuery.proxy(this.hide, this));

    	jQuery(document).on('event:abbrevationOpened',  jQuery.proxy(this.abbrevationOpenedEvent, this));
    },


    /* ****************************************************************
     * 							events
     * ***************************************************************/

    show : function (event) {
    	if(this.tooltipContainer.is(':visible')){
    		this.hide();
    	}else{
    		this.positionToTheRight();
        	this.tooltipContainer.show( 'fade', {}, 300, null);

        	if(!this.elementFullyVisibleInViewport(this.tooltipContainer)){
        		this.positionToTheLeft();
        	}

        	jQuery(document).trigger("event:abbrevationOpened",[this.instanceId]);
    	}
    	event.stopPropagation();
    },

    hide : function () {
    	this.tooltipContainer.hide( 'fade', {}, 300, null);
    },

    abbrevationOpenedEvent : function(event, openerInstanceId){
    	if(this.instanceId == openerInstanceId){
    		return;
    	}
    	this.log('another tooltip opened with id '+openerInstanceId + ' / this instance id is' + this.instanceId );
    	this.hide();
    },


    /* ****************************************************************
     * 						  help functions
     * ***************************************************************/

    lookupUniqueElement : function (parent,selector) {
    	var elems = parent.find(selector);
    	return (elems.length == 0) ? null : jQuery(elems.get(0));
    },

    positionToTheLeft : function() {
    	var posTrigger = this.abbreviationContainer.offset().left;
    	var tooltipWidth = this.tooltipContainer.outerWidth(true);

    	var relativeXOffset = parseInt(this.settings['position']['left']['positionOffsetX']);
    	var x = posTrigger + relativeXOffset - tooltipWidth;
    	this.tooltipContainer.css({'left': x+'px'});

    	var relativeYOffset = parseInt(this.settings['position']['left']['positionOffsetY']);
   	 	var scrollTopDoc = jQuery(document).scrollTop();
 		var y = this.abbreviationContainer.offset().top + relativeYOffset - scrollTopDoc;
     	this.tooltipContainer.css({'top': y+'px'});
    },

    positionToTheRight : function() {
    	 var relativeXOffset = parseInt(this.settings['position']['right']['positionOffsetX']);
    	 var relativeYOffset = parseInt(this.settings['position']['right']['positionOffsetY']);

     	 var x = this.abbreviationContainer.offset().left + relativeXOffset;;
     	 this.tooltipContainer.css({'left': x+'px'});

     	 var scrollTopDoc = jQuery(document).scrollTop();
 		 var y = this.abbreviationContainer.offset().top + relativeYOffset - scrollTopDoc;
     	 this.tooltipContainer.css({'top': y+'px'});
    },

    elementFullyVisibleInViewport : function (el) {
	  var windowWidth = jQuery(window).width();
	  var elemPos = el.offset().left;
	  var elemWidth = el.outerWidth();
	  return (elemPos + elemWidth) < windowWidth;
    },

    log : function (msg) {
    	if(window.console && window.console.log){
			window.console.log(msg);
		}
    }

  };

  jQuery.fn.moreTooltip = function(options) {
    return this.each(function() {
      var element = jQuery(this);
      // Return early if this element already has a plugin instance
      if (element.data('moreTooltipHandler')) {
        return;
      }
      // Store plugin object in this element's data
      element.data('moreTooltipHandler', new MoreTooltipHandler(this, jQuery.extend({}, options)));
    });
  };
})();
//
////
