/*
	TATV 'ToolBox'
	Author: emakina\fde
*/

var TATV_CONSOLE_ENABLED = false;
var TATV_CONSOLE_ID = 'DBGConsole_DEBUG';

// FireBug console debugging ( http://www.joehewitt.com/software/firebug/ )
// If not present (Internet Explorer/Safari), dynamically create a div to output messages.
function DBGConsole()
{
	this.debugCounter = 0;
}
DBGConsole.prototype.log = function(message)
{
	if (!TATV_CONSOLE_ENABLED) return;
    this.debugCounter++;

	var found = !!$(TATV_CONSOLE_ID);
	if (!found) {
		// create the debugging div
		d = document.createElement('div');
		d.id = TATV_CONSOLE_ID;
		d.style.border = '2px solid #dc0000';
		d.style.background = '#fff5f5';
		d.style.padding = '5px';
		d.style.font = 'bold 10px Verdana;';
		d.style.textAlign = 'left';
		d.style.color = '#000';
		d.style.font = '12px Courier New, monospace;';
	}
	var t = document.createTextNode(''+this.debugCounter + ': ' + message);
    var br = document.createElement('br');
	d.appendChild(t);
    d.appendChild(br);
	if (!found) {
		document.getElementsByTagName('body')[0].appendChild(d);
	}
}

// Unobstrusive add to window.onload with addEvent(window, 'load', init_whatever);
function addEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent){ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}

// document.getElementById(id1, id2, id3, ...) returns one element or an array of elements
function $() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    if (arguments.length == 1)
      return element;
    elements.push(element);
  }
  return elements;
}


function tatvGetElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}


/* disable/enable any buttons or submit fields */
function tatvSetButtonState(divid, enabled) {
	var i;
	var btnd = $(divid);
	if (!btnd) return;
	var btns = btnd.getElementsByTagName('button');
	for (i=0;i<btns.length;i++)
		btns[i].disabled = !enabled;
	var inps = btnd.getElementsByTagName('input');
	for (i=0;i<inps.length;i++) {
		if (inps[i].type="submit")
			inps[i].disabled = !enabled;
	}
}


function tatvToggleHtmlInput(divid, enable) {
	var inp = $(divid).getElementsByTagName('input')[0];
	if (inp) {
		inp.disabled = !enable;
		inp.style.color = enable ? '#000' : '#838061';
		inp.style.backgroundPosition = enable ? '0 0' : '0 -32px';
	}
}


/*	Usage: setupToggleBlocks();

	Each on/off display block consist of two id's :
	- the container for the input element (radio or checkbox) <div id="tb-toggle-elem:N"...><input ...></div>
	- the container div for the on/off block <div id="tb-toggle-block:N" ...> on/off content </div>
	Where N starts at 0, and increases with each new 'toggle' block in the page.
*/
function ToggleBlock(sShowId, sBlockId)
{
	this.toggleElem = $(sBlockId);
	this.showElem = null;
	var thisObj = this;

	function OnClickToggleBlock() {
		thisObj.toggleElem.style.display = (thisObj.showElem.checked) ? 'block' : 'none';
	}

	pshow = $(sShowId);
	pshowelems = pshow.getElementsByTagName('input');
	if (pshowelems.length > 0) {
		this.showElem = pshowelems[0];
		var pShowE = pshowelems[0];
		if (pShowE.getAttribute('type')=='radio') {
			var radioGroup = pShowE.getAttribute('name');
			var elems = document.getElementsByTagName('input');
			var i;
			for (i=0; i<elems.length; i++) {
				if (elems[i].getAttribute('type')=='radio' && elems[i].getAttribute('name')==radioGroup) {
					elems[i].onclick = OnClickToggleBlock;
				}
			}
		}
		else if (pShowE.getAttribute('type')=='checkbox') {
			pShowE.onclick = OnClickToggleBlock;
		}
		
		this.toggleElem.style.display = (pShowE.checked) ? 'block' : 'none';
	}

}
function setupToggleBlocks()
{
	var sToggleCmd = 'tb-toggle-elem:';
	var sToggleDiv = 'tb-toggle-block:';
	var i = 0;

	while(1) {
		var sToggleElemId = sToggleCmd + i;
		if ($(sToggleElemId)) {
			var sToggleBlockId = sToggleDiv + i;
			new ToggleBlock(sToggleElemId, sToggleBlockId);
		}
		else break;
		i++;
	}
}


// This script handles mouseover popups.
// Code modified by fde/emakina
// --------------------------------------------------------------------------
var tatvCurrentMouseOver;

var mouseover_elem;
// set delay vars to emulate normal hover delay
var mouseover_delay;
var mouseover_interval = 0.10;


function mouseoverParentDiv() {
	// popup divs are offset by the centered content div
	return $('tatvsite_mainview');
}


// this function runs on window load
// it runs through all the images on the page with a special title
function makeMouseOvers()
{
	//fde: replaced 'document.links' with 'images'
	var elements = null;
	var mo_divid = 1;

	if (!document.createElement || !document.getElementsByTagName) return;
	if (!document.createElementNS)
		{
		document.createElementNS = function(ns, elt)
			{
			return document.createElement(elt);
			}
		}

	function applyMouseOver(htmltag) {		
		var elements = document.getElementsByTagName(htmltag);
		
		for (var ti=0; ti<elements.length; ti++)
		{
			var lnk = elements[ti];
			var lnktitle = lnk.title;

			// alternate version with message provided through title like attribute
			var indesc = lnk.getAttribute('mouseovertext');
			if (typeof(indesc)=='string' && indesc.length>0) {
				// generate div for the popup
				var d = document.createElement('div');
				var sMouseoverId = 'tatvmo'+mo_divid++;
				d.style.display = 'none';
				d.className = 'mouseover';
				d.id = sMouseoverId;
			    var tn = document.createTextNode(indesc);
				d.appendChild(tn);
				lnktitle = 'mouseover:'+sMouseoverId;
				mouseoverParentDiv().appendChild(d);
			}

			if (lnktitle && /^mouseover:[A-Za-z]+/.test(lnktitle) )
			{
				//faB : get the name of the div with the content we want
				var sId = lnktitle.split(':')[1];

				// if associated div has no content, dont show
				if (!indesc && /^\s*$/.test($(sId).innerHTML)) {
					lnk.title = '';
					continue;
				}
				
				lnk.setAttribute('nicetitle', sId /*lnk.title*/);
				lnk.removeAttribute('title');
				addEvent(lnk, 'mouseover', showDelay);
				addEvent(lnk, 'mouseout', hideMouseOver);
				addEvent(lnk, 'focus', showDelay);
				addEvent(lnk, 'blur', hideMouseOver);
				lnk.className += lnk.className?' mouseovercursor':'mouseovercursor';
			}
		}
	}

	// do regular links
	applyMouseOver('img');
	applyMouseOver('area');
}


function findPosition(oLink)
{
	if (oLink.offsetParent){
		for (var posX = 0, posY = 0; oLink.offsetParent; oLink = oLink.offsetParent){
			posX += oLink.offsetLeft;
			posY += oLink.offsetTop;
		}
		return [posX, posY];
	}else{
		return [oLink.x, oLink.y];
	}
}


function getParent(el)
{
	if (el == null){
		return null;
	}
	// gecko bug, supposed to be uppercase
	else if (el.nodeType == 1 && (el.tagName.toLowerCase()=='img' || el.tagName.toLowerCase()=='area'))
	{
		return el;
	}else{
		return getParent(el.parentNode);
	}
}


function showDelay(e)
{
    if (window.event && window.event.srcElement){
        mouseover_elem = window.event.srcElement
	} else if (e && e.target){
        mouseover_elem = e.target
	}
    if (!mouseover_elem) 
    	return;

	// mouseover_elem is a textnode or an elementnode that's not ins/del
    if (mouseover_elem.nodeType == 3 || (mouseover_elem.nodeType == 1 && mouseover_elem.tagName.toLowerCase() != 'ins' && mouseover_elem.tagName.toLowerCase() != 'del'))
	{
		// ascend parents until we hit a link
		mouseover_elem = getParent(mouseover_elem);
	}
	
	mouseover_delay = setTimeout("showMouseOver(mouseover_elem)", mouseover_interval * 1000);
}


function mouseoverParentDiv() { return $('tatvsite_mainview'); }

// build and show the nice titles
function showMouseOver(mouseoverelem)
{
    if (tatvCurrentMouseOver) hideMouseOver(tatvCurrentMouseOver);
    if (!document.getElementsByTagName) return;

    var nicetitle = mouseoverelem.getAttribute('nicetitle');

    d = $(nicetitle);

	// dynamically create div, so we can insert an iframe to fix combobox display order bug in IE6
	var tText = d.innerHTML;
	var div = document.createElement('div');
	div.style.position = 'absolute';
	div.style.display = 'none';
	div.id = 'tatvdynmouseover';
	div.style.width = '230px';
	dt = document.createElement('div');
	dt.className = 'mouseover';
	dt.innerHTML = tText;
	div.appendChild(dt);
	mouseoverParentDiv().appendChild(div);

	// position of popups on imagemap is 'hardcoded'
	if (mouseoverelem.nodeName.toLowerCase() != 'area')
	{
		// position tooltip
		w = 230;

	    mpos = findPosition(mouseoverelem);
	    mx = mpos[0];
	    my = mpos[1];
		
		var posleft = (mx+10);
		var postop = (my+25);
	    
	    if (window.innerWidth && ((mx+w) > window.innerWidth))
	        posleft = (window.innerWidth - w - 25);
	    if (document.body.scrollWidth && ((mx+w) > document.body.scrollWidth))
			posleft = (document.body.scrollWidth - w - 25);
	
	    div.style.left = posleft + 'px';
	    div.style.top = postop + 'px';
	    
	    // must display before timeout so the element is generated!
    	div.style.display = '';

		window.setTimeout(
			// after timeout, we should be able to read the proper pixel dimensions
			function() {
				var tWidth = dt.offsetWidth;
				var tHeight = dt.offsetHeight;
				console.log('mouseover size '+tWidth+'x'+tHeight);
				var ifr = document.createElement('iframe');
				ifr.frameBorder = '0';
				ifr.scrolling = 'no';
				ifr.style.position = 'absolute';
				ifr.style.width = tWidth + 'px';
				ifr.style.height = tHeight+'px';
				ifr.src = "javascript:'<html></html>';"; // fixes SSL warning for IE
				div.insertBefore(ifr, dt);
			}, 0);
		
		d = div;
	}
	else
	{
		// show it
		d.style.display = '';
	}
	
	tatvCurrentMouseOver = d;
}


function hideMouseOver(e)
{
	if (mouseover_delay) clearTimeout(mouseover_delay);
	if (!document.getElementsByTagName) return;
	if (tatvCurrentMouseOver)
	{
		if (tatvCurrentMouseOver.id=='tatvdynmouseover')
		{
			// it was dynamically generated
			console.log('remove child'+tatvCurrentMouseOver.id);
			mouseoverParentDiv().removeChild(tatvCurrentMouseOver);
		}
		else {
			tatvCurrentMouseOver.style.display = 'none';
		}
		tatvCurrentMouseOver = null;
	}
}


// --------------------------------------------------------------------------


function tatvCreateCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}


function tatvReadCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}


// --------------------------------------------------------------------------

var tatvfontsize = 11;
function getDefaultFontSize() { return 11; }
function setActiveFontSize(n){
	if (!document.getElementsByTagName) return;
	var b = document.getElementsByTagName('body')[0];
	b.style.fontSize = n+'px';
};
function tatvChangeFontSize(n){
	tatvfontsize = tatvfontsize + n;
	if(tatvfontsize>15){tatvfontsize=15;}else if(tatvfontsize<8){tatvfontsize=8;}
	setActiveFontSize(tatvfontsize);
	tatvSaveFontSize();
};
function tatvLoadFontSize() {
	var cookie = tatvReadCookie("fontsize");
	tatvfontsize = cookie ? parseInt(cookie) : getDefaultFontSize();
	if (tatvfontsize == 'null')
		tatvfontsize = getDefaultFontSize();
	if (tatvfontsize != getDefaultFontSize())
		setActiveFontSize(tatvfontsize);
}
function tatvSaveFontSize() {
	tatvCreateCookie("fontsize", tatvfontsize, 30);
}

// --------------------------------------------------------------------------

// if validation error applet is present, jump to it (overrides Siebel jump to the anchor of the form applet)
function jumpToValidationErrorApplet()
{
	if ($('tatv_validationerrorapplet')) {
		window.location = '#tatv_validationerrorapplet';
	}
}

// activity indicator
function tatvShowActivityIndicator()
{
	var da = $('tatvprocess');
	var db = $('tatvprocessing');
	da.style.display = 'none';
	db.style.display = 'block';
}

// This function clears the City & Street combos BEFORE calling Siebel's original onchange() event on the PostCode combo,
// when the form is submitted and the page reloaded, the new postcode appears with empty City & Street values.
function tatvResetCityStreetCombos(orig_onchange_event, divOne, divTwo) {
	// divOne/Two = container elements for the <select>s
	var selOne = $(divOne).getElementsByTagName('select')[0];
	var selTwo = $(divTwo).getElementsByTagName('select')[0];
	// control may not be present if Siebel generate read-only field
	if (selOne) { selOne.selectedIndex = 0; }
	if (selTwo) { selTwo.selectedIndex = 0; }
	// call Siebel's original onchange() event for the PostCode <select>
	orig_onchange_event();
}


// --------------------------------------------------------------------------

function tatvViewSetup()
{
	// dont change font size on homepage (because of the form)
	if (!$('layout_home')) {
		tatvLoadFontSize();
		//addEvent(window, 'unload', tatvSaveFontSize);
	}
	makeMouseOvers();
	setupToggleBlocks();
	jumpToValidationErrorApplet();
}

// If FireBug's console is present, but we want to turn it off, overwrite it with our own
// In IE, always create it (so the console calls do not generate errors)
// Test for some methods to detect a non-FireBug "console" object that we should replace (Apple Safari)
if (!console || (!TATV_CONSOLE_ENABLED && console.log && console.assert) )
{
	var console = new DBGConsole();
}

addEvent(window, 'load', tatvViewSetup);
