/*
+----------------------------------------------------------------------------
|	Useful little tools
+----------------------------------------------------------------------------
*/


/*
 *  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 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 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,proptype) {
	var fn = function(a,b) {
		//TestAlert(a[property] + " ... " + b[property]);
		if (a[property] < b[property]) {
			return (rev)? 1:-1;
		} else if (a[property] > b[property]) {
			return (rev)? -1:1;
		} else {
			return 0;
		}
	}
	this.sort(fn);
	return this;
}
Array.prototype.sortByProperty = _sortByProperty;


/*
 *  UpdateInnerHTML(divID,Msg)
 */
function UpdateInnerHTML(divID,Msg,Add) {
	//alert(divID);
	if (IsDef(Add)) {
	    Msg = document.getElementById(divID).innerHTML + Msg;
	}
	var div = document.getElementById(divID);
	if( div && div!='' )
		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) {
	styleObj = document.getElementById(widget).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];
		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) {
	elem = Gebi(widget);
	elem.style[name] = value;
}


/*
 *  SetClassById()
 */
function SetClassById(widget, value) {
	elem = Gebi(widget);
	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) {
	if (typeof cog != "undefined") {
		return true;
	}
	return false;
}


/*
 *  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();
	}
}




/*
+----------------------------------------------------------------------------
|	jsBM()
|       Javascript Benchmarking
+----------------------------------------------------------------------------
*/
GetObj = GetGETObj();
if (GetObj["jsbm"] == "true") var jsON = true;
var jsBM = {

    Start : function(elem)
            {
                if (!jsON) return true;
                this.StartTime = new Date();
                this.BenchTime = new Date();
                if (IsDef(elem))
                {
                    this.elem = elem;
                    this.seperator = "<br>";
                    this.Draw(Padder('Action', 25, ' ')+" | "+Padder('Lap (sec)', 11, ' ')+" | "+Padder('Start (sec)', 11, ' ')+" "+this.seperator);
                    this.Draw(Padder('', 60, '-')+this.seperator);
                    if (this.Row(this.StartTime.getTime(), this.BenchTime.getTime(), 'Start Benchmark')) {
                        this.BenchTime = CurrentTime;
                    }
                } else {
                    this.seperator = "\n";
                }
            },

    Lap : function(Msg)
            {
                if (!jsON) return true;
                this.Row(this.StartTime.getTime(), this.BenchTime.getTime(), Msg);
            },

    Row : function(Start, Lap, Msg)
            {
                if (!jsON) return true;
                CurrentTime = new Date();
                Now = CurrentTime.getTime();
                AlertMsg = "";
                Msg = Padder(Msg, 25, ' ');
                if (IsDef(Msg)) AlertMsg += Msg + "&nbsp;|&nbsp;";
                TempStart = ((parseInt(Now) - parseInt(Start)) / 1000);
                TempStart = Padder(TempStart, 11, ' ');
                TempLap = ((parseInt(Now) - parseInt(Lap)) / 1000);
                TempLap = Padder(TempLap, 11, ' ');
                AlertMsg += TempLap + "&nbsp;|&nbsp;";
                AlertMsg += TempStart + "&nbsp;"+this.seperator;
                if (this.Draw(AlertMsg)) {
                    this.BenchTime = CurrentTime;
                }
            },

    Draw : function(AlertMsg)
            {
                if (!jsON) return true;
                if (IsDef(this.elem))
                {
                    SetStyleById(this.elem,'border','1px orange solid');
                    PreData = Gebi(this.elem).innerHTML;
                    PreData = PreData.replace(/<pre>/g,"");  PreData = PreData.replace(/<\/pre>/g,"");
                    AlertMsg = "<pre>" + PreData + AlertMsg + "</pre>";
                    UpdateInnerHTML(this.elem, AlertMsg);
                    alert("go");
                    return true;
                } else {
                    return confirm(AlertMsg);
                }
            }
}


/*
 *
 */
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;
}
