// Almega BibleTools Tooltip Javascripts by Simon Lock
// adapted from Ajax Tooltip by JavaScript Kit: http://www.javascriptkit.com

var tooltips=[] //array to contain references to all tooltip DIVs on the page

var bibletooltip={
	fadeeffect: [false, 300], //enable Fade? [true/false, duration_milliseconds]
	useroffset: [10, 10], //additional x and y offset of tooltip from mouse cursor, respectively
	loadingHTML: '<div style="font-style:italic">Loading . . .</div>', // 
	autohide: true,

	positiontip:function($tooltip, e){
		// Get screen dimension
		var docwidth = ((window.innerWidth) ? window.innerWidth : bibletooltip.iebody.clientWidth) - 5
		var docheight = ((window.innerHeight) ? window.innerHeight : bibletooltip.iebody.clientHeight) - 5
		var tipwidth = $tooltip.get(0).offsetWidth // return 0
		var tipheight = $tooltip.get(0).offsetHeight // return height of tooltip when full width is used
		// Set tooltip position
		var tipx = e.clientX+this.useroffset[0]
		var tipy = e.clientY+this.useroffset[1]
//alert(tipx+','+tipy+' '+tipwidth+','+tipheight)
		// Auto select best width for tooltip
		tipwidth = docwidth * 0.5 // default as half the client width
		if (tipheight>docheight)
			tipwidth = docwidth - tipx - this.useroffset[0] - 20
		else
			for (var ratio=1; ratio>0.5; ratio-=0.05) {
				//alert(ratio+':'+tipheight+'>'+docheight*ratio)
				if (tipheight>docheight*ratio) { tipwidth = (docwidth*ratio).toFixed(); break; }
				}
		
		// Adjust position to accommodate tooltip
		if (tipx+tipwidth>docwidth) { // width exceed screen
			tipx = docwidth - tipwidth - this.useroffset[0] - 20
			if (tipx<0) tipx = 0
			if (tipy+tipheight>docheight) // heigth exceed screen
				tipheight = docheight - tipy - this.useroffset[1] -10
		}
		//alert(tipy+','+tipheight+','+docheight)
		if (tipy+tipheight>docheight) { // heigth exceed screen
			tipy = docheight - tipheight - this.useroffset[1] - 10
			if (tipy<0) tipy = 0
			if (tipx+tipwidth>docwidth) // width exceed screen
				tipwidth = docwidth - tipx - this.useroffset[0] - 20
		}
	//	tipx = (e.clientX+tipwidth>docwidth) ? docwidth-tipwidth : tipx //account for right edge
	//	tipy = (e.clientY+tipheight>docheight) ? docheight-tipheight : tipy //account for bottom edge
	//	var tiph = docheight * 0.5 // default as half the client width
		$tooltip.css({left: tipx, top: tipy, width: tipwidth, zIndex: 9999})
	},

	showtip:function($tooltip, e){
		bibletooltip.hidealltips($tooltip)
		if (this.fadeeffect[0])
			$tooltip.hide().fadeIn(this.fadeeffect[1])
		else
			$tooltip.show()
	},

	hidetip:function($tooltip, e){
		if (this.fadeeffect[0])
			$tooltip.fadeOut(this.fadeeffect[1])
		else
			$tooltip.hide()
	},
	
	hidealltips:function($tooltip){
		// Hide all the other tooltips
		for (var i=0; i<tooltips.length; i++)
			if ($tooltip!=tooltips[i] && this.autohide) tooltips[i].hide()
	}

}

function InitBBTTooltips(){
	bibletooltip.iebody = (document.compatMode && document.compatMode!="BackCompat") ? document.documentElement : document.body
	//$('body').attr('onclick','bibletooltip.hidealltips();')
	var keyword, parameter, url, link
	$('a[rel^="bbt"]').each(function(index){ //find all A tags with "rel=bbt" declaration
		var title = this.getAttribute('rel')
		var i = title.indexOf(':')
		var text = (document.all) ? this.innerText : this.textContent
		if (i<0) {
			keyword = title
			parameter = text
		}
		else {
			keyword = title.substr(0,i)
			parameter = (title.substr(i+1,1)=='&') ? text : ''
			parameter += title.substr(i+1)
		}
		parameter = encodeURI(parameter)
		switch (keyword) {
		case 'bbtverses':
			url = 'http://www.almega.com.hk/bible/bbtverses.asp?ref='+parameter
			//url = '/components/bible/bbtverses.asp?ref='+parameter // for localhost testing and IE to work locally
			link = 'http://www.almega.com.hk/bible/?ref='+parameter
			break
		case 'bbtsearch':
			url = 'http://www.almega.com.hk/bible/bbtsearch.asp?text='+parameter
			link = 'http://www.almega.com.hk/bible/?search='+parameter
			break
		default:
			url = ''
			link = ''
		}
		url += '&option=close'
		link = ''
		this.titleurl = url
		this.titleposition = index+' pos' //remember this tooltip DIV's position relative to its peers
		this.autohide = true
		tooltips.push($('<div class="bibletooltip"></div>').appendTo('body'))
		
		var $target = $(this)
		$target.removeAttr('rel')
		if (link!='') {
			$target.attr('href',link)
			$target.attr('target','_blank')
		}
		$target.hover(
			function(e){ //onMouseover element
				var $tooltip = tooltips[parseInt(this.titleposition)]
				if (!$tooltip.get(0).loadsuccess){ //first time fetching Ajax content for this tooltip?
					//$tooltip.html(bibletooltip.loadingHTML).show()
					$tooltip.load(this.titleurl, '', function(){
						bibletooltip.positiontip($tooltip, e)
						bibletooltip.showtip($tooltip, e)
						//$tooltip.draggable({ handle: "p" }) // Requires JQuery UI
						$tooltip.draggable() // Requires JQuery UI
						//$tooltip.resizable()
						$tooltip.get(0).loadsuccess = true
					})
				}
				else{
					bibletooltip.positiontip($tooltip, e)
					bibletooltip.showtip($tooltip, e)
				}
			},
			function(e){ //onMouseout element
				//var $tooltip=tooltips[parseInt(this.titleposition)]
				//bibletooltip.hidetip($tooltip, e)
			}
		)
		$target.bind("mousemove", function(e){
			//var $tooltip=tooltips[parseInt(this.titleposition)]
			//bibletooltip.positiontip($tooltip, e)
		})
	})
	
	// Process in-line bible verses
	$('div[rel^="bbt"]').each(function(index){ //find all DIV tags with "rel=bbt" declaration
		var title = this.getAttribute('rel')
		var i = title.indexOf(':')
		var text = (document.all) ? this.innerText : this.textContent
		if (i<0) {
			keyword = title
			parameter = text
		}
		else {
			keyword = title.substr(0,i)
			parameter = (title.substr(i+1,1)=='&') ? text : ''
			parameter += title.substr(i+1)
		}
		parameter = encodeURI(parameter)
		switch (keyword) {
		case 'bbtverses':
			url = 'http://www.almega.com.hk/bible/bbtverses.asp?ref='+parameter
			//url = '/components/bible/bbtverses.asp?ref='+parameter // for localhost testing and IE to work locally
			link = 'http://www.almega.com.hk/bible/?ref='+parameter
			break
		case 'bbtsearch':
			url = 'http://www.almega.com.hk/bible/bbtsearch.asp?text='+parameter
			link = 'http://www.almega.com.hk/bible/?search='+parameter
			break
		default:
			url = ''
			link = ''
		}
		url += '&option=-heading,-copyrights,-provider'
		link = this.innerHTML
		var $target = $(this)
		$target.removeAttr('rel')
		$target.load(url,'','') // load AJAX content from url
		$target.before(link)
	})
	
	//$( 'div[class^="bibletooltip"]' ).draggable();
}

jQuery(document).ready(function(){
	InitBBTTooltips()
})

// For cross domain ajax in IE8+
// See http://forum.jquery.com/topic/cross-domain-ajax-and-ie
$.ajaxTransport("+*", function( options, originalOptions, jqXHR ) {
	if (jQuery.browser.msie && window.XDomainRequest) {
		var xdr;
		return {
				send: function( headers, completeCallback ) {

						// Use Microsoft XDR
						xdr = new XDomainRequest();
						xdr.open("get", options.url);
						xdr.onload = function() {
								if (this.contentType.match(/\/xml/)){
										var dom = new ActiveXObject("Microsoft.XMLDOM");
										dom.async = false;
										dom.loadXML(this.responseText);
										completeCallback(200, "success", [dom]);
								}else {
										completeCallback(200, "success", [this.responseText]);
								}
						};
						xdr.ontimeout = function(){
								completeCallback(408, "error", ["The request timed out."]);
						};
						xdr.onerror = function(){
								completeCallback(404, "error", ["The requested resource could not be found."]);
						};
						xdr.send();
			},
			abort: function() {
					if (xdr)xdr.abort();
			}
		};
	}
});
