/*
 * Copyright (c) 2006 Jonathan Weiss <jw@innerewut.de>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */


/* tooltip-0.1.js - Small tooltip library on top of Prototype 
 * by Jonathan Weiss <jw@innerewut.de> distributed under the BSD license. 
 *
 * Unlike other libraries it does not declare its own tooltip 
 * div or window. It relies on an already existing div or element defined by you to display as 
 * the tooltip. This element will be placed (and shown) near the mouse pointer when a trigger-element is moused-over.
 * 
 *
 * Usage: 
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *   <script type="text/javascript">
 *     var my_tooltip = new Tooltip('id_of_trigger_element', 'id_of_tooltip_to_show_element')
 *   </script>
 * 
 * Now whenever you trigger a mouseOver on the `trigger` element, the tooltip element will
 * be shown. On o mouseOut the tooltip disappears. 
 * 
 * Example:
 * 
 *   <script src="/javascripts/prototype.js" type="text/javascript"></script>
 *   <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
 *   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
 *
 *   <div id='tooltip' style="display:none; margin: 5px; background-color: red;">
 *     Detail infos on product 1....<br />
 *   </div>
 *
 *   <div id='product_1'>
 *     This is product 1
 *   </div>
 *
 *   <script type="text/javascript">
 *     var my_tooltip = new Tooltip('product_1', 'tooltip')
 *   </script>
 *
 * You can use my_tooltip.destroy() to remove the event observers and thereby the tooltip.
 */

var Tooltip = Class.create();
Tooltip.prototype = {
  initialize: function(element, type, givenurl_or_tooltipid) {
    var options = Object.extend({
      default_css: false,
      margin: "0px",
	  padding: "5px",
	  backgroundColor: "#d6d6fc",
	  delta_x: 5,
	  delta_y: 5,
	  zindex: 1000
    }, arguments[1] || {});

	/*this._blank = Builder.node("div", { id: "_blank", style:"background-color:blue;"},[
																 Builder.build("<span>2222</span>"),
																 ]);*/
    this.element      = $(element)//this._blank//(!element)? this._blank  : $(element);
	//dumpProps();
	this.icon = '<img src="/images/info.gif" border="0"><br>info';

		if (type == 1){
			/*this.tool_tip = Builder.node("div", { id: "tooltip", style:"background-color:blue;"},[
																 Builder.build("<span>2222</span>"),
																 ]);		*/
			
			
		this.tool_tip = Builder.node("div", {id: "tooltip", style: "display: none; text-align:left"}, [
			this.MBframe = Builder.node("div", {id: "PT_Frame"}, [
				this.MBheader = Builder.node("div", {id: "PT_header"}, [
					//this.MBcaption = Builder.node("div", {id: "MB_caption"}),
					this.MBclose = Builder.node("a", {id: "PT_close", title: "Close window", href: "#"}, [
						Builder.build("<span>&times; CLOSE &times;</span>"),
					]),
				]),
				this.MBcontent = Builder.node("div", {id: "PT_content"}, [
					this.tool_tip_content = Builder.node("div", {id: "tooltipc"}, Builder.build("<span>&nbsp;</span>")),//CSmall: allowing loadingstring to be html
					//this.MBloading = Builder.build("<span>"+this.options.loadingString+"</span>"),
				]),
			]),
		]);
			
			
			
			this.ajax_url     = givenurl_or_tooltipid;
			this.element.innerHTML = (givenurl_or_tooltipid == '' )? '':this.icon;//check for inline tip
				//
			

		} else {
			this.orgi_tip     = $(givenurl_or_tooltipid);
			this.element.innerHTML = (this.orgi_tip.innerHTML == '' )? '':this.icon;//check for inline tip

			this.tool_tip = Builder.node("div", {id: "tooltip", style: "display: none; text-align:left"}, [
			this.MBframe = Builder.node("div", {id: "PT_Frame"}, [
				this.MBheader = Builder.node("div", {id: "PT_header"}, [
					//this.MBcaption = Builder.node("div", {id: "MB_caption"}),
					this.MBclose = Builder.node("a", {id: "PT_close", title: "Close window", href: "#"}, [
						Builder.build("<span>&times; CLOSE &times;</span>"),
					]),
				]),
				this.MBcontent = Builder.node("div", {id: "PT_content"}, [
					this.tool_tip_content = Builder.node("div", {id: "tooltipc"}, Builder.build("<span>"+this.orgi_tip.innerHTML+"</span>")),//CSmall: allowing loadingstring to be html
					//this.MBloading = Builder.build("<span>"+this.options.loadingString+"</span>"),
				]),
			]),
		]);
			
		}
		
		
		
    //
	
	this.changecursor('help');
    this.options      = options;
    // hide the tool-tip by default
	

    //this.tool_tip.hide();
	this.tool_tip.style.display = 'none'

    this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
	
    this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
		    
	this.bodyelement =document.getElementsByTagName("body").item(0);

    this.registerEvents();
  },
	changecursor: function(type){
		this.element.style.cursor = type;
	},
	
  destroy: function() {
	  
    Event.stopObserving(this.element, "click", this.eventMouseOver);
    Event.stopObserving(this.tool_tip_content, "mouseout", this.eventMouseOut);
	   // Event.stopObserving(this.tool_tip, "click", this.eventMouseOut);
		Event.stopObserving(this.bodyelement, "dblclick", this.eventMouseOut);
		Event.stopObserving(this.MBclose, "click", this.eventMouseOut);
		
  },

  registerEvents: function() {
	  
    Event.observe(this.element, "click", this.eventMouseOver);
	Event.observe(this.bodyelement, "dblclick", this.eventMouseOut);
    Event.observe(this.tool_tip_content, "mouseout", this.eventMouseOut);
	Event.observe(this.MBclose, "click", this.eventMouseOut);
  },
  loadcontent: function(){
	 // alert(this.ajax_url)
	 document.body.insertBefore(this.tool_tip, document.body.childNodes[0]);
	  new Ajax.Request(this.ajax_url, {
					   parameters:'', 
					   onComplete: function(originalRequest) {
							var response = new String(originalRequest.responseText);
							this.tool_tip_content.innerHTML = response;
							this.element.title = response;
							//alert(response)
						}.bind(this)
					   });
  },
  showTooltip: function(event){
	  
	Event.stop(event);
	//dumpProps(event);
	// get Mouse position
    var mouse_x = Event.pointerX(event);
	var mouse_y = Event.pointerY(event);
	
	
	// decide if wee need to switch sides for the tooltip
	var dimensions = Element.getDimensions( this.tool_tip );
	var element_width = dimensions.width;
	var element_height = dimensions.height;
	
	if ( (element_width + mouse_x) >= ( this.getWindowWidth() - this.options.delta_x) ){ // too big for X
		mouse_x = mouse_x - element_width;
		// apply delta to make sure that the mouse is not on the tool-tip
		mouse_x = mouse_x - this.options.delta_x;
	} else {
		mouse_x = mouse_x + this.options.delta_x;
	}
	
	if ( (element_height + mouse_y) >= ( this.getWindowHeight() - this.options.delta_y) ){ // too big for Y
		mouse_y = mouse_y - element_height;
	    // apply delta to make sure that the mouse is not on the tool-tip
		mouse_y = mouse_y - this.options.delta_y;
	} else {
		mouse_y = mouse_y + this.options.delta_y;
	} 
	
	// now set the right styles
	this.setStyles(mouse_x, mouse_y);
	//this.tool_tip.innerHTML = this.content;
	
		//alert(this.tool_tip.innerHTML)
		//this.tool_tip.hide();
		this.loadcontent();
	// finally show the Tooltip
	//new Effect.BlindDown(this.tool_tip);
	new Effect.Appear(this.tool_tip);
	//new Element.show(this.tool_tip);

  },
  
  setStyles: function(x, y){
    // set the right styles to position the tool tip
	Element.setStyle(this.tool_tip, { position:'absolute',
	 								  top:y + "px",
	 								  left:x + "px",
									  width:"300px",
									  backgroundColor:this.options.backgroundColor,
									  zindex:this.options.zindex
	 								});
	
	// apply default theme if wanted
	if (this.options.default_css){
	  	Element.setStyle(this.tool_tip, { margin:this.options.margin,
		 								  padding:this.options.padding,
		                                  backgroundColor:this.options.backgroundColor,
										  zindex:this.options.zindex
		 								});	
	}	
  },

  hideTooltip: function(event){
	new Effect.Fade(this.tool_tip);
	new Effect.BlindUp(this.tool_tip);
	//new Element.hide(this.tool_tip);

},
 
  getWindowHeight: function(){
    var innerHeight;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerHeight = document.body.clientHeight;
    } else {
		innerHeight = window.innerHeight;
    }
    return innerHeight;	
  },
 
  getWindowWidth: function(){
    var innerWidth;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerWidth = document.body.clientWidth;
    } else {
		innerWidth = window.innerWidth;
    }
    return innerWidth;	
  }

}

function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
	  //document.write(msg);
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
   }
}

	  function tp_init(the){
//		   setTimeout("alert(2000)",6000);
		match_class = new RegExp("^(.*)\s?poptip\s?(.*)$", 'i');
	   	String.prototype.trim = function() {
			a = this.replace(/^\s+/, '');
			return a.replace(/\s+$/, '');
		};

		var divs = document.getElementById(the).getElementsByTagName('div');
		//alert(document.getElementById(the))
		//alert(document.getElementById('content').innerHTML)
		//alert(document.getElementsByTagName("body"))
		for (var i = 0; i < divs.length; i++) {
			if (divs.item(i).className.match(match_class)) {
				//alert(divs.item(i).className)
				
				var tipid = divs.item(i).title;
				var attrib = document.getElementById(tipid)
				
				//alert(divs.item(i).title)
				//alert(attrib.className)
				//alert(attrib.innerHTML)
				var url_id = (attrib.className == 1)? attrib.innerHTML:divs.item(i).title
				//if (type){
					//alert(url_id.trim());
					//Tooltip.prototype._test(url_id.trim());
				//} else {
					new Tooltip(divs.item(i).id,attrib.className,url_id.trim())
				//}
			} 
		
		}
		
	  }
