//
//$Log: utils.js,v $
//Revision 1.16  2008/11/19 11:18:37  diginnet
//mark2 check in
//
//Revision 1.15  2008/07/11 12:37:55  diginnet
//add hideObj() as a wrapper for hideObject()
//
//Revision 1.14  2008/01/11 12:35:54  diginnet
//moved reverse sort function to here
//added function to return the value of checked radio button
//
//Revision 1.12  2007/04/20 09:45:24  diginnet
//add syncXYCoords() to move one object to teh same
//x,y position as another
//
//add +"px" to moveObjTo(), as this caused javascript to
//barf sometimes.
//
//Revision 1.11  2007/04/17 21:11:13  diginnet
//add conditionalFormSubmit()
//add beginnings of drag code (moving layers)
//
//
//Revision 1.10  2007/01/07 10:23:10  diginnet
//fix to currencyString()
//
//Revision 1.9  2006/12/31 10:48:45  imogen
//Add cvs $Log: utils.js,v $
//Add cvs Revision 1.16  2008/11/19 11:18:37  diginnet
//Add cvs mark2 check in
//Add cvs
//Add cvs Revision 1.15  2008/07/11 12:37:55  diginnet
//Add cvs add hideObj() as a wrapper for hideObject()
//Add cvs
//Add cvs Revision 1.14  2008/01/11 12:35:54  diginnet
//Add cvs moved reverse sort function to here
//Add cvs added function to return the value of checked radio button
//Add cvs
//Add cvs Revision 1.12  2007/04/20 09:45:24  diginnet
//Add cvs add syncXYCoords() to move one object to teh same
//Add cvs x,y position as another
//Add cvs
//Add cvs add +"px" to moveObjTo(), as this caused javascript to
//Add cvs barf sometimes.
//Add cvs
//Add cvs Revision 1.10  2007/01/07 10:23:10  diginnet
//Add cvs fix to currencyString()
//Add cvs
//
//

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

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

function screenObject()
{
	this.x = 0;
	this.y = 0;
	this.dragging = false;
	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;



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

function setDragObj(o)
{
	if (o == null)
	{
		dragObj = false;
	}
	
	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.width += deltaX;
	resizeObj.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;
			
	moveObjectTo(dragObj.id,
			max(dragObj.offsetLeft + deltaX, 0),
			max(dragObj.offsetTop + deltaY, 0));
				
	cursorXOrigin = cursorX;
	cursorYOrigin = cursorY;
	
}

function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}


function updateMouseCoords(event)
{
	//var cursorXY = getPosition(event);
	cursorX = event.clientX;
	cursorY = event.clientY;
	
}
			


function reverse_sort(a, b)
{
   if(a > b)
      return -1
   if(a < b)
      return 1
   return 0
} 



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;

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) { 
  
  if(document.getElementById) 
  {
  	return document.getElementById(n); 
  }
  
 
  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 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";
	}
	
	return;
	
}

function syncXYCoords(objtosync, syncobj, deltaX, deltaY)
{
	var syncobj_coords = getScreenCoords(syncobj);
	var X = syncobj_coords.x;
	var Y = syncobj_coords.y;
	if(deltaX)
	{
		X += deltaX;
	}
	if(deltaY)
	{
		Y += deltaY;
	}
	
	moveObjectTo(objtosync, X, Y)

	return;
}

function syncSizes(_objtosync, _syncobj, deltaX, deltaY)
{
	
	var syncObj =  findObj(_syncobj);
	var objToSync =  findObj(_objtosync);
	
	if(!syncObj || !objToSync)
	{
		return;
	}
	
	var X = syncObj.offsetWidth;
	var Y = syncObj.offsetHeight;
		
	if(deltaX)
	{
		X += deltaX;
	}
	if(deltaY)
	{
		Y += deltaY;
	}
	
	objToSync.style.width = X + 'px';
	objToSync.style.height = Y + 'px';
	
	return;
	
}

function hideObj(objid)
{
	hideObject(objid)
}

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);
}

//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 + ')';
}


function makeShadowDiv(divId, shadowDivId, opacity, 
						shadowColour, shadowWidth)
{
	var div = findObj(divId);
	
	if(!div)
	{
		return;
	}
	
	var shadowDiv = findObj(shadowDivId);
	
	if(!shadowDiv)
	{
		shadowDiv = document.createElement('DIV');
		if(!shadowDiv)
		{
			return;
		}
		shadowDiv.id = shadowDivId;
		shadowDiv.style.visibility = "hidden";
		document.body.appendChild(shadowDiv);
	}
	
	shadowDiv.style.position = 'absolute';
	setOpacity(shadowDivId, opacity);
	syncSizes(shadowDivId, divId);
	syncXYCoords(shadowDivId, divId, shadowWidth, shadowWidth);
	shadowDiv.style.backgroundColor = shadowColour;
	shadowDiv.style.zIndex = div.style.zIndex - 1;
	shadowDiv.style.visibility = "visible";
}

function isChecked(objid)
{
    return findObj(objid).checked;
}

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 toggleCheckbox(objid)
{
	var obj = findObj(objid);
	
	if (obj)
	{
		var old_val = obj.checked;
		setCheckbox(objid, !old_val);
		return old_val;
	}
	
	return null;
	
}

/**
 *  BEWARE: This function takes an id for the first parm,
 *  and a name for the second.
 *  Radio buttons in a group have the same name, but should
 *  have different ids.    
 *
 */
   
function radioSelectedValue(formId, radioName)
{
  
  try
  {
      var formObj = findObj(formId);
      var formElements = formObj.elements;
      var radioObj = formElements[radioName];
      var radioLength = radioObj.length;
  }
  catch (e)
  {
    alert("Exception thrown in radioSelectedValue");
  }
  
  for (var i = 0; i < radioLength; ++i)
    {
        if (radioObj[i].checked)
        {
            return radioObj[i].value;
        } 
    }

    return "";

}

function getListSelectedIdx(objid)
{
	var obj = findObj(objid);
	var idx = -1;
	
	if (obj)
	{
		idx = obj.selectedIndex;
	}
	
	return idx;

}

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



//	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;

	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;
	}

	return thing;
}

	/*
		validEmail
		==========
		(c) laccata 2003
		
		NOTE:
		This is a simple email validator
		
				
	*/
function checkEmail(emailId)
{
	var emailObj = findObj(emailId);
	if (emailObj)
	{
		return validEmail(emailObj);
	}
	
	return false;
}

function validEmail(formControl) {

	pattern = new RegExp("^[a-zA-Z0-9]+([\\-_\\.]?[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([\\-_\\.]?[a-zA-Z0-9]+)*\\.[a-zA-Z]{2,4}$");
	if (!pattern.test(formControl.value))
	{
		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);
		
}

var logIdx = 0;

function makeLog()
{
	var bgColour = 'ffffff';

	new layer("log_layer", "imogen_body",
			600, 600, 400, 100,
			'left', 'top',
			'',
			'',
			bgColour,
			'bbbbbb',
			'', '', '',
			'images/close_button_20.gif', null);

	var logg = findObj('log_layer_client');

	if (!logg)
	{
		return;
	}

	var logDiv = document.createElement("DIV");
	logDiv.id = 'log_div';
	logDiv.style.overflow = 'auto';
	logDiv.width = 580 + "px";
	logDiv.height = 580 + "px";

	logg.appendChild(logDiv);

}

function writeLog(msg)
{

	var logDiv = findObj('log_div');
	if (!logDiv)
	{
		makeLog();
		logDiv = findObj('log_div');
		if (!logDiv)
		{
			return;
		}
	}

	var msgDiv  = document.createElement("DIV");
	msgDiv.width = 570 + "px";

	var idxSpan = document.createElement("SPAN");
	idxSpan.width = 40 + "px";
	var spIdxText = document.createTextNode("[" + (++logIdx) + "] ");
	idxSpan.appendChild(spIdxText);

	var msgSpan = document.createElement("SPAN");
	msgSpan.width = 520 + "px";

	spMsgText = document.createTextNode(msg.replace(/\;/g, "; "));

	msgSpan.appendChild(spMsgText);

	msgDiv.appendChild(idxSpan);
	msgDiv.appendChild(msgSpan);
	logDiv.appendChild(msgDiv);
}

function makeLoginForm(formDiv, formId, parentId, 
						formWidth, formHeight,
						formX, formY, 
						formBackgroundColour, formTitleBarColour )
{
	writeLog("making login form");
	
	new layer(formId, parentId,
			formWidth, formHeight, 
			formX, formY,
			'center',
			'top',
			formBackgroundColour,
			formTitleBarColour,
			'', '', '',
			'images/close_button_20.gif', null);

	var fform = findObj(formId + '_client');

	if (!fform)
	{
		writeLog("ERROR: couldn't find " +  formId + '_client');
		return;
	}

	fform.appendChild(formDiv);

}

function getLoginDetails()
{
	return true;
	
}