// File js_handlers.js - Common document event handling for VNS web site
// **************************************************************************************************

// Function to the banner div content with the banner flash, utimately showing the origial H1 text
// Note that the V2 swfobject script must be loaded before this script in the header of the calling html file
// We're using low level swfobject routines (rather than embedSWF) to do the H1 text grab in on(DOM)Load
// **************************************************************************************************

function place_flash_banner() {
	// We require at least Flash version 7 which is already pretty old
	if (swfobject.hasFlashPlayerVersion("7.0.0")) {
		// Obtain the text in the H1 with id=bannertext to pass on to the flash banner
		var btext = document.getElementById("bannertext").firstChild.nodeValue;
		// Parameters and attributes to use 
		var params = { 
			bgcolor: "#ffffff", 
			wmode: "transparent",
			menu: "false",
			flashvars: "btext="+btext
		};
		var attributes = { 
			data: "common/vns_banner.swf",
			width: "850",
			height: "80",
			id: "banner_flash", 
			name: "banner_flash"
		};
		var replacesId = "banner";
		var myObj = swfobject.createSWF(attributes, params, replacesId);
	}
}

// Function  to break out of any frame of a referring site 
// **************************************************************************************************

function breakout_from_frame() {
	if (top.location != location)
		top.location.href = document.location.href;
}

// Function  to go to #top anchor of current page (assumed to be always present)
// **************************************************************************************************

function to_top() {
	location.hash = 'top';
}


// Function to 'activate' the icons 
// **************************************************************************************************

function activate_icons() {

	// ico div colorisation and cursor 
	function ico_color (ico) {
		ico.onmouseover = function() { 
		 	//ico.style.backgroundColor = '#eeffee'; 
			//ico.style.fontSize = '11px';
			ico.style.color  = '#000000';
			ico.style.border = 'solid 1px #56ba56';
		}
		ico.onmouseout  = function() { 
			//ico.style.backgroundColor = ''; 
			//ico.style.fontSize = '10px'; 
			ico.style.color  = '#ffffff';
			ico.style.border = 'solid 1px #ffffff';
		}
		ico.style.cursor = 'pointer';
	}

	// ico_home - div in html. Let URL be that of the current document, but without any parameters. 
	// This assumes that every page will be generated by i.e. index.php
	var ico1 = document.getElementById("ico_home");	 ico_color(ico1);
	ico1.onclick     = function() { location.href = document.URL.substring(0, document.URL.indexOf('?')); }	
	ico1.title       = 'To Home page';
	// ico_mail - div in html
	var ico2 = document.getElementById("ico_mail"); ico_color(ico2);
	ico2.onclick     = function() { location.href = 'mailto:info@vns.nl'; }	
	ico2.title       = 'Send Mail';
	// ico_print - div in html
	var ico3 = document.getElementById("ico_print"); ico_color(ico3);
	ico3.onclick     = function() { window.print(); }
	ico3.title       = 'Print page';
	// ico_back - div in html
	var ico4 = document.getElementById("ico_back"); ico_color(ico4);
	ico4.onclick     = function() { history.back(); }
	ico4.title       = 'Go Back';
	// ico_fwd - div in html
	var ico5 = document.getElementById("ico_fwd"); ico_color(ico5);
	ico5.onclick     = function() { history.forward(); }
	ico5.title       = 'Go Forward';
	// ico_top - div in html
	var ico6 = document.getElementById("ico_top"); ico_color(ico6);
	ico6.onclick     = to_top;
	ico6.title       = 'To Top';

	// Validation link tweaking 
	function val_tweaking (val) {
		var img = val.childNodes[1];
		val.onmouseover = function() { 
			val.style.color = '#cd6600';
			img.setAttribute('src', 'common/list_check_r.gif'); 
		}
		val.onmouseout  = function() { 
			val.style.color = '#777777';
			img.setAttribute('src', 'common/list_check_b.gif'); 
		}		
		val.title = img.alt;
	}
	
	// Tweak the two validation links containing check images. 
	// Note that the stylesheet does not specify hover colors for the text
	var val1 = document.getElementById("valid_xhtml"); val_tweaking(val1);
	var val2 = document.getElementById("valid_css"); val_tweaking(val2);

	// Tweak the <span> element "rendermode" (if present) to pop up javascript giving the Browser Render Mode
	var brm = document.getElementById("rendermode");
	if (brm) {
		var rendermode = 'Unknown';
		if (document.compatMode) rendermode = document.compatMode;
		brm.onclick = function() { alert('This page is rendered in mode: ' + rendermode); }
		brm.style.cursor = 'pointer';
	}
}

// Function to install search form handling
// The form one immediate <input type="submit" ..> submit button for local web search that will work without
// javascript support and an additional button for global web search that will do nothing without javascript
// Alternately, it is also possible to use two button inputs and NO submit input. The javascript here will
// attach alternate handlers to both inputs.
// **************************************************************************************************

// Add a trim function to the String class
String.prototype.trim = function() {
	a = this.replace(/^\s+/,'');
	return a.replace(/\s+$/,'');
}

function search_form_handling() {
	// Obtain the relevant DOM objects
	var searchform   = document.getElementById("searchform");    // Form object
	var searchprev   = document.getElementById("searchprev");    // Hidden Input Text object
	var searchterm   = document.getElementById("searchterm");    // Input Text object
	var searchsite   = document.getElementById("searchsite");    // Input Submit or Button object
	var searchweb    = document.getElementById("searchweb");     // Input Button object

	// Obtain the rooturl from the scm injected <base> tag, if present. This is needed for the "action" property of the search form
	// when using Apache's mod_rewrite for pretty permalinks. It seems that a search form with empty "action" will not automatically
	// assume the base href.  Note that with javascripting disabled while having mod_rewrite we will have a problem with local site search
	var rooturl = '';
	if (document.getElementById("rooturl")) rooturl = document.getElementById("rooturl").href;

	// The template defines the searchweb button as disabled as it will never work without javascripting. We can enable it from here..
	searchweb.disabled = false;

	// function setup the search form for one of two search engines. Called upon form submit. 
	function search_form_setup (b_site) {
		if (b_site) {
			searchterm.name   = "search";
			searchform.method = "get";
			searchform.target = "_self";
			searchform.action = rooturl;
			// non-empty validation here, after trimming the search term for server side recycling. No alerts, but quiet.
			searchterm.value  = searchterm.value.trim();
			return (searchterm.value.length != 0);
		} else {
			searchterm.name   = "q";
			searchform.method = "get";
			searchform.target = "_blank";
			searchform.action = "http://www.google.com/search";
			// No validation here; google will present it's own search input field when the serch term is empty
			return true;
		}
	}

	// Button or Submit input to search this local site using local search engine.
	// This also fires upon Enter when searchsite is a submit input type. Not when it is a button input
	searchsite.onclick = function() {	
		// Need to check return value!
		if (search_form_setup (true))	
			searchform.submit();
		// Return false for in case this is a submit input and not a button input
		// Because of this false a subsequent OnSubmit event will be cancelled
		return false;
	}
	searchsite.title = 'Default search on this site';

	// Button input to search globally on the web using Google
	searchweb.onclick = function() {
		search_form_setup (false);
		searchform.submit();
	}
	searchweb.title = 'Search the web';

	// Ensure default behaviour of local site search when using the Enter key while having 2 input buttons
	// Note that the onsubmit handler will NOT fire as a reaction to any scripted submit() call.
	// I have found that when using 2 Button inputs, these buttons must NOT have a name=".." attribute otherwise 
	// searchform.submit() is reported as an inexistant method..    
	searchform.onsubmit = function() {  
		// Pass through return value!
		return search_form_setup (true);
	}

	// Copy the previous search term to the search input. This is contained in hidden input searchprev
	// We protect against non-existing searchprev for when SCM doesn't insert it
	if (searchprev) {
		searchterm.value = searchprev.value;
		// Remove searchprev as it has now fulfilled its purpose. We don't want it in the submit data
		searchform.removeChild(searchprev);
	}
}

// Generic Tooltip functionality. This code allows for ONE SINGLE tooltip
// Note that this steals the mouse move event only when needed 
// Note the Target should not already have any mouse handling (that will be superseded / removed)
// **************************************************************************************************

var tooltip = null;
var tooltiptarget = null;

function tooltip_associate(target, title, cntnt) { 
	tooltip = document.getElementById('tooltip');
	// Create and append a hidden tooltip div if not yet existing 
	if (!tooltip) {
		tooltip = document.createElement('div');
		tooltip.setAttribute('id', 'tooltip');
		tooltip.style.position = 'absolute';
		tooltip.style.visibility = 'hidden';
//experimental alpha for ff/opera resp ie        
tooltip.style.opacity = ".85";
tooltip.style.filter = "alpha(opacity=85)";
		tooltip.style.top = '0px';
		tooltip.style.left = '0px';
		tooltip.style.width = '200px';
		tooltip.style.height = '100px';
		var body = document.getElementsByTagName('body')[0];
		body.appendChild(tooltip);
	}
	// Fill the tooltip div with approprate html
	tooltip.innerHTML = 
		'<table class="tooltiptable">'+
		'<thead><tr><th>'+title+'</th></tr></thead>'+
		'<tbody><tr><td>'+cntnt+'</td></tr></tbody></table>';
	// Unregister events for previous tooltiptarget (if any)
	if (tooltiptarget) {
		tooltiptarget.onmouseover = null; 
		tooltiptarget.onmouseout  = null;
		tooltiptarget.onmousemove = null;     
	}
	// Remember new target and register events
	tooltiptarget = target;
	tooltiptarget.onmouseover = tooltip_on; 
	tooltiptarget.onmouseout  = tooltip_off;
	tooltiptarget.onmousemove = tooltip_move;    
}

function tooltip_on(e) {
	tooltip.style.visibility = 'visible';
}

function tooltip_off(e) {
	tooltip.style.visibility = 'hidden';
}

function tooltip_move(e) {
	// See www.quirksmode.org/js/event_properties.html#position
	var x = 0;
	var y = 0;
	var ei;
	if (e) ei=e; else  ei = window.event;  
	if (ei.pageX || ei.pageY) { 
		x = ei.pageX; 
		y = ei.pageY; 
	} 
	else if (ei.clientX || ei.clientY) {
		x = ei.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		y = ei.clientY + document.body.scrollTop + document.documentElement.scrollTop;    
	}
	// Make offset. Place under pointer, somewhat to the right
	x = x - 40; 
	y = y + 20; 
	// Reposition 
	tooltip.style.left = x + 'px';
	tooltip.style.top  = y + 'px';  
}

// Function to tooltip upon the *first* RSS <strong> in the document (is expected within a link)
// **************************************************************************************************

function annotate_feed_link() {
	var rss = null;
	var spans = document.getElementsByTagName('strong');
	for (var i=0; i<spans.length; i++)
		if (spans[i].className=='rssmark')
			{ rss = spans[i]; break; }
	if (!rss) return;

	var tiptitle = 'RSS Feed link';
	var tipcntnt = 
		'Copy &amp; Paste this link to your '+
		'favorite RSS reader or click it to '+
		'view the feed as a web page.';   
	tooltip_associate(rss, tiptitle, tipcntnt); 
}


// Execution starts here.
// **************************************************************************************************
// swfobject is already there by previous script inclusion
 
swfobject.addDomLoadEvent(handlers_onDomLoad);
swfobject.addLoadEvent(handlers_onLoad);

function handlers_onDomLoad() {     
	//alert('js_handlers.js - onDomLoad');
	place_flash_banner();
}

function handlers_onLoad() {  
	//alert('js_handlers.js - onLoad');
	breakout_from_frame();
	activate_icons();
	search_form_handling();
	annotate_feed_link();
}

