/*
+----------------------------------------------------------------------------
|	Useful little tools
+----------------------------------------------------------------------------
*/

/*
 * Fire bug console logger.
 */
function printfire()
{
    if (document.createEvent)
    {
      try {
        printfire.args = arguments;
        var ev = document.createEvent("Events");
        ev.initEvent("printfire", false, true);
        dispatchEvent(ev);
      } catch (e) {};
    }
}

/*
 *  function ObjSplat(obj, msg)
 */
function ObjSplat(obj, msg) {
	splat_msg = "";
	splat_text = "";
	if (typeof msg != "undefined") { splat_text += msg + "\n\n\n"; }
	for (var name in obj) {
		val = obj[name];
		splat_text += name + ": " + val + "\n";
	}
	alert(splat_text);
}

/*
 *  function FireSplat
 */
function FireSplat(val)
{
    printfire(JSON.stringify(val));
}

/*
 *  function ObjCopy
 */
function ObjCopy(obj) {
	return obj;
}


/*
 *  function TestAlert()
 *		limit the number of alerts.  avoid insanity.
 */
var Debug_Alert = false;
function dalert(msg) {
    if (Debug_Alert) {
        alert("DEBUG:\n\n" + msg);
    }
}


/*
 *  function TestAlert()
 *		limit the number of alerts and avoid insanity.
 */
var TestAlertLimit = 10;
var TestAlertCounter = 0;
function TestAlert(msg) {
	if (TestAlertCounter < TestAlertLimit) {
		alert("[" + (TestAlertCounter + 1 - 0) + "] " + msg);
		TestAlertCounter++;
	}
}


/*
 *  function TestDump()
 *		limit the number of dumps.  avoid insanity.

var TestDumpLimit = 1;
var TestDumpCounter = 0;
DumperTagProperties["OPTION"] = ['text','value','defaultSelected'];
function TestDump(obj)
{
    if (TestDumpCounter < TestDumpLimit)
    {
        //DumperAlert(obj);
    }
    TestDumpCounter++;
}
*/


/*
 *  function TestSplat()
 *		limit the number of splats.  avoid insanity.
 */
var TestSplatLimit = 1;
var TestSplatCounter = 0;
function TestSplat(obj) {
	if (typeof TestSplatLimit != "undefined") {
		if (TestSplatCounter < TestSplatLimit) {
			ObjSplat(obj);
			TestSplatCounter++;
		}
	}
}



/*
 *  _sortByProperty(property,rev)
 *		sort array of objects by object propery
 *		optional parameter to reverse sort order
 */
function _sortByProperty(property,rev) {
	var dir = rev ? 1 : -1;
	var fn = function(a,b) {
		//TestAlert(a[property] + " ... " + b[property]);
		if (a[property] < b[property]) {
			return dir;
		} else if (a[property] > b[property]) {
			return -dir;
		} else {
			return 0;
		}
	}
	this.sort(fn);
	return this;
}
//Array.prototype.sortByProperty = _sortByProperty;


/*
 *  _sortByProperty(property,rev)
 *		sort array of objects by object propery
 *		optional parameter to reverse sort order
 */
function _sortByProperty2(property,property2,rev) {
	var dir = rev ? 1 : -1;
	var fn = function(a,b) {
	  var a1 = a[property];
	  var b1 = b[property];
	  if (a1 < b1) return dir;
	  if (a1 > b1) return -dir;

	  var a2 = a[property2];
	  var b2 = b[property2];
	  if (a2 < b2) return dir;
	  if (a2 > b2) return -dir;
	  return 0;
	}

	this.sort(fn);
	return this;
}
//Array.prototype.sortByProperty2 = _sortByProperty2;


/*
 *  UpdateInnerHTML(divID,Msg)
 */
function UpdateInnerHTML(divID,Msg,Add) {
	//alert(divID);
	if (IsDef(Add)) {
	    Msg = document.getElementById(divID).innerHTML + Msg;
	}
	document.getElementById(divID).innerHTML = Msg;
}
function UpdateDivInnerHTML(divID,Msg,Add) {    //depreciated -- bad name.  Use UpdateInnerHTML
    return UpdateInnerHTML(divID,Msg,Add);
}


/*
 *  DisplayBatch(shows, hides)
 */
function DisplayByList(prop, list) {
    if (IsDef(list)) {
        var ListArray = list.split(',');
        for(i=0; i<ListArray.length; i++) {
            ToggleDisplay(ListArray[i],prop);
        }
    }
}


/*
 *  ToggleDisplay()
 */
function ToggleShow(widget, force) {
	ToggleDisplay(widget, force);
}
function ToggleDisplay(widget, force) {
    cog = document.getElementById(widget);
    if (cog == 'null') alert("ID does not exist:  " + widget);
	styleObj = cog.style;
	if (IsDef(styleObj)) {
	    if (typeof force == "undefined") {
	    	if (styleObj.display=='none') {
	    		styleObj.display = '';
	    	} else {
	    		styleObj.display = 'none';
	    	}
	    } else {
	    	styleObj.display = force;
	    }
	}
}


/*
 *  ToggleVisibility()
 */
function ToggleVisibility(widget, force) {
	styleObj = document.getElementById(widget).style;
	if (typeof force == "undefined") {
		if (styleObj.visibility=='hidden') {
			styleObj.visibility = 'show';
		} else {
			styleObj.visibility = 'hidden';
		}
	} else {
		styleObj.visibility = force;
	}
}


/*
 *  GetCheckboxValue()
 */
function GetCheckboxValue(box) {
	if (typeof box != "undefined") {
		return box.checked;
	}
	return false;
}


/*
 *  GetRadioValue()
 */
function GetRadioValue(radio_group) {
	if (typeof radio_group != "undefined") {
		for(i=0;i<radio_group.length;i++) {
			if (radio_group[i].checked) {
				return radio_group[i].value;
			}
		}
	}
	return false;
}


/*
 *  SetRadioValue()
 */
function SetRadioValue(radio_group, value) {
	if (typeof radio_group != "undefined") {
		for(i=0;i<radio_group.length;i++) {
			if (radio_group[i].value == value) {
			    radio_group[i].checked = true;
				return radio_group[i].value;
			}
		}
	}
	return false;
}


/*
 *  GetTextValue()
 */
function GetTextValue(text_field) {
	if (typeof text_field != "undefined") {
		return text_field.value;
	}
	return false;
}


/*
 *  SetTextValue()
 */
function SetTextValue(text_field, value) {
	if (typeof text_field != "undefined") {
		text_field.value = value;
		return text_field.value;
	}
	return false;
}


/*
 *  GetSelectedValue()
 */
function GetSelectedValue(select_list) {
	if (typeof select_list != "undefined") {
		for(i=0;i<select_list.length;i++) {
			if (select_list[i].selected == true) {
				return select_list[i].value;
			}
		}
	}
	return false;
}


/*
 *  GetSelectedValue()
 */
function SetSelectedValue(select_list,value) {
	if (typeof select_list != "undefined") {
		select_list.selectedIndex = -1;
		for(i=0;i<select_list.length;i++) {
			if (select_list[i].value == value) {
				select_list.selectedIndex = i;
				return select_list[i].value;
			}
		}
	}
	return false;
}


/*
 *  SelectOptionBuilder()
 *
 *		Use an object element name as the option value and the object element
 *		value as the option name:
 *			foo.OP1 = "Option 1";
 *			<option value='OP1'>Option 1</option>
 */
function SelectOptionBuilder(select_obj, select_field, mod_obj) {
	current_selected = "";
	if (select_field.length > 0) {
	    if (select_field.selectedIndex >= 0) {
		    var current_selected = select_field[select_field.selectedIndex].value;
	    }
	}
	select_field.options.length = 0;
	var i = 0;
	if (typeof mod_obj != "undefined") {
		if (typeof mod_obj.add_select != "undefined") {
			select_field.options[i] = new Option('Select','');
			i++;
		}
	}
	var selected_index = false;

	for (var option_value in select_obj) {
		option_name = select_obj[option_value];
		option_name = option_name.replace(/&nbsp;/g," ");
		select_field.options[i] = new Option(option_name,option_value);
		if ( (option_value == current_selected) && (selected_index == false) ) {
			selected_index = i;
			select_field.selectedIndex = selected_index;
		}
		i++;
	}
}


/*
 *  Gebi()
 */
function Gebi(widget) {
	return document.getElementById(widget);
}


/*
 *  SetStyleById()
 */
function SetStyleById(widget, name, value) {
  var elem = Gebi(widget);
  if (elem == null) return;
  elem.style[name] = value;
}


/*
 *  SetClassById()
 */
function SetClassById(widget, value) {
  var elem = Gebi(widget);
  if (elem == null) return;
  elem.className = value;
}


/*
 *  SetClassById()
 */
function FormElementDisable(formo, bgColor, enable, widget_arr)
{
    if (widget_arr.length > 0)
    {
        flag = (enable)?false:true;
        for(i=0; i<widget_arr.length; i++)
        {
            widget = widget_arr[i];
            if (IsDef(formo[widget]))
            {
                widg = formo[widget];
                //ObjSplat(widg);
                if (IsDef(widg[0]))
                {
                    field_type = 'RADIO';
                } else {
                    field_type = widg.nodeName;
                }
                switch (field_type)
                {
                    case 'SELECT':
                        widg.disabled = flag;
                        break;
                    case 'INPUT':
                        widg.disabled = flag;
                         break;
                    case 'RADIO':
                        for(j=0;j<widg.length;j++) {
                            widg[j].disabled = flag;
                        }
                        break;
                }
            } else {
                alert('Disable element not found');
            }
        }
    }
}


/*
 *  IsNumeric()
 */
function IsNumeric(sText) {
    var ValidChars = "-.0123456789";
    var IsNumber=true;
    var Char;
    var j;
	if (sText == "") { return false; }
    for (j = 0; j < sText.length && IsNumber == true; j++) {
      Char = sText.charAt(j);
      if (ValidChars.indexOf(Char) == -1) {
        IsNumber = false;
      }
    }
    return IsNumber;
  }


/*
 *  IsDef()
 */
function IsDef(cog) {
	return typeof cog != "undefined";
}


/*
 *  Trim(str)
 */
function Trim(str) {
        if (typeof str == "string")
		return str.replace(/^\s+|\s+$/g,"");
        else
                return str;
}


/*
 *  Padder(str)
 */
function Padder(Str, TotalLength, Padder) {
    Str = Str.toString();
    Padder = Padder.toString();
    var PadStr = '';
    if (TotalLength > Str.length) {
        for (i=0; i < (TotalLength-Str.length); i++) {
            PadStr += Padder;
        }
    }
    return PadStr + Str.toString();
}


/*
 *  Sleep(timer)
 */
function WasteTime() {
	//alert(GlobalSleeper);
	return true;
}
function Sleep(timer) {
	var then,now;
	then=new Date().getTime();
	now=then;
	while((now-then)<timer) {
		now=new Date().getTime();
	}
}


/*
 *
 */
function Set_Cookie( name, value, expires, path, domain, secure )
    {
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires )
    {
    expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}
// this function gets the cookie, if it exists
function Get_Cookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring( 0, name.length ))) {
        return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
}
// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
    if (Get_Cookie(name)) {
        document.cookie = name + "=" +((path)?";path="+path:"")+((domain)?";domain="+domain:"")+";expires=Thu, 01-Jan-1970 00:00:01 GMT;";
    }
}


/*
 *      GetGETObj
 *          return value-pair Object of get variables
 */
function GetGETObj()
{
    GetObj = new Object();
    if (document.URL.indexOf('?') != -1)
    {
        var GS = document.URL.substring(document.URL.indexOf('?')+1, document.URL.length);
        GSArr = GS.split("&");
        for (i=0;i<GSArr.length;i++)
        {
            GSpair = GSArr[i].split("=");
            GetObj[GSpair[0]] = GSpair[1];
        }
    }
    return GetObj;
}


/*
 *  SetFormValues(obj,form);
 *      obj is form field: value pairs
 */
function SetFormValues(obj, formo)
{
    for (field in obj)
    {
        if (typeof formo[field] != 'undefined')
        {
            setInputValue(formo[field],obj[field]);
        }
    }
}

