//
//$Log: utils.js,v $
//Revision 1.7  2009/01/20 21:23:16  agitpap
//sanity check (in)
//
//Revision 1.6  2008/12/29 22:51:00  agitpap
//add check for opera addEventListener
//remove logging code
//
//Revision 1.5  2008/12/14 22:11:54  agitpap
//add
//    showHelp()
//    setOpacity()
//
//Revision 1.4  2008/12/10 23:48:04  agitpap
//add withAlert option to checkEmail()
//to allow suppression of message
//- needed for onKeyUp checking etc
//
//Revision 1.3  2008/12/10 20:40:47  agitpap
//sanity check (in)
//
//Revision 1.2  2008/07/12 16:23:09  agitpap
//sync for oldtimer
//
//Revision 1.1  2008/05/24 21:14:16  agitpap
//initial check-in
//

//

try
{
	var dom_event_handler = (document.addEventListener) ? true : false;
	var ie_event_handler = (document.attachEvent) ? true : false;
	var opera_event_handler = (window.opera && window.opera.addEventListener) ? true : false;
} catch (err) {}

function strltrim()
{
	return this.replace(/^\s+/,'');
}

function strrtrim()
{
	return this.replace(/\s+$/,'');
}

function strtrim()
{
	return this.replace(/^\s+/,'').replace(/\s+$/,'');
}

function strxtrim()
{
	return this.replace(/^[^a-zA-Z0-9]+/, '').replace(/[^a-zA-Z0-9]+$/, '');
}

String.prototype.ltrim = strltrim;
String.prototype.rtrim = strrtrim;
String.prototype.trim = strtrim;
String.prototype.xtrim = strxtrim;


//empty for the time being ...
function init()
{

}

function max(a, b)
{
	return (a > b) ? a : b;
}

function min(a, b)
{
	return (a < b) ? a : b;
}

function screenObject()
{
	this.id = '';
	this.x = 0;
	this.y = 0;
	this.message = "";
}


var dragObj = null;
var resizeObj = null;

var resizeHorz = false;
var resizeVert = false;

var cursorXOrigin = 0;
var cursorX = 0;
var cursorYOrigin = 0;
var cursorY = 0;
var shadowWidth = 20;

function initDragXY(event)
{
	cursorXOrigin = event.clientX;
	cursorYOrigin = event.clientY;
}

var zDragRestore = 2;
var zObjRestore = null;

function setDragObj(o)
{

	if (o != null)
	{
		zDragRestore  = o.style.zIndex;
		if (zObjRestore != null)
		{
			zObjRestore.style.zIndex = zDragRestore;
		}
		zObjRestore   = o;
		o.style.zIndex = "99";
		o.style.cursor = 'move';
		setOpacity(o.id, 50);
	}
	else
	{
		if (zObjRestore != null)
		{
			zObjRestore.style.cursor = 'default';
			setOpacity(zObjRestore.id, 100);
		}
	}
	
	dragObj = o;

}

function setResizeObj(o)
{
	if (o == null)
	{
		resizeObj = false;
	}

	resizeObj = o;
}

function resize()
{
	if (resizeObj == null)
	{
		return;
	}

	var deltaX = cursorX - cursorXOrigin;
	var deltaY = cursorY - cursorYOrigin;

	resizeObj.style.width += deltaX;
	resizeObj.style.height += deltaY;

	if (deltaX < 0 || deltaY < 0)
	{
		moveObjectTo(dragObj.id,
				dragObj.offsetLeft + deltaX,
				dragObj.offsetTop + deltaY);
	}

	cursorXOrigin = cursorX;
	cursorYOrigin = cursorY;

}


function drag()
{
	if (dragObj == null)
	{
		return;
	}

	var deltaX = cursorX - cursorXOrigin;
	var deltaY = cursorY - cursorYOrigin;
	var newX = max(dragObj.offsetLeft + deltaX, 0);
	var newY = max(dragObj.offsetTop + deltaY, 0);

	moveObjectTo(dragObj.id,
			newX,
			newY);

	try
	{
		var shadow = Layers[dragObj.id].shadowLayer;
		if (shadow != null)
		{
				//syncXYCoords(shadow.id, dragObj.id, 0, 0);
				moveObjectTo(shadow.id, newX + shadowWidth, newY + shadowWidth);
		}
		else
		{
			writeLog("Unable to locate shadow " + dragObj.id + "_shadow");
		}
	}
	catch (e) {}
	
	cursorXOrigin = cursorX;
	cursorYOrigin = cursorY;
}

function updateMouseCoords(event)
{

	cursorX = event.clientX;
	cursorY = event.clientY;

}


function isDefined( variable)
{
    return (typeof(variable) == "undefined")?  false: true;
}

function conditionalLink(question, url) {
  if (confirm(question))
  {
    document.location = url;
  }
}

function conditionalFormSubmit(question, form_name) {
  if (confirm(question))
  {
    findObj(form_name).submit();
  }
}

function findObj(n) {

	try
	{
		if(document.getElementById)
		{
			return document.getElementById(n);
		}
	}
	catch (e)
	{ return o; }

	return null;
}

function findObject(o)
{
	return (findObj(o));
}

function isVisible(obj)
{
	var o = findObj(obj);

	if (!o)
	{
		return false;
	}

	return (o.style.visibility == "visible");

}


function setCursor(obj, cursor_style)
{
	var o = findObj(obj);
	o.style.cursor = cursor_style;
	return;
}

function swapImg(imgid, imgsrc)
{
	var img = findObj(imgid);

	if (!img)
	{
		alert("not found");
		return;
	}

	img.src = imgsrc;
	return;

}

function toggleImg(imgid, imgsrc1, imgsrc2)
{
	var img = findObj(imgid);

	if (!img)
	{
		alert(imgid + " not found");
		return;
	}

	//NOTE:
	//Kludge - the src returns the http://...
	//so look for substring
	if (img.src.indexOf(imgsrc1) > 0)
	{
		img.src = imgsrc2;
	}
	else
	{
		img.src = imgsrc1;
	}

	return;

}

function setObjectDisplay(objid, displayMode)
{
	var obj = findObj(objid);

	if (obj)
	{
		obj.style.display = displayMode;
	}

	return;
}

function toggleObjectDisplay(objid, visStyle)
{
	//visStyle indicates visible style, i.e., inline, block
	var obj = findObj(objid);

	if (obj)
	{
		obj.style.display = (obj.style.display == "none") ?
					visStyle : "none" ;
	}

	return;
}

function toggleClassName(objId, className1, className2)
{
	var o = findObj(objId);
	var oClassName = o.className;

	writeLog(objId + "[" + o + "] : className [" + oClassName + "] - choice ["
		+ className1 + ", " + className2 + "]");

	if (oClassName == className1)
	{
		o.className = className2;
	}
	else
	{
		o.className = className1;
	}

	writeLog(objId + "[" + o + "] : className changed to [" + o.className + "]");


}

function _toggleClassName(objId, either_, or_)
{
	var obj = findObj(objid);

	writeLog("Changing classname for " + objId
			+ " either [" + either_ + "] or [" + or_ + "]");
	writeLog("- current classname [" + obj.className + "]");

	if (obj)
	{
		obj.className = (obj.style.className == either_)
						? or_ : either_ ;
		writeLog("- new classname [" + obj.className + "]");
	}

}

function toggleListItemDisplayImg(objId, either, or)
{
	var obj = findObj(objid);

	if (obj)
	{
		obj.style.listStyleImage = (obj.style.listStyleImage == either) ?
									or : either ;
	}

}

function setObjectVisibility(objid, bool)
{
	if (bool)
	{
		showObject(objid);
	}
	else
	{
		hideObject(objid);
	}

	return;
}

function showObject(objid)
{
	var obj = findObj(objid);

	if (obj)
	{
		obj.style.visibility = "visible";
	}

	return;

}

function showObjectAt(objid, x, y)
{
	var obj = findObj(objid);

	moveObjectTo(objid, x, y);
	showObject(objid);

	return;

}

function moveObjectTo(objid, x, y)
{
	var obj = findObj(objid);

	if (obj)
	{
		obj.style.left = x + "px";
		obj.style.top = y + "px";
	}
	else
	{
		writeLog("[moveObjectTo()]Cant find " + objid);
	}

	return;

}

function syncXYCoords(objtosync, syncobj, delta_x, delta_y)
{
	var syncobj_coords = getScreenCoords(syncobj);

	moveObjectTo(objtosync, syncobj_coords.x + delta_x, syncobj_coords.y + delta_y)

	return;
}

function hideObject(objid)
{
	var obj = findObj(objid);

	if (obj)
	{
		obj.style.visibility = "hidden";
	}

	return;

}

function getObjValue(objid)
{
	var obj = findObj(objid);

	if (obj)
	{
		return obj.value;
	}

	return null;

}

function setObjValue(objid, val)
{
	var obj = findObj(objid);

	if (obj)
	{
		var old_val = obj.value;
		obj.value = val;
		return old_val;
	}

	return null;

}

function setObjectValue(objid, val)
{
	return setObjValue(objid, val);
}

function forceInt(objId)
{
	var strVal = getObjValue(objId).replace(/[^0-9]/g, "");

	setObjValue(objId, strVal);

}

function forceValidID(objId)
{
	var strVal = getObjValue(objId).replace(/^[^a-zA-Z_]/, "").replace(/ /g, "_").replace(/[^0-9a-zA-Z_]/g, "");

	setObjValue(objId, strVal);
}

function forceValidRGB(objId)
{
	var strVal = getObjValue(objId).replace(/[^a-fA-F0-9]/, "");

	setObjValue(objId, strVal);
}


function setCheckbox(objid, true_false)
{
	var obj = findObj(objid);

	if (obj)
	{
		var old_val = obj.checked;
		obj.checked = true_false;
		return old_val;
	}

	return null;

}

function getListSelectedIdx(objid)
{
	var obj = findObj(objid);
	var idx = -1;

	if (obj)
	{
		idx = obj.selectedIndex;
	}

	return idx;

}

function setSelectedIndex(objid, idx)
{
	try
	{
		var obj = findObj(objid);
		if (!obj)
		{
			return;
		}

		if (idx >= 0)
		{
			obj.selectedIndex = idx;
		}
	}
	catch(err){}
}



//	convert a decimal / int value to
//	a currency string with 2 dp
//	so    1 => 1.00
//	   10.5 => 10.50
function currencyString(val)
{
	var pence = parseInt(parseFloat(val) * 100.0) % 100;
	var pounds = parseInt(val);

	if (pence < 10)
	{
		return pounds + ".0" + pence;
	}
	else
	{
		return pounds + "." + pence;
	}

}


function getElementCoords(objid)
{
	var objOfInterest = findObj(objid);

	if (!objOfInterest)
	{
		alert("unable to find " + objid);
		return null;
	}

	var thing = new screenObject();

	thing.x = objOfInterest.offsetLeft;
	thing.y = objOfInterest.offsetTop;

	thing.id = objid;

	return thing;

}


function getScreenCoords(objid)
{

	var objOfInterest = findObj(objid);

	if (!objOfInterest)
	{
		alert("unable to find " + objid);
		return null;
	}

	var thing = new screenObject();

	thing.x = objOfInterest.offsetLeft;
	thing.y = objOfInterest.offsetTop;


	var numParents = 0;

	while (objOfInterest = objOfInterest.offsetParent)
	{
		thing.x += objOfInterest.offsetLeft;
		thing.y += objOfInterest.offsetTop;
		++numParents;
	}

	thing.id = objid;
	return thing;
}

	/*
		validEmail
		==========
		(c) laccata 2003

		NOTE:
		This is a simple email validator


	*/
function checkEmail(emailId, withAlert)
{
	var emailObj = findObj(emailId);
	if (emailObj)
	{
		return validEmail(emailObj, withAlert);
	}

	return false;
}

function validEmail(formControl, withAlert) {

	//pattern = new RegExp("^[_a-zA-Z0-9]+([\\-_\\.]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\\-_\\.]?[a-zA-Z0-9]+)*\\.[a-zA-Z]{2,4}$");
	pattern = new RegExp("^[\\w]+([\\-\\.]?[\\w]+)*@[\\w]+([\\-\\.]?[\\w]+)*\\.[a-zA-Z]{2,4}$");

	if (!pattern.test(formControl.value))
	{
		if(withAlert)
		{
			alert("Please check your email address");
		}
		return false;
	}

	return true;

}

	/*
		validName
		==========
		(c) laccata 2003

		Simple name validator.
		A string starting with a-z or A-Z.
		Any more rules, let me know ...
	*/
function validName(formControl) {

	pattern = new RegExp("^[a-zA-Z]");

	if (!pattern.test(formControl.value.trim()))
	{
		alert("You've forgotten to enter your name");
		return false;
	}

	return true;

}

function validPostcode(formControl, country_code) {

	if (country_code != 'uk')
	{
		if (formControl.value.trim().length == 0)
		{
			alert("You've forgotten to enter a postcode");
			return false;
		}
		else
		{
			return true;
		}
	}

	//uk postcodes can be validated properly
	pattern = new RegExp("^[a-zA-Z]{1,2}[0-9]{1,2}[ ]*[0-9][a-zA-Z][a-zA-Z]");

	if (!pattern.test(formControl.value.trim()))
	{
		alert("Please check your postcode");
		return false;
	}

	return true;

}


function validAddress(formControl) {

	if (formControl.value.trim().length == 0)
	{
		alert("You've forgotten to enter your address");
		return false;
	}

	return true;

}

function validDate(yyyy, mm, dd)
{

	var today = new Date();
	var days_in_month;
	var check_it;
	var leap;

	--mm;	//for zero-based month

	check_it = new Date(yyyy, mm, dd, 0, 0, 1);

	leap = ( (yyyy % 4 == 0 && yyyy % 100 != 0) || (yyyy %400 == 0) );


	days_in_month = (mm == 1) ? (leap ? 29 : 28) :
			(mm == 3 || mm == 5 || mm == 8 || mm == 10) ? 30 :
			31;

	//alert("checkit date : " +  yyyy + "-" +
	//		(mm + 1) + "-" + dd + " , days_in_month = " + days_in_month);

	if 	(dd > days_in_month)
	{
		alert("Invalid Date : " + yyyy
			+ ":" + (mm+1) + ":" + dd);
		return false;
	}

	return true;

	}

/*
	This is a bit kludgy - but I'm in a hurry
*/

function showHelp(help_id, help_text,
					syncObj, delta_x, delta_y,
					background_colour)
{

	if (findObj(help_id))
	{
		syncXYCoords(help_id, syncObj, delta_x, delta_y);
		showObject(help_id);
		return;
	}

	var margin_width = "4px";
	var margin_bottom_width = "4px";

	var help_container_div = document.createElement("DIV");
	var help_div = document.createElement("DIV");
	var help_para = document.createElement("P");
	//var help_speech_pointer = document.createElement("IMG");

	if (!help_div || !help_container_div || !help_para)
	{
		alert("Unable to create help elements");
		return;
	}

	help_container_div.id = help_id;
	help_container_div.style.backgroundColor = background_colour;
	help_container_div.style.border = "1px solid #777777";
	help_container_div.style.position = "absolute";
	help_container_div.style.visibility = "hidden";
	help_container_div.style.top = "200px";
	help_container_div.style.left = "200px";

	//help_speech_pointer.src = speech_pointer_image_src;
	//help_speech_pointer.position = "absolute";

	help_div.style.position = "relative";

	//help_speech_pointer.style.top = help_container_div.offsetHeight + "px";
	//help_speech_pointer.style.left = help_container_div.offsetWidth + 20 + "px";;

	help_para.style.marginTop = margin_width;
	help_para.style.marginLeft = margin_width;
	help_para.style.marginRight = margin_width;
	help_para.style.marginBottom = margin_width;
	help_para.innerHTML = help_text;


	help_div.appendChild(help_para);
	help_container_div.appendChild(help_div);
	//help_container_div.appendChild(help_speech_pointer);
	document.body.appendChild(help_container_div);
	help_container_div.style.zIndex = 999;
	syncXYCoords(help_id, syncObj, delta_x, delta_y);
	showObject(help_id);

}

//setOpacity
//	firefox has a style opacity, decimal 0.0 - 1.0
//	ie has a style alpha(opacity = o), percentage 0 - 100
//	so, this function takes a percentage.
function setOpacity(objId, opacity)
{

	var o = findObj(objId);

	if (!o)
	{
		return;
	}

	o.style.opacity = opacity/100;

	o.style.filter = 'alpha(opacity=' + opacity + ')';

}

//cleanDOMENode
//=============
//Alternative to .innerHTML = ''
// - walks the DOM, and uses the api to rmove all elements
function cleanDOMNode(root)
{
  writeLog("cleanDOMNode() called with " + root);
  if (null == root)
  {
	writeLog("cleanDOMENode() called with null root");
	return;
  }

  var id = root.id;
  if (null == id || id.trim() == '')
  {
	id = '<unknown>';
  }

 try
 {
	if (root.hasChildNodes())
	{
	  var kids = root.childNodes;
	  writeLog(id + " has "  + kids.length + " child(ren)");
	  for (var i in kids)
	  {
		cleanDOMNode(kids[i]);
	  }
	}
	else
	{
	  writeLog(id + " has NO children - deleting");
	  p = root.parentNode;
	  p.removeChild(root);
	  writeLog(id + " deleted");
	}
  }
  catch (err) {}
}
