

function getElement(id) {
	if(typeof(id) !== "string") {
		return id;
	}
	return document.getElementById(id);
}

function Element(t) {
	return document.createElement(t);	
}

function FilledElement(t,h) {
	var d = Element(t);
	if(t == "img") {
		d.setAttribute("src",h);
		return d;		
	}
	
	if (is_array(h)) {
		for (var i = 0; i < h.length; i++) {
			var x = h[i];
			switch (typeof(x)) {
				case "string":
					d.innerHTML += x;
					break;
				default:
					d.appendChild(x);
			}
		}
	}
	else {
		switch (typeof(h)) {
			case "string":
				d.innerHTML = h;
				break;
			default:
				d.appendChild(h);
		}
	}
	if(typeof(arguments[2]) !== "undefined") {
		d.className = arguments[2];
	}
	return d;
}


function Clear(d) {
	if(typeof(d) == "string") {
		d = getElement(d);
	}
	d.innerHTML = "";
}



var ElementGroup = {
	getByPrefix: function(type,prefix) {
		var coll = document.body.getElementsByTagName(type);
		var matches = new Array();
		for(var i=0;i<coll.length;i++) {
			//alert(coll[i].id)
			if(coll[i].id.indexOf(prefix) != -1) {
				matches.push(coll[i]);
			}
		}
		return matches;
	}
}









function openHelper(url, width, height){
    var today = new Date();
    var name = today.getTime();
    var helperWindow = window.open(url, name, 'width=' + width + ',height=' + height + ',resizable=yes,scrollbars=yes,menubar=yes,status=yes,location=yes');
}

function openHelper_fixed(url, width, height){
    var today = new Date();
    var name = today.getTime();
    var helperWindow = window.open(url, name, 'width=' + width + ',height=' + height + ',resizable=no,scrollbars=no,menubar=no,status=no,location=no');
}


function geturl(url){
    window.location = url;
}


function show(d){
	if(is_array(d)) {
		for(var i=0;i<d.length;i++) {
			show(d[i]);
		}
	}
	d = getElement(d);
	d.style.display = "block";
	return d;
}

function hide(d) {
	if(is_array(d)) {
		for(var i=0;i<d.length;i++) {
			hide(d[i]);
		}
	}
	d = getElement(d);
	if (typeof(d) !== "undefined") {
		d.style.display = "none";
	}
	return d;
}

function toggle_div(d){
    d = getElement(d);
    if (d.style.display != "none") {
        d.style.display = "none";
    }
    else {
        d.style.display = "block";
    }
}

function toggle_status(d){
    d = getElement(d);
    if (d.style.display != "none") {
        return true;
    }
    else {
        return false;
    }
}


var hilite_bkgds = new Array("transparent", "#ededed");
var hilite_weights = new Array();
function hilite_row(who, how){
    cells = who.getElementsByTagName("td");
    for (i = 0; i < cells.length; i++) {
        cells[i].style.backgroundColor = hilite_bkgds[how];
    }
}





var Table = {
	alternate_backgrounds: function(tid,css_base,css_lite,css_dark) {
		var skip = "__INVALID_CLASSNAME__that_you_would_NEVER_ACTUALLY_USE__";
		if(typeof(arguments[4] == "string")) {
			skip = arguments[4];
		}
		
		var tbody;
		if (typeof(tid) === "string") {
			tbody = getElement(tid).getElementsByTagName("tbody")[0];
		} else {
			tbody = tid.getElementsByTagName("tbody")[0];
		}
		var rows = tbody.getElementsByTagName("tr");
		var index = -1;
		for(var i=0;i<rows.length;i++) {
			var matched = 0;
			var cells = rows[i].getElementsByTagName("td");
			for(var q=0;q<cells.length;q++) {
				var td = cells[q];
				if(td.className == skip) {
					break;
				}
				matched = 1;
				if (index % 2) {
					td.className = css_base + " " + css_dark;
				} else {
					td.className = css_base + " " + css_lite;
				}
			}
			if (matched) {
				index++;
			}
		}
	}
}




function fill_selectbox(boxID, opt_ar){
    var box = getElement(boxID);
    for (var i in opt_ar) {
        var opt = document.createElement("OPTION");
        opt.setAttribute("value", opt_ar[i][0]);
        if (BrowserDetect.browser == "Explorer") {
            opt.setAttribute("label", opt_ar[i][1]);
        }
        else {
            opt.text = opt_ar[i][1];
        }
        box.appendChild(opt);
    }
}


var Selectbox = {
	fill: function(boxID, opt_ar) {
	    var box = getElement(boxID);
		if(!is_array(opt_ar)) {
			var tmpar = new Array();
			for(var i in opt_ar) {
				tmpar.push( { "label": opt_ar[i], "value": i} );
			}
			opt_ar = tmpar;
		}
	    for (var i=0;i<opt_ar.length;i++) {
	        var opt = Element("OPTION");
			var choice = opt_ar[i];
			if(typeof(choice.value) != "string" && typeof(choice.value) != "number") {
				var value = choice;
				choice = { "label": value, "value": value };
			}
	        opt.setAttribute("value", choice.value);
	        if (BrowserDetect.browser == "Explorer") {
	            opt.setAttribute("label", choice.label);
	        }
	        else {
	            opt.text = choice.label;
	        }
	        box.appendChild(opt);
   		}
	},
	
	
	find: function(id,val) {
		var opts = getElement(id).options;
		for(var i=0;i<opts.length;i++) {
			var test_value = opts[i].value;
			if(test_value == val) {
				return i;
			}
			var test_int = intval(test_value,10);
			var val_int = intval(val,10);
			if(test_int && val_int && test_int == val_int) {
				return i;
			}
		}
		return false;
	},
	
	reset: function(id) {
		getElement(id).selectedIndex = 0;
	},
	
	set: function(id,index) {
		var box = getElement(id);
		if(index < box.options.length) {
			box.selectedIndex = index;
		}
	},
	
	get: function(id,index) {
		var box = getElement(id);
		return box.options[box.selectedIndex].value;
	},
	
	get_label: function(id) {
		var box = getElement(id);
		if(BrowserDetect.browser == "Explorer") {
			return box.options[box.selectedIndex].label;
		}
		return box.options[box.selectedIndex].text;
	}
	
	
}




var Checkbox = {
	check: function(id,h) {
		if(h !== false) {
			getElement(id).checked = "true";
		} else {
			getElement(id).checked = "";
		}
	},
	
	state: function(id) {
		if(getElement(id).checked) {
			return true;
		}
		return false;
	},
	
	value: function(id) {
		if(this.state(id) !== false) {
			return getElement(id).value;
		}
		return false;		
	}
	
	
}



function radioBtn_getCheckedValue(radioObj){
    //radioObj = document.elements[radioObj];
    if (!radioObj) 
        return "_UNCHECKED_";
    var radioLength = radioObj.length;
    if (radioLength == undefined) 
        if (radioObj.checked) 
            return radioObj.value;
        else 
            return "_UNCHECKED_";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "_UNCHECKED_";
}


function radioBtn_setCheckedValue(radioObj, newValue){
    if (!radioObj) 
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}



function toggle_exclusive_pair(obj_on, obj_off, field, val){
    getElement(obj_on).checked = "checked";
    getElement(obj_off).checked = "";
    getElement(field).value = val;
}



function toggle_exclusive_group(obj_on,group_ar,field,val) {
	for(var i=0;i<group_ar.length;i++) {
		var d = group_ar[i];
		if (typeof(obj_on) !== "undefined") {
			if (obj_on != d) {
				d = getElement(d);
				if (typeof(d) !== "undefined") {
					d.checked = "";
				}
			}
		}
	}
	getElement(field).value = val;
	obj_on = getElement(obj_on);
	if (typeof(obj_on) !== "undefined") {
		obj_on.checked = "checked";
	}
}


function reset_exclusive_group(group_ar,field,val) {
	for(var i=0;i<group_ar.length;i++) {
		var d = group_ar[i];
		getElement(d).checked = "";
	}
	getElement(field).value = val;
}













function concat(delim,pieces) {
	return pieces.join(delim);
}




function CRLF_to_BR(s) {
	s = s.replace(/\r/g,"");
	return s.replace(/\n/g,"<br/>");	
}



function remove_escaping(s) {
	if(typeof(s) !== "string") {
		return "";
	}
	s = s.replace(/\&quot;/g,"\"");
	s = s.replace(/\\'/g,"'");
	return s;
}

function add_escaping(s) {
	s = s.replace(/\"/g,"&quot;");
	return s;
}


function set_content(element,content) {
	element.innerHTML = content;
}


var is_array = function(v){
    return v &&
    typeof(v) === "object" &&
    typeof(v.length) === "number" &&
    typeof(v.splice) === "function" &&
    !(v.propertyIsEnumerable("length"));
};



function intval(mixed_var, base){
    // Get the integer value of a variable
    // 
    // +    discuss at: http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_intval/
    // +       version: 809.522
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: stensi
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
    // *     example 4: intval('09');
    // *     returns 4: 9
    
    var tmp;
    
    
    
    if (typeof(mixed_var) == 'string') {
        tmp = parseInt(mixed_var * 1);
        if (isNaN(tmp)) {
            return 0;
        }
        else {
            return tmp.toString(base || 10);
        }
    }
    else 
        if (typeof(mixed_var) == 'number') {
            return Math.floor(mixed_var);
        }
        else {
            return 0;
        }
}// }}}




var Include = {
	included_css: new Array(),
	included_js: new Array(),
	
	css: function(file) {
		// todo: check to ensure file is not already included...
		this.included_css.push(file);
		
		var head = document.getElementsByTagName("head")[0];
		var css = document.createElement("link");
		css.type = "text/css";
		css.rel = "stylesheet";
		css.href = file;
		css.media = "screen";
		head.appendChild(css);
	},
	
	JS: function(file) {
		// todo: check to ensure file is not already included...
		this.included_js.push(file);
		
		var head = document.getElementsByTagName("head")[0];
		var sc = document.createElement("script");
		sc.type = "text/javascript";
		sc.src = file;
		head.appendChild(sc);
	}
	
}



var ThisInstance = {
	onloaders: new Array(),
	
	add_onload: function(funref) {
		this.onloaders.push(funref);		
	},
	
	init: function() {
		for(var i=0;i<this.onloaders.length;i++) {
			eval(this.onloaders[i]);
		}
	}
	
}





var Position = {
	topLeft: function(obj){
		var topValue = 0, leftValue = 0;
		if(typeof(obj) === "string") {
			obj = getElement(obj);
		}
		while (obj) {
			leftValue += obj.offsetLeft;
			topValue += obj.offsetTop;
			obj = obj.offsetParent;
		}
		return {
			"x": leftValue,
			"y": topValue
		};
	}
}



var ConstrainInput = {
	to_numbers: function(obj) {
		obj = getElement(obj);
		obj.value = obj.value.replace(/[^0-9]/g,'');
	}
}

////////////////////////////////////



function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=getElement('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=getElement('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = "100%";//document.body.scrollWidth+'px';
        var pageHeight = "100%";document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = "100%";//document.body.offsetWidth+'px';
      var pageHeight = "100%";//document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= "4800px";
	dark.style.top = self.pageYOffset;
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
  
  	
}



function center(div) {
div = getElement(div);
var Xwidth = parseInt(div.innerWidth);
var Yheight = parseInt(div.innerHeight);

//alert(Xwidth + "x" + Yheight);
Xwidth = 463;
Yheight = 500;

var scrolledX, scrolledY;
if( self.pageYOffset ) {
scrolledX = self.pageXOffset;
scrolledY = self.pageYOffset;
} else if( document.documentElement && document.documentElement.scrollTop ) {
scrolledX = document.documentElement.scrollLeft;
scrolledY = document.documentElement.scrollTop;
} else if( document.body ) {
scrolledX = document.body.scrollLeft;
scrolledY = document.body.scrollTop;
}

// Next, determine the coordinates of the center of browser's window

var centerX, centerY;
if( self.innerHeight ) {
centerX = self.innerWidth;
centerY = self.innerHeight;
} else if( document.documentElement && document.documentElement.clientHeight ) {
centerX = document.documentElement.clientWidth;
centerY = document.documentElement.clientHeight;
} else if( document.body ) {
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;
}

// Xwidth is the width of the div, Yheight is the height of the
// div passed as arguments to the function:
var leftOffset = scrolledX + (centerX - Xwidth) / 2;
var topOffset = scrolledY + (centerY - Yheight) / 2;
// The initial width and height of the div can be set in the
// style sheet with display:none; divid is passed as an argument to // the function
var o=div;//document.getElementById(divid);
var r=o.style;
r.position='absolute';
r.top = topOffset + 'px';
r.left = leftOffset + 'px';
r.display = "block";
return div;
}





//////////////////////////////////////////////////////////////////
function serialize( mixed_value ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}


function formatNumber(n) {
	if (!isFinite(n)) {
	    return n;
	}
	
	var s = ""+n, abs = Math.abs(n), _, i;
	
	if (abs >= 1000) {
	    _ = (""+abs).split(/\./);
	    i = _[0].length % 3 || 3;
	
	    _[0] = s.slice(0,i + (n < 0)) +
	           _[0].slice(i).replace(/(\d{3})/g,',$1');
	
	    s = _.join('.');
	}
	
	return s;
	}