﻿if(!AP)
  var AP = new Object();
AP.ToolTip_IFrame = document.createElement("IFRAME");
AP.ToolTipOptionCache = new Object();
AP.ToolTips = new Object();

AP.ToolTipOptionCache["mouse"] = {align: "mouse"};
AP.ToolTipOptionCache["page"] = {align: "page"};
AP.ToolTipOptionCache["timezone"] = {maxWidth:500};
AP.ToolTipOptionCache["pmtc"] = {className: "toolTip_pmtc_"};
AP.ToolTipOptionCache["photocell"] = {
	placement: "top-*"
};
AP.ToolTipOptionCache["hit"] = {
	placement: "*-right",
	maxWidth: 138,
	className: "searchHitMenu_",
	action: "click",
	isResuable: false,
	formatNode: FormatSearchHitMenu,
	//onClose: SearchHitMenu_OnClose,
	onOpen: SearchHitMenu_OnOpen
};
AP.ToolTipOptionCache["hit1up"] = { align: "mouse" };
Object.extend(AP.ToolTipOptionCache["hit1up"], AP.ToolTipOptionCache["hit"]);

AP.ToolTip_OnLoad = function(event, parent) {
  var fields = ["DIV", "A", "FIELDSET", "LABEL", "IMG", "INPUT", "SELECT", "SPAN"];
  
  AP.ToolTip_IFrame.style.position = "absolute";
  AP.ToolTip_IFrame.style.display = "none";
  AP.ToolTip_IFrame.style.zIndex = 10000;
  AP.ToolTip_IFrame.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=0)";
  AP.ToolTip_IFrame.frameBorder = 0;
  AP.ToolTip_IFrame.scrolling = "no";
  ($("__whitehole") || document.body).appendChild(AP.ToolTip_IFrame);
    
  //Position.includeScrollOffsets = true;
  for(var f=0; f<fields.length; f++) {
		var nodes = ($(parent) || document).getElementsByTagName(fields[f]);
		
		for(var i=0; i<nodes.length; i++) {
			var html;
			if((html = nodes[i].getAttribute("tooltip"))) {
				nodes[i].removeAttribute("tooltip")
				
				var tt = new AP.ToolTip(nodes[i], html);
				if(html.charAt(0) == '_')
					AP.ToolTips[html] = tt;
			}
		}
	}
}
Event.observe(window, "load", AP.ToolTip_OnLoad);

AP.ToolTip = Class.create();
AP.ToolTip.prototype = {
  initialize: function(node, html) {
		this.func = this.delayInit.bindAsEventListener(this, node, html);
    Event.observe(node, "mouseover", this.func);
  },
  
  delayInit: function(event, node, html) {
		var optionKey = node.getAttribute("tooltipmode");
		this.options = Object.extend({
			placement: "*-*",//vertical-horizontal
			windowPlacement: "top-left",//vertical-horizontal
			align: "node",//node|mouse|page|handle
			maxWidth: 300,
			showDelay: 800,
			hideDelay: 750,
			className: "toolTip_default_",
			action: "move",
			isResuable: true,
			autoHide: true,
			formatNode: Prototype.emptyFunction,
			onOpen: Prototype.emptyFunction,
			onClose: Prototype.emptyFunction
		}, AP.ToolTipOptionCache[optionKey] || {});
		
    this.isHovering = false;
    this.node = node;
    this.window = document.createElement("DIV");
    this.window.className = "toolTipWindow ";
    if(this.options.className)
			this.window.className = this.window.className + " " + this.options.className + "window";
    
    Element.hide(this.window);
		($("__whitehole") || document.body).appendChild(this.window);
    
		this.prepareContent(html);
		    
    var hw = Element.getDimensions(this.window);
    if(hw.width > this.options.maxWidth)
			this.window.style.width = this.options.maxWidth + "px";
		
    if(this.options.action == "move") {
			this.delayShow(event);//this was before the max width part...i dont rememerb why though...
			Event.observe(node, "mouseover", this.delayShow.bind(this));
			Event.observe(node, "mouseout", this.delayHide.bind(this));
			if(this.options.autoHide) {
				Event.observe(this.window, "mouseover", this.beginHover.bind(this));
				Event.observe(this.window, "mouseout", this.endHover.bind(this));
			}
		}
		else if(this.options.action == "click") {
			Event.observe(node, "click", this.show.bind(this));
			//Event.observe(this.window, "mousedown", this.hideAfterBlur.bind(this));
			//Event.observe(this.window, "blur", this.delayHide.bind(this));
			if(this.options.autoHide) {
				Event.observe(document, "click", this.hide.bind(this));
				var similarBar = $("sideBarContent");
				if(similarBar) {
					//Event.observe(similarBar, "scroll", this.hide.bind(this));
					Event.observe(similarBar, "scroll", this.position.bind(this));
				}
			}
		}
		
    Event.stopObserving(node, "mouseover", this.func);
		this.func = null;
  },
  
  prepareContent: function(tt) {
		var node;
		
		//if tooltip attribute starts with "_" consider it a node we are suppose to look for and clone
		if(tt.charAt(0) == '_' && (node = $(tt))) {
			//this.parentNode = node.parentNode;
			if(!this.options.isResuable) {
				node = node.cloneNode(true);
				node.id = null;
			}
			this.options.formatNode.call(this, this.node, node);
			this.window.appendChild(node);
			Element.show(node);//window is hidden so dont worry...
		}
		else
			this.window.innerHTML = tt.replace(/\n/g, "<BR />");
  },
  
  beginHover: function() {
    this.isHovering = true;
  },
  
  endHover: function() {
    this.isHovering = false;
    setTimeout(this.hide.bind(this), this.options.hideDelay);
  },
  
  delayShow: function(event) {
    this.isHovering = true;
    var x = Event.pointerX(event);
    var y = Event.pointerY(event);
    this.showTimerId = setTimeout(function(event) { this.show.call(this, event, x, y); }.bind(this), this.options.showDelay);
  },
  
  delayHide: function(event) {
    this.isHovering = false;
    this.hideTimerId = setTimeout(function(event) { this.hide.call(this, event); }.bind(this), this.options.hideDelay);
  },
  
  position: function(event, x, y) {
    var leftTop, hwNode;
    
    switch(this.options.align) {
    case "mouse":
			if(!x) {
				x = Event.pointerX(event);
				y = Event.pointerY(event);
			}
      leftTop = [x, y];
      hwNode = {height:0, width:0 };
      break;
    case "page":
      leftTop = Position.page(this.node);
      hwNode = Element.getDimensions(this.node);
			break;
    case "handle":
			Position.prepare();
      leftTop = Position.cumulativeOffset($(this.options.handle));
      hwNode = Element.getDimensions(this.options.handle);
			break;
    case "node":
    default:
			//Position.includeScrollOffsets = true;
			Position.prepare();
      leftTop = Position.cumulativeOffset(this.node);
      hwNode = Element.getDimensions(this.node);
    }
    var hwToolTip = Element.getDimensions(this.window);
    
    var visibleArea = Position.realOffset(document.documentElement || document.body);
    var visibleDims = Element.getDimensions(document.documentElement || document.body);
    var xMin = visibleArea[0];
    var xMax = xMin + visibleDims.width;
    var yMin = visibleArea[1];
    var yMax = yMin + visibleDims.height;
    //alert("x: " + xMin + "-" + xMax + "\ny: " + yMin + "-" + yMax);
    
    //default to bottom right of "handle"
    var xoffset = leftTop[0] + hwNode.width;
    var yoffset = leftTop[1] + hwNode.height;
    
    if(this.options.windowPlacement.endsWith("-right")) {
			xoffset -= (hwToolTip.width + 2);//use right side of tool tip instead of left
			if(/MSIE/.test(navigator.userAgent)) {
				xoffset += 1;
				yoffset += 1;
			}
		}
    
    //if tool tip overflows right side AND wont overflow left OR hard-coded to right
    //move to left of handle
    if(this.options.placement.endsWith("-left")
				|| (this.options.placement.endsWith("-*") && xoffset + hwToolTip.width > xMax && leftTop[0] - hwToolTip.width > xMin)) {
			xoffset = leftTop[0] - hwToolTip.width;
		}
    //move above handle...
    if(this.options.placement.startsWith("top-")
				|| (this.options.placement.startsWith("*-") && yoffset + hwToolTip.height > yMax && leftTop[1] - hwToolTip.height > yMin)) {
			yoffset = leftTop[1] - hwToolTip.height;
		}
    
    AP.ToolTip_IFrame.height = hwToolTip.height;
    AP.ToolTip_IFrame.width = hwToolTip.width;
    
    this.window.style.left = (xoffset) + "px";
    this.window.style.top = (yoffset) + "px";
    AP.ToolTip_IFrame.style.left = (xoffset) + "px";
    AP.ToolTip_IFrame.style.top = (yoffset) + "px";
  },
  
  show: function(event, x, y) {
		if(this.func) this.func();//if not initilized
		
		if(this.options.action == "move") {
			if(!this.isHovering || Element.visible(this.window)) return;
		}
		else if(this.options.action == "click") {
			if(event && Element.visible(this.window))
				return this.hide();
		}
    
    this.position(event, x, y);
    
    if(this.options.className)
			AP.ToolTip_IFrame.className = this.options.className + "iframe";
		else
			AP.ToolTip_IFrame.className = "";
    
    Element.show(AP.ToolTip_IFrame);
    Element.show(this.window);
    this.options.onOpen(this.node, this.window)
    
    if(event) Event.stop(event);
    return false;
  },
  
  hide: function(event) {
		if(this.options.action == "move") {
			if(this.isHovering)
				return;
			clearTimeout(this.hideTimerId);
		}
		else if(this.options.action == "click" && !Element.visible(this.window)) {
			return;
		}
    
    Element.hide(AP.ToolTip_IFrame);
    Element.hide(this.window);
    this.options.onClose(this.node, this.window)
    
    if(event) Event.stop(event);
    return false;
  }
  
}

function CloseSearchHitToolTip(recordId, searchId) {
    var searchResults = SearchManager.getSearch(searchId);
	searchResults.hits[recordId].toolTip.hide.call(searchResults.hits[recordId].toolTip);
}
function FormatSearchHitMenu(handle, menu, searchId) {
    var searchResults = SearchManager.getSearch(searchId);
	var recordId = handle.getAttribute("recordid");
	
	if(searchResults.hits[recordId]) {
		searchResults.hits[recordId].toolTip = this;
		menu.innerHTML = menu.innerHTML.replace(/__RECORDID__/gi, recordId);
		//debugService.trace(menu.innerHTML);
	}
}
function SearchHitMenu_OnOpen(handle, menu) {
	menu.focus();
//	var hit = Element.up(handle, "FIELDSET.photoCell");
//	new Effect.Move(hit, {x: -159});
}
function SearchHitMenu_OnClose(handle, menu) {
	var hit = Element.up(handle, "FIELDSET.photoCell");
	new Effect.Move(hit, {x: 159});
}

//var manualRefreshFunction = RegisterMaxResize({}, id1, id2, id3)
function RegisterMaxResize() {
	var refreshFunc = MaxResize.bind(this, arguments);
	Event.observe(window, "load", refreshFunc);
	Event.observe(window, "resize", refreshFunc);
	
	return refreshFunc;
}

function MaxResize(args) {
	args = $A(args);
	opts = Object.extend({
		vertical: true,
		horizontal: false,
		minHeight: 1,
		minWidth: 1
	}, args.shift() || {});
	
	var attempts = 0;
	var elements = $.apply(this, args);
	
	do {
		attempts++;
		var delta = 0;
		
		Position.prepare();
		var beforeY = Position.deltaY;
		for(var i=0; i<elements.length; i++) {
			delta += MaxResizeElem(elements[i], opts);
		}
		
		Position.prepare();
		if(beforeY == Position.deltaY) {
			attempts = 10;//we had no effect, these elements are not the thing that is to big, stop resizing
			window.scrollTo(0, 0);
			//resize them back
			for(var i=0; i<elements.length; i++)
				elements[i].style.height = (elements[i].getHeight() + 2*Position.deltaY) + 'px';
		}
	} while(attempts < 10 && (delta > 0 || Position.deltaY > 0));
	
	//alert("done in " + attempts);
}

function MaxResizeElem(element, opts) {
	var viewport = document.viewport.getDimensions();
	var dimensions = element.getDimensions();
	var deltaY;
		
	window.scrollBy(viewport.height, viewport.width);
	
	if(Position.deltaY > 0)
		deltaY = -Position.deltaY;//element is to big
	else
		deltaY = viewport.height;
	
	//alert(element.id + "("+dimensions.height+") += " + deltaY);
	if(dimensions.height + deltaY > opts.minHeight) {
		element.style.height = (dimensions.height + deltaY) + 'px';
		return deltaY;
	}
	return 0;
}