// tools.js includes functions and prototypes that are used on many page
function addEvent(obj, evType, fn){
 if (obj.addEventListener){
  obj.addEventListener(evType, fn, true);
  return true;
 } else if (obj.attachEvent){
  var r = obj.attachEvent("on"+evType, fn);
  return r;
 } else {
  return false;
 }
}

function _cTxt(newText){ return document.createTextNode( newText) }
function _cEl(type){ return document.createElement( type ) }
function trim(paddedString){ return paddedString.replace(/^\s*|\s*$/g,""); }
function replaceText( elm, text ){
    removeAllChildNodes($(elm));
    $(elm).appendChild( _cTxt( text ) );
}
function removeAllChildNodes(node){
    while ( node.firstChild ) { node.removeChild( node.firstChild ); }
}
function evaluateReturnData( returnData ){
    return eval('(' + returnData + ')');
}
function toggleElement( el, setting ) {
  var node=$(el);
  if( node ) {
   if( setting == 'on' ) {
    node.style.display='block';
   } else if (setting == 'off') {
    node.style.display='none';   
   } else {
    if(  node.style.display=='none' ) {
      node.style.display='';
    } else {
      node.style.display='none';
    }
   }
  }
}

var throbber = document.createElement('img');
throbber.src = '/images/throbber.gif';
function createActionNotice(noticeText){
    noticeText = noticeText ? noticeText : 'Loading...';
    var newDiv = document.createElement('div');
    newDiv.className = 'notification';
    newDiv.appendChild(throbber.cloneNode(false));
    var newSpan = document.createElement('span');
    newSpan.appendChild(document.createTextNode(noticeText));
    newDiv.appendChild(newSpan);
    $('notifier-block').appendChild(newDiv);
    return newDiv;
}

function closeActionNotice(noticeElement){
    $('notifier-block').removeChild(noticeElement);
}

function  addOver(field)  { $(field).addClassName("overit"); }
function   addOut(field)  { $(field).removeClassName("overit"); }
function addFocus(field)  { $(field).addClassName("focused"); }
function  addBlur(field)  { $(field).removeClassName("focused"); }

function addScript( scriptName ){
    var scr = document.body.appendChild(document.createElement('script'));
    scr.language='javascript';
    scr.type='text/javascript';
    scr.src=scriptName;
    return scr;
}

function isEmail( string ){
    return (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1);
}

function insertAtCursor(fieldName, newValue) {
    fieldName = $(fieldName);
    if( document.selection ){
	// IE
	fieldName.focus();
	sel = document.selection.createRange();
	sel.text = newValue;
	fieldName.focus();
    } else if (fieldName.selectionStart || fieldName.selectionStart == '0') {
	fieldName.focus();
	// Mozilla and kindred
	var startPos = fieldName.selectionStart;
	var endPos = fieldName.selectionEnd;
	var scrollTop = fieldName.scrollTop;
	fieldName.value = fieldName.value.substring(0, startPos)
	    + newValue
	    + fieldName.value.substring(endPos, fieldName.value.length);
	fieldName.selectionStart = startPos + newValue.length;
	fieldName.selectionEnd = startPos + newValue.length;
	fieldName.scrollTop = scrollTop;
    } else {
	fieldName.value += newValue;
	fieldName.focus();
    }
}

Array.prototype.deleteElement = function(elementPosition){
    for( var i=elementPosition; i < (this.length-1); i++ )
	this[i] = this[i+1];

    this.length = this.length - 1;
}

Array.prototype.duplicateElement = function(elementPosition){
    // expand the length now
    this.length = this.length + 1;

    for( var i=(this.length-1); i > elementPosition; i-- ){
	this[i] = this[i-1];
    }
    if ( typeof this[elementPosition] == 'object' ) {
	this[elementPosition + 1] = cloneObject(this[elementPosition]);
    } else {
	this[elementPosition + 1] = this[elementPosition];
    }
}
Array.prototype.inArray = function( value )
// Returns TRUE if the passed value is found in the array.
{
    var i;
    for (i=0; i < this.length; i++)
        if (this[i] === value)
            return true;

    return false;
}
function cloneObject(objectToClone) {
    var tmpObject = new objectToClone.constructor();
    for ( attribute in objectToClone ) {
	if ( typeof objectToClone[attribute] == 'object' ) {
	    tmpObject[attribute] = cloneObject(objectToClone[attribute]);
	} else {
	    tmpObject[attribute] = objectToClone[attribute];
	}
    }
    return tmpObject;
}

function getOffsetLeft(elm){
    var offset = elm.offsetLeft;
    var mOffsetParent = elm.offsetParent;
    while(mOffsetParent.offsetParent){
	offset += mOffsetParent.offsetLeft;
	mOffsetParent = mOffsetParent.offsetParent;
    }
    return offset;
}

function getOffsetTop(elm){
    var offset = elm.offsetTop;
    var mOffsetParent = elm.offsetParent;
    while(mOffsetParent.offsetParent){
	offset += mOffsetParent.offsetTop;
	mOffsetParent = mOffsetParent.offsetParent;
    }
    return offset;
}

function elementWidth(elm){
    return elm.style.width.replace(/[a-z]/ig,'');
}
function makeTextHTMLSafe(text){
    text = text.replace(/\"/g, '&quot;');
    text = text.replace(/</g, '&lt;');
    return text.replace(/>/g, '&gt;');
}

// Handles loading multiple things at once
fetchingNotices = new Object();
fetchingNotices.text = 'Loading...';
fetchingNotices.count = 0;
fetchingNotices.list = new Array();
fetchingNotices.increment = function(loadingName){
    fetchingNotices.list[ loadingName ] = true;
    if( ++this.count == 1 )
	this.actionNotice = createActionNotice(this.text);
}
fetchingNotices.decrement = function(loadingName){
    if( fetchingNotices.list[ loadingName ] ) {
	fetchingNotices.list[ loadingName ] = false;
	if( --this.count == 0 ){
	    closeActionNotice(this.actionNotice);
	}
    }
}
function getDomain(){
    var domain =  location.href;
    domain = domain.match(/http[s]?:\/\/([^\/]+).*/);
    return domain[1];
}
var getRemoteValueFuncs = new Object();
function getRemoteValue(namespace,valueName,additionalArgs,completeFunction,showFetchingNotice){
    if( typeof getRemoteValueFuncs[namespace] == 'undefined' )
	getRemoteValueFuncs[namespace] = new Object();

    if( getRemoteValueFuncs[namespace][valueName] )
	return;

    if( typeof completeFunction != 'function' ){
	alert( 'ERROR: completeFunction not set (' + namespace + '/' + valueName + ')' );
	return;
    }

    getRemoteValueFuncs[namespace][valueName] = completeFunction;

    if( typeof showFetchingNotice == 'undefined' )
	showFetchingNotice = true;

    showFetchingNotice = showFetchingNotice ? true:false;

    if( showFetchingNotice )
	fetchingNotices.increment( namespace + '-' + valueName);

    if(typeof additionalArgs == 'function')
	additionalArgs='';
    if(typeof additionalArgs == 'object')
	additionalArgs = Object.toJSON(additionalArgs);

    encodedArgs = encodeURIComponent(additionalArgs);
    var parms = 'value='+encodedArgs;
    var url = '/get/json/' + namespace + '/' + valueName;

    var myAjax = new Ajax.Request(url,
				  {method: 'post',
				   postBody: parms,
				   onComplete: getRemoteValue_complete });

    return true;
}
function getRemoteValue_complete( originalRequest ){
    var returnObject = eval('(' + originalRequest.responseText + ')');
    if( ( typeof getRemoteValueFuncs[ returnObject.namespace ] == 'undefined' ) ||
	( typeof getRemoteValueFuncs[ returnObject.namespace ][ returnObject.name ] != 'function' ) ) {
	alert( 'ERROR: No function set for returning value \'' + returnObject.name +'\'' );
    } else {
	if( returnObject.response.value == null )
	    returnObject.response.value = '';
	var runFunction = getRemoteValueFuncs[ returnObject.namespace ][ returnObject.name ];
	getRemoteValueFuncs[ returnObject.namespace ][ returnObject.name ] = false;
	runFunction( returnObject );
    }
    fetchingNotices.decrement( returnObject.namespace + '-' + returnObject.name);   
}


// handles saving a few things at once.  can perform an action when last item is saved.
savingNotices = new Object();
savingNotices.text = 'Saving...';
savingNotices.count = 0;
savingNotices.list = new Array();
savingNotices.postAction;
savingNotices.postAction_set;
savingNotices.setAction = function( action ){ this.postAction_set = action; }
savingNotices.increment = function( savingName ){
    savingNotices.list[ savingName ] = true;

    if( ++this.count == 1 )
	this.actionNotice = createActionNotice(this.text);

    if( this.postAction_set ){
	this.postAction = this.postAction_set;
	this.postAction_set = false; 
    }
}

savingNotices.decrement = function( savingName ){
    if( savingNotices.list[ savingName ] ){
	savingNotices.list[ savingName ] = false;
	if( --this.count == 0 ){
	    closeActionNotice(this.actionNotice);

	    if( this.postAction ){
		this.postAction();
		this.postAction = false;
	    }
	}
    }
}

var setRemoteValueFuncs = new Object();
function setRemoteValue(namespace,valueName,value,completeFunction,showSavingNotice,valuePassThru){
    if( typeof setRemoteValueFuncs[namespace] == 'undefined' )
	setRemoteValueFuncs[namespace] = new Object();

    if( setRemoteValueFuncs[namespace][valueName] )
	return;

    if( typeof completeFunction != 'function' ){
	alert( 'ERROR: completeFunction not set (' + namespace + '/' + valueName + ')' );
	return;
    }

    setRemoteValueFuncs[namespace][valueName] = completeFunction;

    if( typeof showSavingNotice == 'undefined' )
	showSavingNotice = true;

    if( typeof valuePassThru == 'undefined' )
	valuePassThru = false;


    if( showSavingNotice )
	savingNotices.increment( namespace + '-' + valueName);

    var parms = '';
    if( ! valuePassThru ) {
	if(typeof value == 'function')
	    value='';
	if(typeof value == 'object')
	    value = Object.toJSON(value);
	encodedValue = encodeURIComponent(value);
	parms = 'value='+encodedValue;
    } else {
	parms = value;
    }

    var url = '/set/json/' + namespace + '/' + valueName;

    var myAjax = new Ajax.Request(url,
				  {method: 'post',
				   postBody: parms,
				   onSuccess: setRemoteValue_complete});
    return true;
}
function setRemoteValue_complete( originalRequest ){
    var returnObject = eval('(' + originalRequest.responseText + ')');
    
    if( ( typeof setRemoteValueFuncs[ returnObject.namespace ] == 'undefined' ) ||
	( typeof setRemoteValueFuncs[ returnObject.namespace ][ returnObject.name ] != 'function' ) ){
	alert( 'ERROR: No function set for \'' + returnObject.name +'\'' );
    } else {
	var runFunction = setRemoteValueFuncs[ returnObject.namespace ][ returnObject.name ];
	setRemoteValueFuncs[ returnObject.namespace ][ returnObject.name ] = false;
	runFunction( returnObject );
    }
    savingNotices.decrement( returnObject.namespace + '-' + returnObject.name);   
}

singleFormSubmitBool = false;
function singleFormSubmit( formName ){
  if( (! singleFormSubmitBool) && 
     $(formName).submit ) {
    singleFormSubmitBool = true;
    $(formName).submit();
  } 
}
function makeNumberPretty(number){
    number += '';
    var x = number.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
	x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

var loadedScriptFiles = new Array();
function loadScriptFile(scriptPath, fireEvent){
    var docHead = document.getElementsByTagName("head")[0];
    var newScript = _cEl('script');
    newScript.type= 'text/javascript';
    if( fireEvent ){
	loadedScriptFiles[fireEvent] = false;
	var loadFunction = function(){
	    if( loadedScriptFiles[fireEvent] ) return;
	    loadedScriptFiles[fireEvent] = true;
	    document.fire(fireEvent); 
	};
	newScript.onload = loadFunction;
	newScript.onreadystatechange = loadFunction;
    }
    newScript.src=scriptPath;
    docHead.appendChild(newScript);
}

function loadCssFile(filePath){
    var docHead = document.getElementsByTagName("head")[0];
    var newCSS  = _cEl('link');
    newCSS.type = 'text/css';
    newCSS.rel  = 'stylesheet';
    newCSS.media= 'screen';
    newCSS.href=filePath;
    docHead.appendChild(newCSS);
}
