// util.js: Javascript utilities

function BrowserBack()
{
	history.go(-1);
	return true;
}

function BrowserForward()
{
	history.go(1);
	return true;
}

function isJQueryObject(e) {
	return (e != null && e.jquery);
}

function ScrollToBottom()
{
	if (document.layers) {		
		// Netscape
		window.scrollTo(0, window.innerHeight);
	} else if (document.all) {	
		// Internet Explorer 
		window.scrollTo(0, document.body.clientHeight);
	} else {
		// Any other - might cause problem
		window.scrollTo(0, 999999999);
	}
}

function SetElementFocus(_element) {

	if (typeof(WrapSelect) !== "undefined" && WrapSelect.isWrapSelectObj(_element)) {
		return WrapSelect.setFocus(_element);
	}	
	// Test offsetHeight/Width to see if element is visible
	if (_element && _element.type != 'hidden' && _element.disabled != true && 
			_element.offsetWidth != 0 && _element.offsetHeight != 0) {
		_element.focus();
		if (_element.type == 'text') {
			_element.select();
		}
		return true;
	}
	return false;
}

function SetFirstInputFocus(elems)
{
	if (!elems) elems = $j('input, select');
	else elems = $j(elems).find('input, select');
	
	var found = false;
	var loop1 = 0;
	var length1 = elems.length;
	for (var elem = elems[loop1]; loop1 < length1; elem = elems[++loop1]) {
		if (SetElementFocus(elem)) {
			found = true;
			break;
		}
	}
	return found;
	
	/*
	var theForms = document.forms;
	for (var f = 0; f < theForms.length; f++) {
		var theElements = theForms[f].elements;
		for (var e = 0; e < theElements.length; e++) {
			var _element = theElements[e];
			if (SetElementFocus(_element)) return true;
		}
	}
	return false;
	*/
}

function startBusyPleaseWaitSpin(withClose, withBackground)
{
	var bWithClose = withClose ? withClose : false;
	var bWithBackground = withBackground ? 0 : 50;
	$j.modal.open("<div class='inProgress'><div class='waitImage'><div>Please wait...</div>", { close: bWithClose, opacity: bWithBackground});
}
function stopBusyPleaseWaitSpin() 
{
	$j.modal.close();
}

function getSelectedValue(e) {
	if (typeof (WrapSelect) !== "undefined" && WrapSelect.isWrapSelectObj(e))
			return $j(e).val();
	else if(isJQueryObject(e))
			return e.find(":selected").val();

	// Safe checking
	if (e == null || e.type != 'select-one' || e.selectedIndex == -1) {
		return '-1';
	}
	return e.options[e.selectedIndex].value;
}

function getSelectTextByValue(e, value) {
	if (typeof (WrapSelect) !== "undefined" && WrapSelect.isWrapSelectObj(e)) {
		return WrapSelect.getSelectTextFromValue($j(e), value);
	}
	// Safe checking
	if (e == null || e.type != 'select-one' || value == '-1') {
		return '';
	}
	var theOptions = e.options;
	for (var i=0; i < theOptions.length; i++)
	{
		if (theOptions[i].value == value)
			return theOptions[i].text;
	}
	return '';
}

function getSelectTextByIndex(e, i)
{
	// Safe checking
	if (e == null || e.type != 'select-one' || i == -1) {
		return '';
	}
	return e.options[i].text;
}

function getSelectedText(e)
{
	if (typeof (WrapSelect) !== "undefined" && WrapSelect.isWrapSelectObj(e))
			return WrapSelect.getInputVal($j(e));
	else if(isJQueryObject(e))
			return e.find(":selected").text();

	// Safe checking
	if (e == null || e.type != 'select-one' || e.selectedIndex == -1) {
		return '';
	}
	return e.options[e.selectedIndex].text;
}

function getNextSiblingElement(_e) 
{
	// HACK - works for NN4?
	return findNextElement(_e, -1) ;

	var e = _e.nextSibling;
	while (e && e.nodeType != Node.ELEMENT_NODE) {
		e = e.nextSibling;
	}
	return e;
}

function findNextElement(_e, start) 
{
	// HACK - later - use nextSibling for IE5+ and NN6?
	if (start == -1)
		start = 0;
	var theForm = _e.form;
	var theElements = theForm.elements;
	for (var i = start; i < theElements.length; i++) {
		var e = theElements[i];
		if (e == _e)
			break;
	}
	i = ++i % theElements.length;
	return i;
}

function findNextElementName(_e, name, start) {
	// Return the index
	var theForm = findParentForm(_e);
	var theElements = findFormElements(theForm);  
	var bFoundE = false;
	if (start == -1)
		start = 0;
	else
		bFoundE = true;
	for (var i = start; i < theElements.length; i++) {
		var e = theElements[i];
		if (e == _e) {
			bFoundE = true;
			continue;
		}
		if (bFoundE == true && e.name == name) {
			return i;
		}
	}
	return -1;
}

function findFormElements(_e) {
	if (isJQueryObject(_e))
		return _e.find(":input");	

	return _e.elements;
} 
function findParentForm(_e) {
	if (isJQueryObject(_e))
		return _e.parents("form:first");
	else
		return _e.form;
}

function findElement(_form, name, type)
{
	if (name == null && type == null) // Supply at least one
		return null;
	var theForms = document.forms;
	for (var f = 0; f < theForms.length; f++) {
		var _thisform = theForms[f];
		if (_form != null && _thisform != _form)
			continue;
		var theElements = _thisform.elements;
		for (var e = 0; e < theElements.length; e++) {
			var _element = theElements[e];
			if ((name == null || _element.name == name) && (type == null || _element.type == type)) {
				return _element;
			}
		}
	}
	return null;
}

function OnFocusDisabled(_e) // Pass 'this'
{
	// For NN4x - Call this during OnFocus
	// if (document.getElementById || document.all) { // IE4+/NS6
	//		document.theForm.e.disabled = false;
	// } else if (document.layers) { // NS4
	//		document.theForm.e.oldonfocus = document.theForm.e.onfocus;
	//		document.theForm.e.onfocus    = OnFocusDisabled; // No passing e
	// }
	_e.blur();
}

function OnClickDisabled(_e) // Pass 'this'
{
	// For NN4x - Call this during OnClick
	// Undo the check
	_e.checked = _e.checked ? false : true;
	_e.blur();
}

function DoCheckAll(_form, name, bCheck)
{
	var theElements = _form.elements;
	for (var i=0; i < theElements.length; i++)
	{
		var e = theElements[i];
		if ((e.type == 'checkbox') && (e.name == name) && (e.disabled != true))
			e.checked = bCheck;
	}
}

function CheckAll(_form, name, eall)
{
	DoCheckAll(_form, name, eall.checked);
}

function CheckCheckAllQuick(e, eall)
{
	// Faster than CheckCheckAll - no rechecking if all checked
	if (e == null || eall == null)
		return false;
	if (eall.disabled == true)
		return true;
	if (e.checked == false) {
		eall.checked = false;
		return true;
	}
	return true; // Nothing to do
}

function CheckCheckAll(_form, name, allname)
{
	var TotalBoxes = 0;
	var TotalOn = 0;
	var eall = null;
	var theElements = _form.elements;
	for (var i=0; i < theElements.length; i++) {
		var e = theElements[i];
		if ((e.name != allname) && (e.type == 'checkbox') && (e.name == name)) {
			TotalBoxes++;
			if (e.checked) {
				TotalOn++;
			}
		}
		if (e.name == allname)
			eall = e;
	}
	if (eall == null) {
		alert("All checkbox does not exist!");
		return false;
	}
	if (eall.disabled == true)
		return false;
	if (TotalBoxes == TotalOn) {
		eall.checked = true;
	} else {
		eall.checked = false;
	}
	return true;
}

function HasChecked(_form, name)
{
	var theElements = _form.elements;
	for (var i=0; i<theElements.length; i++) {
		var e = theElements[i];
		if ((e.name == name) && (e.type == 'checkbox') && (e.checked)) {
			return true;
		}
	}
	return false;
}

function CountChecked(_form, name)
{
	var tally = 0;
	var theElements = _form.elements;
	for (var i=0; i<theElements.length; i++) {
		var e = theElements[i];
		if ((e.name == name) && (e.type == 'checkbox') && (e.checked)) {
			tally++;
		}
	}
	return tally;
}

function CountUnChecked(_form, name)
{
	var tally = 0;
	var theElements = _form.elements;
	for (var i=0; i<theElements.length; i++) {
		var e = theElements[i];
		if ((e.name == name) && (e.type == 'checkbox') && (!e.checked)) {
			tally++;
		}
	}
	return tally;
}

function HasOneChecked(_form, name)
{
	if (_form == null) {
		alert('Invalid form passed to hasonechecked');
		return false;
	}
	var theElements = _form.elements;
	for (var i=0; i<theElements.length; i++) {
		var e = theElements[i];
		if ((e.name == name) && (e.type == 'checkbox') && (e.checked)) {
			return true;
		}
	}
	return false;
}

function EnsureChecked(e)
{
	e.checked = true;
}

function CheckIfText(e_checkbox, e_text)
{
	if (e_text.value == "")
		e_checkbox.checked = false;
	else
		e_checkbox.checked = true;
}

function OnSubmitDisabled()
{
	alert("This form has already been submitted.");
	return false;
}

function DisableSubmits(_form)
{
	// Do just before submit - keeps double click from happening
	var theElements = _form.elements;
	for (var e = 0; e < theElements.length; e++) {
		var _element = theElements[e];
		if (_element.type == 'submit') {
			_element.onclick = function () { OnSubmitDisabled(); return false; }
		}
	}
	return true;
}

////////////////////
// Dirty functions

function setFormDirty(_form) {
	if (_form) {
		if (isJQueryObject(_form))
			_form.attr('isdirty', 1);
		else
			_form.isdirty = 1;				
	}
}

function setFormModify(_form) {
	if (_form) {
		if (isJQueryObject(_form))
			_form.attr('ismodify', 1);
		else
			_form.ismodify = 1;
	}
}

function isFormModify(_form) {
	if (_form && _form.ismodify == 1)
		return true;
	return false;
}

function isFormDirty(_form)
{
	if (_form && _form.isdirty == 1)
		return true;
	return false;
}

function okIfDirty(_form)
{
	if (isFormDirty(_form)) {
		if (!confirm('Changes will be lost.  Continue without saving?'))
			return false;
	}
	return true;
}

/*	okIfDirty2 uses the non-blocking method and callbacks. */

function okIfDirty2(formElem, onOk, options)
{
	options = $j.extend({}, options);
	formElem = $j(formElem);
	
	if (isFormDirty(formElem[0])) {

		options.scrollToOptions = $j.extend({
			duration: 200,
			onAfter: function() {
				Effects.highlight(options.scrollElem);
			},
			offset: -100, // Fixed offset for now, this means leave it 100px from the top of the window
			easing: 'swing',
			duration: 500
		}, options.scrollToOptions);

		if (options.scrollElem && options.scrollElem[0]) {
			$j.scrollTo(options.scrollElem, options.scrollToOptions);
		}

		modalQuery("Confirmation", "Data has been modified. Close without saving?", {cssClass: 'message_box attention'}, [
			{cssClass: 'ok', text: 'Close without saving', onClick: function() {
				$j.modal.close();
				onOk();
			}},
			{cssClass: 'cancel', text: 'Cancel', isDefault: true, onClick: function() {
				$j.modal.close();
				if (options && options.onCancel)
					options.onCancel();
			}}
		]);
	} else {
		onOk();
	}
}


////////////////////
// Numeric functions

function isNumeric(x) 
{
	// Is x a String or a character?
	if (x.length == 0) {
		return true;
	} else if (x.length > 1) {
		for(j=0; j < x.length; j++) {
			// call isNumeric recursively for each character
			if (!isNumeric(x.substring(j, j+1)))
				return false;
		} 
		return true;
	} else {
		// if x is number return true '0' though '9' and '.'
		if (x == '0' || x == '1' || x == '2' || x == '3' || x == '4' || 
			x == '5' || x == '6' || x == '7' || x == '8' || x == '9' ||
			x == '.')
			return true;
	}
	return false;
}

function getInt(e) 
{
	if (e.value == "") return 0;
	var i = parseInt(e.value);
	if (isNaN(i)) return 0;
	return i;
}

function getFloat(e) 
{
	if (e.value == "") return 0.0;
	var f = parseFloat(e.value);
	if (isNaN(f)) return 0.0;
	return f;
}

function setFloat(e, f) 
{
	if (f == 0.0) {
		e.value = "";
	} else {
		e.value = f;
	}
}

function NumberKeyDown(event_, element_, bNeg)
{
	var keyCode = event_.keyCode ? event_.keyCode :
                  event_.which ? event_.which :
                  event_.charCode;
    var key = String.fromCharCode(keyCode);
	// Override
    if (event_.shiftKey && event_.shiftKey == true)	
		return true;
	// Special date characters
//	alert(keyCode.toString());

	// Get the new number
	var setnum = false;
	var offset = 0;
	if (keyCode == 107 || keyCode == 187) {	// key == '+'
		offset = +1;
		setnum = true;
	}
	if (keyCode == 109 || keyCode == 189) {	// key == '-'
		if (element_.value.length > 0) {	// first key = allow for negative
			offset = -1;
			setnum = true;
		}
	}
	if (setnum == true && offset != 0) {
		// Seperate initial non-numerics
		for (i = element_.value.length; i >= 0; i-= 1) {
			if (!isNumeric(element_.value.substring(i, i+1)))
				break;
		}
		var alpha = '';
		var num   = 0;
		if (i >= element_.value.length) {
			alpha = element_.value;
			num   = 0;
		} else if (i < 0) {
			num = Number(element_.value);
		} else {
			alpha = element_.value.substring(0, i+1);
			num   = Number(element_.value.substring(i+1));
		}
//		alert('alpha="' + alpha + '", num="' + num + '"');
		if (element_.value.length > 0 && element_.value.substring(0, 1) == '-' && i == 0) {
			num -= offset;	// Neg = Subtract
			if (num == 0) alpha = '';
		} else {
			num += offset;	// Pos = Add
		}
		if (bNeg == false && num < 0) num = 0;
		element_.value = alpha + num;
		element_.select(0, -1);
		// Supress the key
		return false;
	}
	return true;
}

function hasValue(obj, obj_type)
{
	if (obj_type == "TEXT" || obj_type == "PASSWORD") 
	{
    	if (obj.value.length == 0) 
      		return false;
    	else 
      		return true;
	}
    else if (obj_type == "SELECT")
	{
        for (i=0; i < obj.length; i++)
	   	{
			if (obj.options[i].selected)
				return true;
		}
       	return false;	
	}
    else if (obj_type == "SINGLE_VALUE_RADIO" || obj_type == "SINGLE_VALUE_CHECKBOX")
	{
		if (obj.checked)
			return true;
		else
       		return false;	
	}
    else if (obj_type == "RADIO" || obj_type == "CHECKBOX")
	{
        for (i=0; i < obj.length; i++)
    	{
			if (obj[i].checked)
				return true;
		}
       	return false;	
	}
}

/* Function printf(format_string,arguments...)
 * Javascript emulation of the C printf function (modifiers and argument types 
 *    "p" and "n" are not supported due to language restrictions)
 *
 * Copyright 2003 K&L Productions. All rights reserved
 * http://www.klproductions.com 
 *
 * Terms of use: This function can be used free of charge IF this header is not
 *               modified and remains with the function code.
 * 
 * Legal: Use this code at your own risk. K&L Productions assumes NO resposibility
 *        for anything.
 ********************************************************************************/
function printf(fstring)
  { var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }    
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg); 
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg)); 
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg); 
      }
    converters['E'] = function(flags,width,precision,arg) 
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);        
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);        
      }  
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  }
/* Function printf() END */

function ShowHistory(params)
{
	// tokenid, action, objecttype, objectid, objectuserid, objectdate
	var options = {
		type: 'post',
		relativeUrl: '?HistoryView',
		data: params,
		afterOnComplete: function(xhr, textStatus) {
			if (document.xhrStatus != "success")
				return;
		}
	};
	Ajax.send(options);
}

