function isDefined(myVar)
{
    if (typeof(myVar) != "undefined") return false;
	else return true;
}

function addLoadEvent(func) {
    var old_onload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            old_onload();
            func();
        }
    }
}

function set_title(a) {
	document.title = a;
}

function expander(obj) {
	var exsh = $(obj);
    var ex = $('.expandable',exsh.parent());
    
    // save tag text
    temp = exsh.html().substr(5);
	var speed = 150;
    if (ex.css('display')=='none') {
		ex.slideDown(speed,function(){
			exsh.removeClass('expander').addClass('collapser').html( 'Hide ' + temp );
		});
		exsh.animate({ fontSize:"9px" },speed);
    } else {
		ex.slideUp(speed,function(){
			exsh.removeClass('collapser').addClass('expander').html( 'Show ' + temp );
		});
		exsh.animate({ fontSize:"12px" },speed);
    }
}

function add_style(file) {
   var oLink = document.createElement("link");
   oLink.setAttribute("href", file);
   oLink.setAttribute("rel", "stylesheet");
   oLink.setAttribute("type", "text/css");
   document.getElementsByTagName('head')[0].appendChild(oLink);
}
function add_css(file) {
	add_style(file);	
}

function add_javascript(file) {
   var oScript = document.createElement("script");
   oScript.setAttribute("src", file);
   oScript.setAttribute("type", "text/javascript");
   document.getElementsByTagName('head')[0].appendChild(oScript);
}
function add_js(file) {
	add_javascript(file);	
}

function aql_save( theform, model, onSuccessFn, onErrorFn ) {
	message_div = model + '_message';
	if (document.getElementById( message_div ))
		document.getElementById( message_div ).innerHTML = '<img src="/images/loading3.gif" />';

	if (!onSuccessFn) {
		onSuccessFn = function (req) {
			//alert(req.responseText);
			if ( req.responseText.indexOf('redirect=')==0 ) {
				//alert(req.responseText);
				location.href = location.href + '/' + req.responseText.substring(9,req.responseText.length);
			} else if (document.getElementById( message_div )) {
				document.getElementById( message_div ).innerHTML = req.responseText;
				window.scrollTo(0,0);
			}
		};
	}
	if (!onErrorFn) {
		onErrorFn = function (req) {
			alert('There has been an error. Check your form action.');
		};
	}

	theform.method = 'post';
	theform.action = '/aql/save/' + model;
	AjaxRequest.submit(theform,{
		'aql_save' : location.href,
		'onSuccess' : onSuccessFn,
		'onError' : onErrorFn
	});	
}//function


// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function 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 toggleCheckbox(checkboxId) {
	obj = document.getElementById(checkboxId);
	if(!obj)
		return;
	if (obj.checked) obj.checked = false;
	else obj.checked = true;
	return obj.checked;
}

function process_profile_response(req,table) {
// this function is used by the profile module
	xml = new SoftXMLLib();
	xml.loadXML(req.responseText);
	alert(req.responseText);
	
	if( xml.loadXMLError != 0 ) {
		alert("The server gave an invalid response.");
	} else {
		success = xml.selectNodes('//status')[0].innerText;
		message = xml.selectNodes('//message')[0].innerText;
		ide = xml.selectNodes('//ide')[0].innerText;
		document.getElementById(table + '_response').innerHTML = message;
		document.getElementById(table + '_ide').value = ide;
	}//if
}//function

function get_event(e) {
	if (!e) {
		var e = window.event;
	}

	return e;
}

function get_target(e) {
	if (!e) {
		var e = window.event;
	}

	var targ;
	if (e.target) {
		targ = e.target;
	} else if (e.srcElement) {
		targ = e.srcElement;
	}

	if (targ.nodeType == 3) {
		// defeat Safari bug
		targ = targ.parentNode;
	}

	return targ;
}

function get_mouse_coordinates(e) {
	if (!e) {
		var e = window.event;
	}

	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	} else if (e.clientX || e.clientY) {
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

	return new Array(posx, posy);
}

function copy_to_clipboard(text2copy) {
	if (window.clipboardData) {
		window.clipboardData.setData("Text", text2copy);
	} else {
		if (! document.getElementById('flashcopier')) {
			var divholder = document.createElement('div');
			divholder.id = 'flashcopier';
			document.body.appendChild(divholder);
		}

		var clipboard_flash_object = new SWFObject
			('http://www.ezwebstuff.com/intranet/global/_clipboard.swf', 
			 'copy_contents', '0', '0', '4');
			
		clipboard_flash_object.addVariable('clipboard', escape(text2copy));
		clipboard_flash_object.write('flashcopier');
	}
}

function str_pad(str, new_len, pad_char){
	if (str.length >= new_len) return str;

	for (i = str.length; i < new_len; i++) {
		str += pad_char;
	}

	return str;
};

function trimString (str) {
    str = this != window? this : str;
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
} // function

function stripSlashes(str) {
    str = str.replace(/\\'/g, '\'');
    str = str.replace(/\\"/g, '"');
    str = str.replace(/\\0/g, '\0');
    str = str.replace(/\\\\/g, '\\');
    return str;
} // function

function addSlashes(str) {
    str = str.replace(/\\/g, '\\\\');
    str = str.replace(/\\0/g, '\0');
    str = str.replace(/"/g, '\\"');
    str = str.replace(/\'/g, '\\\'');
    return str;
} // function

/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function QueryString(qs) { // optionally pass a querystring to parse
	this.params = new Object();
	this.get = QueryString_get;
	
	if (qs == null) {
		qs = location.search.substring(1, location.search.length);
	}

	if (qs.length == 0) { 
		return;
	}

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &
	
	// split out each name=value pair
	for (var i=0; i < args.length; i++) {
		var value;
		var pair = args[i].split('=');
		var name = unescape(pair[0]);

		if (pair.length == 2) {
			value = unescape(pair[1]);
		} else {
			value = name;
		}
		
		this.params[name] = value;
	}
}

function QueryString_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) {
		default_ = null;
	}
	
	var value = this.params[key];
	if (value == null) {
		value = default_;
	}
	
	return value;
}

// ///////////////////////////
// isDefined v1.0
// 
// Check if a javascript variable has been defined.
// 
// Author : Jehiah Czebotar
// Website: http://www.jehiah.com
// Usage  : alert(isdefined('myvar'));
// ///////////////////////////

function isDefined(variable) {
    return (typeof(eval('variable')) == "undefined") ?  false : true;
}

function confirm_leave(msg) {
	if (msg) {
		return msg;
	}

	return confirm('Are you you sure you want to leave this page? All unsaved changes will be lost.');
}

function windowHeight() {
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  return myHeight;
}

function windowWidth() {
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  return myWidth - scrollbarWidth();
}

function pageHeight() {
	var pageHeight = 0;
	if ( window.innerHeight && window.scrollMaxY ) {
		// Firefox 
		pageHeight = window.innerHeight + window.scrollMaxY;
	}
	else if ( document.body.scrollHeight > document.body.offsetHeight ) {
		// all but Explorer Mac
		pageHeight = document.body.scrollHeight;
	} else {
		// works in Explorer 6 Strict, Mozilla (not FF) and Safari
		pageHeight = document.body.offsetHeight + document.body.offsetTop; 
	}
	return pageHeight;
}

function pageWidth() {
	var pageWidth = 0;
	if ( window.innerHeight && window.scrollMaxY ) {
		// Firefox 
		pageWidth = window.innerWidth + window.scrollMaxX;
	}
	else if ( document.body.scrollHeight > document.body.offsetHeight ) {
		// all but Explorer Mac
		pageWidth = document.body.scrollWidth;
	} else {
		// works in Explorer 6 Strict, Mozilla (not FF) and Safari
		pageWidth = document.body.offsetWidth + document.body.offsetLeft;  
	}
	return pageWidth - scrollbarWidth();
}

function scrollbarWidth() {
	document.body.style.overflow = 'hidden';
	var width = document.body.clientWidth;
	document.body.style.overflow = 'scroll';
	width -= document.body.clientWidth;
	if(!width) width = document.body.offsetWidth-document.body.clientWidth;
	document.body.style.overflow = '';
	return width;
}

function onEnter(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	if(keycode == 13){
		return true;
	} else {
		return false;
	}
}

//  Simulates PHP's date function
//
//	Documentation @ http://jacwright.com/projects/javascript/date_format
//	
//  var MyDate = new Date();
//	var now = MyDate.format('M jS, Y'); 
//
//  returns May 11th, 2006


Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else {
			returnStr += curChar;
		}
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return (((this.getFullYear()%4==0)&&(this.getFullYear()%100 != 0)) || (this.getFullYear()%400==0)) ? '1' : '0'; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60)); },
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d") + "T" + this.format("H:i:sP"); },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};
