/*
 *	History:
 *		2009????	AMM		Created
 *		20090722	AMM		Version 1.0 Launched
 *		20100105	AMM		Changed from JSON-comment-filtered to JSON
 */

var childWins		= new Array();
var	rowMarker		= '`'; 
var	fieldMarker		= '|';
var	valueMarker		= '~';
var	msgBGCaller		= '';
var	responseAction	= '';			// The action to perform after a msg or error msg is closed.
var	progRequestors	= new Array();	// Array of requestors for progress bar

var	monthNames	= new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var	dayNames	= new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');



// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
	var rest = this.slice((to || from) + 1 || this.length);
	this.length = from < 0 ? this.length + from : from;
	return this.push.apply(this, rest);
};

//Array Remove - By John Resig (MIT Licensed)
Array.prototype.removeValue = function(value) {
	if (!value) return;
	for (var x = 0; x < this.length; x++) {
		if (this[x] == value) {
			this.remove(x, x);
			return;
		}
	}
};

//	Equivalent to PHP in_array
Array.prototype.in_array = function(val) {
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == val) return true;
	}
	return false;
}

//	Change stringto Title Case
String.prototype.toProperCase = function() {
	i		=	0;
	bool	=	1;
	punct	= " ()[]{},.-_!@;:?/";
	s		= this.toLowerCase();
	while (i < s.length) {
		c	= s.substring(i, i+1);
		if (punct.indexOf(c) >= 0) {
			bool	= 1;
		} else {
			if (bool == 1) {
				if (c >= 'a' && c <= 'z') {
					s		= s.substring(0,i) + c.toUpperCase() + s.substring(i+1,s.length);
					bool	= 0;
				} else {
					if (c >= '0' && c <= '9') {
						bool	=	0;
					}
				}
			}
		}
		i++;
	}
	return s;
};

String.prototype.trim = function () {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}


if (!window.getComputedStyle) {
	window.getComputedStyle = function(el, pseudo) {
		this.el = el;
		this.getPropertyValue = function(prop) {
			var re = /(\-([a-z]){1})/g;
			if (prop == 'float') prop = 'styleFloat';
			if (re.test(prop)) {
				prop = prop.replace(re, function () {
					return arguments[2].toUpperCase();
				});
			}
			return el.currentStyle[prop] ? el.currentStyle[prop] : null;
		}
		return this;
	}
}


function goPage (href) {
	if (!href) return false;
	window.location	= href;
}


function addslashes(str) {
	str	= str.replace(/\'/g,'\\\'');
	str	= str.replace(/\"/g,'\\"');
	str	= str.replace(/\\/g,'\\\\');
	str	= str.replace(/\0/g,'\\0');
	return str;
}


function stripslashes(str) {
	str	= str.replace(/\\'/g,'\'');
	str	= str.replace(/\\"/g,'"');
	str	= str.replace(/\\\\/g,'\\');
	str	= str.replace(/\\0/g,'\0');
	return str;
}


function openBasicSubWindow(href, subWin, width, height) {
	var subWin	= (subWin == null) ? '_blank' : subWin;
	var width	= (width == null) ? 750 : width;
	var height	= (height == null) ? 400 : height;

	//	Determine Current Window Position
	if (window.screenX) {
		var x	= window.screenX;
		var y	= window.screenY;
	} else if (window.screenLeft) {
		var x	= parent.window.screenLeft;
		var y	= parent.window.screenTop;
	}

	var win	= window.open(href, subWin, "width="+ width +", height="+ height +",top="+ (y + 100) +",left="+ (x + 100) +",toolbar=0,menubar=0,location=0,status=0,scrollbars=1,resizable=1");

	childWins[childWins.length]	= win;

	win.focus();

	return win;
}


function openFullSubWindow(href, subWin) {
	var subWin	= (subWin == null) ? '_blank' : subWin;
	var width	= getScreenWidth();
	var height	= getScreenHeight();

	var win	= window.open(href, subWin, "width="+ width +", height="+ height +",top=0,left=0,toolbar=0,menubar=0,location=0,status=0,scrollbars=1,resizable=1");

	childWins[childWins.length]	= win;

	win.focus();

	return win;
}


function resizeWindow() {
	//	Get Required Size of Body
	var	requiredWidth	= document.getElementById('Page').scrollWidth + 12;
	var	requiredHeight	= document.getElementById('Page').scrollHeight;	// + document.getElementById('PageHeading').scrollHeight;
//	var	requiredWidth	= document.body.scrollWidth;
//	var	requiredHeight	= document.body.scrollHeight;

	//	Get Current Size of Body
	var	currentWidth	= document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth;
	var	currentHeight	= document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;

	//	Determine Current Window Position
	if (window.screenX) {
		var x	= window.screenX;
		var y	= window.screenY;
	} else if (window.screenLeft) {
		var x	= parent.window.screenLeft;
		var y	= parent.window.screenTop - 28;
	} else {
		x	= 0;
		y	= 0;
	}

	//	Get Screen Resolution - Compensate for Multiple Monitors (Use Window's Position)
	var	maxWidth	= screen.width * ((x <= 0) ? 1 : (Math.floor(x / screen.width) + 1)) - 10;
	var	maxHeight	= screen.height * ((y <= 0) ? 1 : (Math.floor(y / screen.height) + 1)) - 100;

	//	Determine How Much to Resize Window by to Fit Contents in
	var	resizeByx	= Math.min(requiredWidth - currentWidth, maxWidth - currentWidth);
	var	resizeByy	= Math.min(requiredHeight - currentHeight, maxHeight - currentHeight);

	//	Calculate New Dimensions
	var	newWidth	= currentWidth + resizeByx;
	var	newHeight	= currentHeight + resizeByy;

	//	Determine How Much to Move the Window by so it Stays on Monitor
	var	moveByx	= (x + newWidth > maxWidth) ?  maxWidth - (x + newWidth) : 0;
	var	moveByy	= (y + newHeight > maxHeight) ? maxHeight - (y + newHeight) : 0;

	//	Resize the Window by Difference between Required and Current (or Maximum and Current)
	window.resizeBy(resizeByx, resizeByy);
	window.moveBy(moveByx, moveByy);
}

function nl2br(text){
	text	= escape(text);
	
	var	re_nlchar	= '';
	
	if (text.indexOf('%0D%0A') > -1) {
		re_nlchar = /%0D%0A/g ;
	} else if (text.indexOf('%0A') > -1) {
		re_nlchar = /%0A/g;
	} else if (text.indexOf('%0D') > -1) {
		re_nlchar = /%0D/g;
	}
	
	if (re_nlchar) text = text.replace(re_nlchar, '<br />');

	return unescape(text);
}


function dataPostError(response, ioArgs) {
	console.debug('An error occurred...');
	console.debug('Response:');
	console.debug(response);
	console.debug('ioArgs:');
	console.debug(ioArgs);
	
	return;
}

function getScrollPosX() {
	if (window.pageXOffset) {
		//	NN4+
		return window.pageXOffset;
	} else if (document.body.scrollLeft) {
		//	IE4+
		return document.body.scrollLeft;
	} else {
		return 0;
	}
}
function getScrollPosY() {
	if (window.pageYOffset) {
		//	NN4+
		return window.pageYOffset;
	} else if (document.body.scrollTop) {
		//	IE4+
		return document.body.scrollTop;
	} else {
		return 0;
	}
}
function getScrollBarWidth() {
	var inner	= document.createElement('p');
	inner.style.width	= '100%';
	inner.style.height	= '200px';

	var outer = document.createElement('div');
	outer.style.position	= 'absolute';
	outer.style.top			= '0px';
	outer.style.left		= '0px';
	outer.style.visibility	= 'hidden';
	outer.style.width		= '200px';
	outer.style.height		= '150px';
	outer.style.overflow	= 'hidden';
	outer.appendChild(inner);

	document.body.appendChild(outer);
	var w1	= inner.offsetWidth;
	outer.style.overflow	= 'scroll';
	var w2	= inner.offsetWidth;	if (w1 == w2) w2 = outer.clientWidth;

	document.body.removeChild(outer);

	return (w1 - w2);
}

function getElementScrollPosX(el) {
	if (!el) return false;
	if (el.pageXOffset) {
		//	NN4+
		return el.pageXOffset;
	} else if (el.scrollLeft) {
		//	IE4+
		return el.scrollLeft;
	} else {
		return 0;
	}
}
function getElementScrollPosY(el) {
	if (!el) return false;
	if (el.pageYOffset) {
		//	NN4+
		return el.pageYOffset;
	} else if (el.scrollTop) {
		//	IE4+
		return el.scrollTop;
	} else {
		return 0;
	}
}


function getElementWidth(el) {
	if (!el) return false;
	return el.offsetWidth;
}
function getElementHeight(el) {
	if (!el) return false;
	return el.offsetHeight;
}

function getViewportWidth() {
	var ViewportWidth;
 
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
	if (typeof window.innerWidth != 'undefined') {
		ViewportWidth	= window.innerWidth;
	}  else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		ViewportWidth	= document.documentElement.clientWidth;
	} else {	// older versions of IE
		ViewportWidth	= document.getElementsByTagName('body')[0].clientWidth;
	}
	 
	return ViewportWidth;
}
function getViewportHeight() {
	var ViewportHeight;
 
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
	if (typeof window.innerHeight != 'undefined') {
		ViewportHeight	= window.innerHeight;
	}  else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		ViewportHeight	= document.documentElement.clientHeight;
	} else {	// older versions of IE
		ViewportHeight	= document.getElementsByTagName('body')[0].clientHeight;
	}
	 
	return ViewportHeight;
}

function getScreenWidth() {
	var screenWidth = 0;
	if (parseInt(navigator.appVersion) > 3) {
		screenWidth	= screen.width;
	} else if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)==3 && navigator.javaEnabled()) {
		var jToolkit	= java.awt.Toolkit.getDefaultToolkit();
		var jScreenSize = jToolkit.getScreenSize();
		screenWidth		= jScreenSize.width;
	}
	
	return screenWidth;
}
function getScreenHeight() {
	var screenHeight = 0;
	if (parseInt(navigator.appVersion) > 3) {
		screenHeight = screen.height;
	} else if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)==3 && navigator.javaEnabled()) {
		var jToolkit	= java.awt.Toolkit.getDefaultToolkit();
		var jScreenSize	= jToolkit.getScreenSize();
		screenHeight	= jScreenSize.height;
	}
	
	return screenHeight;
}

function createMsgCont() {
	elCont	= document.createElement('div');
	document.body.appendChild(elCont);
	
	elCont.id	= 'MsgCont';
	dojo.addClass(elCont, 'Hid');
	
	var html	= '';
	html	+= '<div id="MsgHead">Message</div>';
	html	+= '<div id="MsgText"></div>';
	html	+= '<button type="button" id="MsgClose" onclick="hideMsg();">Close</button>';
	html	+= '<div class="Clear"></div>';

	elCont.innerHTML	= html;
	
	return elCont;
}
function showMsg(msgText) {
	if (!msgText) return;
	
	hideProgress('', true);
	
	elMsgCont	= dojo.byId('MsgCont');	if (!elMsgCont) elMsgCont = createMsgCont();
	elMsgText	= dojo.byId('MsgText');

	if (elMsgCont && elMsgText) {
		elMsgText.innerHTML	= nl2br(msgText);
		centreCont(elMsgCont);
		showMsgBG('msg');
		dojo.removeClass(elMsgCont, 'Hid');
		dojo.byId('MsgClose').focus();
	}
}
function hideMsg() {
	elMsgCont	= dojo.byId('MsgCont');
	if (elMsgCont) dojo.addClass(elMsgCont, 'Hid');
	hideMsgBG('msg');
	
	performAction();	// Perform any required actions
}

function createErrorCont() {
	elCont	= document.createElement('div');
	document.body.appendChild(elCont);
	
	elCont.id	= 'ErrCont';
	dojo.addClass(elCont, 'Hid');
	
	var html	= '';
	html	+= '<div id="ErrHead">Error</div>';
	html	+= '<div id="ErrText"></div>';
	html	+= '<button type="button" id="ErrClose" onclick="hideError();">Close</button>';
	html	+= '<div class="Clear"></div>';

	elCont.innerHTML	= html;
	
	return elCont;
}
function showError(errText, action) {
	if (!errText) return;
	
	hideProgress('', true);
	
	elErrCont	= dojo.byId('ErrCont');	if (!elErrCont) elErrCont = createErrorCont();
	elErrText	= dojo.byId('ErrText');

	if (elErrCont && elErrText) {
		elErrText.innerHTML	= nl2br(errText);
		centreCont(elErrCont);
		showMsgBG('error');
		dojo.removeClass(elErrCont, 'Hid');
		dojo.byId('ErrClose').focus();
	}
}
function hideError() {
	elErrCont	= dojo.byId('ErrCont');
	if (elErrCont) dojo.addClass(elErrCont, 'Hid');
	hideMsgBG('error');
	
	performAction();	// Perform any required actions
}

function createHelpCont() {
	elCont	= document.createElement('div');
	document.body.appendChild(elCont);
	
	elCont.id	= 'HelpCont';
	dojo.addClass(elCont, 'Hid');
	
	var html	= '';
	html	+= '<div id="HelpHead">ipointments Help</div>';
	html	+= '<div id="HelpText"></div>';
	html	+= '<button type="button" id="HelpClose" onclick="hideHelp();">Close</button>';
	html	+= '<div class="Clear"></div>';

	elCont.innerHTML	= html;
	
	return elCont;
}

function fetchHelp(ref) {
	showProgress('FetchHelp');
	
	var xhrArgs = {
    	url: 'fetches/fetch_help.php?ref='+ ref,
    	handleAs: 'json',
    	preventCache: true,
    	timeout: 15000,
    	load: function (response, ioArgs) {
			return response;
		},
		error: function (response, ioArgs) {
			if (response.dojoType == 'timeout') {
				error('The request for help has timed out.\n\nPlease try again.', 'fetch-TimeOut', false);
			} else {
				error('An error has occurred while attempting to retrieve the help for this topic.\n\nPlease try again.', 'fetch-Error', false);
			}
			return response;
		},
		handle: function (response, ioArgs) {
			hideProgress('FetchHelp');
			
			if (response) {
				if (response.help) showHelp(urldecode(response.help), urldecode(response.title));
				if (response.msg) showMsg(urldecode(response.msg));
				if (response.error) showError(urldecode(response.error));
			}
			
			return response;
		}
	};

	//Call the asynchronous xhrGet
	var deferred = dojo.xhrGet(xhrArgs);
	
	return deferred;
}
function showHelp(helpText, title) {
	if (!helpText) return;
	
	elHelpCont	= dojo.byId('HelpCont');
	if (!elHelpCont) elHelpCont = createHelpCont();
	
	elHelpText	= dojo.byId('HelpText');

	if (elHelpCont && elHelpText) {
		elHelpText.innerHTML	= nl2br(helpText);
		centreCont(elHelpCont);
		showMsgBG('help');
		dojo.removeClass(elHelpCont, 'Hid');
		dojo.byId('HelpClose').focus();
	}
}
function hideHelp() {
	elHelpCont	= dojo.byId('HelpCont');
	if (elHelpCont) dojo.addClass(elHelpCont, 'Hid');
	hideMsgBG('help');
}

function createMsgBG() {
	elCont	= document.createElement('div');
	document.body.appendChild(elCont);
	
	elCont.id	= 'MsgBG';
	dojo.addClass(elCont, 'Hid');
	
	resizeBG(elCont)
	
	return elCont;
}
function showMsgBG(caller) {
	if (caller) msgBGCaller = caller;
	
	elMsgBG	= dojo.byId('MsgBG');
	if (elMsgBG) {
		resizeBG(elMsgBG);
	} else {
		elMsgBG = createMsgBG();
	}
	
	dojo.removeClass(elMsgBG, 'Hid');
}
function hideMsgBG(caller) {
	//	Do not close BG if this was not the most current caller
	if (caller && msgBGCaller != caller) return false;
	
	elMsgBG	= dojo.byId('MsgBG');
	if (elMsgBG) dojo.addClass(elMsgBG, 'Hid');
}
function resizeBG(el) {
	if (el) {
		var	width	= Math.max(getElementWidth(dojo.byId('AllCont')), getElementWidth(dojo.byId('CalCont')));
		var	height	= Math.max(getElementHeight(dojo.byId('AllCont')), getElementHeight(dojo.byId('CalCont')));
		el.style.width	= (width) ? width +'px' : '100%';
		el.style.height	= (height) ? height +'px' : '100%';
	}
}
function solidMsgBG() {
	dojo.addClass(dojo.byId('MsgBG'), 'Solid');
}
function unsolidMsgBG() {
	dojo.removeClass(dojo.byId('MsgBG'), 'Solid');
}

function centreCont(elMsgCont) {
	//	Adjust width on iPhone/iPod
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
		//	Resize Msg Container in case view port is smaller than default width
		if (getViewportWidth() < 600) {
			var	width	= (getViewportWidth() - 20);
		} else {
			var	width	= '600';
		}
		elMsgCont.style.width		= width +'px';
		
		if (getScrollPosY() > 100) elMsgCont.style.top = getScrollPosY() + 20 +'px'; else elMsgCont.style.top = '100px';
		elMsgCont.style.left = getScrollPosX() + 10 +'px';
	} 
}

function nl2nl(str) {
	//	Convert /n to newline (\n)
	
	str	= str.replace(new RegExp("/n", "g"), "\n");
	
	return str;
}

function urldecode(str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u00DC'] = '%DC';
    histogram['\u00FC'] = '%FC';
    histogram['\u00C4'] = '%D4';
    histogram['\u00E4'] = '%E4';
    histogram['\u00D6'] = '%D6';
    histogram['\u00F6'] = '%F6';
    histogram['\u00DF'] = '%DF'; 
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
 
    for (unicodeStr in histogram) {
        hexEscStr = histogram[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
    
    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);
 
    return ret;
}

function createProgress() {
	elCont	= document.createElement('div');
	document.body.appendChild(elCont);
	
	elCont.id	= 'ProgressCont';
	dojo.addClass(elCont, 'Hid');
	
	var html	= '';
	html	+= '<div class="BG"></div>';
	html	+= '<div id="ProgressBar"><img src="images/pbar.gif" /></div>';
	html	+= '<div class="TextCont">Loading...</div>';
	html	+= '<div class="Clear"></div>';

	elCont.innerHTML	= html;
	
	return elCont;
}
function showProgress(requestor) {
	elProgCont	= dojo.byId('ProgressCont');
	if (!elProgCont) elProgCont = createProgress();
	dojo.removeClass(elProgCont, 'Hid');
	showMsgBG('progress');
	
	if (!progRequestors.in_array(requestor)) progRequestors.push(requestor);
}

function hideProgress(requestor, forceHide) {
	if (forceHide) {
		progRequestors = [];
	} else {
		progRequestors.removeValue(requestor);
	}
	
	if (!progRequestors.length || forceHide) {
		dojo.addClass(dojo.byId('ProgressCont'), 'Hid');
		hideMsgBG('progress');
	}
}


function parseMySQLDate(strDate) {  
	var date = new Date();  
	var parts = String(strDate).split(/[- :]/);  
	
	date.setFullYear(parts[0]);  
	date.setMonth(parts[1] - 1);  
	date.setDate(parts[2]);  
	//date.setHours(parts[3]);
	//date.setMinutes(parts[4]);  
	//date.setSeconds(parts[5]);  
	//date.setMilliseconds(0);  
	
	return date;  
}  

function parseMySQLTime(strDate) {  
	var date = new Date();  
	var parts = String(strDate).split(/[- :]/);  

	//date.setFullYear(parts[0]);  
	//date.setMonth(parts[1] - 1);  
	//date.setDate(parts[2]);  
	date.setHours(parts[0]);
	date.setMinutes(parts[1]);  
	date.setSeconds(parts[2]);  
	date.setMilliseconds(0);  
	
	return date;  
}  

function parseMySQLDateTime(strDate) {  
	var date = new Date();  
	var parts = String(strDate).split(/[- :]/);  
	
	date.setFullYear(parts[0]);  
	date.setMonth(parts[1] - 1);  
	date.setDate(parts[2]);  
	date.setHours(parts[3]);
	date.setMinutes(parts[4]);  
	date.setSeconds(parts[5]);  
	date.setMilliseconds(0);  
	
	return date;  
} 


function shrinkTexttoFit(elBox, maxHeight, maxWidth, maxFontSize) {
	/*
	 *	This function will adjust the font size property of the element
	 *	in order to make the text fit 
	 */
	if (!elBox) return;
	
	if (!maxFontSize) maxFontSize = 20;
	
	var	origOverflow			= elBox.style.overflow;
	elBox.style.overflow	= 'auto';
	
	currWidth		= getElementWidth(elBox);
	currHeight		= getElementHeight(elBox);
	clientWidth		= elBox.clientWidth; // This is used to detect if vertical scrollbar is present
	clientHeight	= elBox.clientHeight; // This is used to detect if horizontal scrollbar is present
	
	if (origOverflow) {
		elBox.style.overflow	= origOverflow;
	} else {
		elBox.style.overflow	= '';
	}
		
	if ((maxWidth && currWidth > maxWidth) || (maxHeight && currHeight > maxHeight) || (clientWidth && currWidth != clientWidth) || (clientHeight && currHeight != clientHeight)) {
		var currFontSize = elBox.style.fontSize.replace('px', '') / 1;
		if (!currFontSize) currFontSize = maxFontSize;
		if (currFontSize > 8) {
			elBox.style.fontSize	= (currFontSize - 1)+ 'px';
		
			shrinkTexttoFit(elBox, maxHeight, maxWidth, (currFontSize - 1));
		}
	}

	return;
}


function removeGetVars(href, unwantedVars) {
	if (!href || !unwantedVars) return '';
	
	var	newVars	= [];
	var	splitHref	= href.split('?');
	var	page		= splitHref[0];
	var	vars	= [];
	if (splitHref[1]) vars = splitHref[1].split('&');
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		
		if (!unwantedVars.in_array(pair[0])) newVars.push(pair.join('='));
	}
		
	return page + ((newVars.length) ? '?'+ newVars.join('&') : '');
}


function checkForm(frmID) {
	if (!frmID) return false;
	
	var	invalidCnt	= 0;
	var valid		= true;
	var	elFrm		= dojo.byId(frmID);
	for(var i = 0; i < elFrm.elements.length; i++) {
		//	Check for required fields that are blank
		if (elFrm.elements[i].getAttribute('Required') && elFrm.elements[i].getAttribute('Required').toLowerCase() == 'true' && elFrm.elements[i].value.trim() == '') {
			valid	= false;
			dojo.addClass(elFrm.elements[i], 'Invalid');
		} else {
			dojo.removeClass(elFrm.elements[i], 'Invalid');
		}
	}
	
	if (!valid) alert('Please fill in all required fields.');
	
	return valid;
}

function goSignup() {
	window.location	= 'ss_register.php';
}

function goPasswordRetrieve() {
	window.location	= 'retrieve_password.php';
}

function processResponse(response) {
	if (!response) return;
	
	if (response.action) responseAction = response.action;
	
	//	If there is a msg or error, perform the action
	//	when they are closed, otherwise perform the action now
	if (!response.delayAction || (!response.msg && !response.error)) performAction();
		
	if (response.msg && response.msg != '') showMsg(response.msg);
	if (response.error && response.error != '') showError(response.error);
}

function performAction() {
	if (!responseAction) return;
	
	action			= responseAction;
	responseAction	= '';
	
	var	params	= [];
	if (action.indexOf('>') != -1) {
		params		= action.split('>');
		action		= params.shift();
	}
	
	switch (action) {
		case 'reload':			// Reload the window
			reloadWindow();
		break;
		case 'refresh':			// Refresh the calendar
			refreshCal();
		break;
		case 'mode':			// Change the calendar mode
			changeMode(params[0], false);
		break;
		case 'closepage':		// Close the page
			hidePage();
		break;
		case 'showavail':
			showAvail(params[0]);
			disablePageRefresh();
		break;
		case 'showappoint':
			showAppoint(params[0]);
			disablePageRefresh();
		break;
	}
	
	hideProgress('', true);
}

function error(errorMsg, errorType, reload) {
	if (!errorMsg) return false;
	
	alert(errorMsg);
	
	if (reload) performAction('reload');
}

function setFocus(focusID) {
	elFocus	= dojo.byId(focusID);
	if (elFocus) {
		elFocus.focus();
		elFocus.select();
	}
}

function isiPhone() {
	return (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i));
}

function fieldProperCase(elField) {
	if (elField) elField.value = elField.value.toProperCase();
}

function toggleHelpTip(helptipID) {
	elHelpTip	= dojo.byId(helptipID);
	if (elHelpTip) {
		if (dojo.HasClass(elHelpTip, 'Hid')) {
			showHelpTip(helptipID);
		} else {
			hideHelpTip(helptipID);
		}
	}
}
function showHelpTip(helptipID) {
	elHelpTip	= dojo.byId(helptipID);
	if (elHelpTip) dojo.removeClass(elHelpTip, 'Hid');
}
function hideHelpTip(helptipID) {
	elHelpTip	= dojo.byId(helptipID);
	if (elHelpTip) dojo.addClass(elHelpTip, 'Hid');
}

function reloadWindow() {
	window.location.reload(true);
}

function fetchContent(vars, container) {
	if (!vars ||  !container) return false;

	showProgress('FetchContents');
	
    var xhrArgs = {
		url: 'fetches/fetch_page.php?'+ vars,
		handleAs: 'json',
		preventCache: true,
		timeout: 15000,
		container: container,
		load: function(response, ioArgs) {
    		processResponse(response);
    		if (response.success) {
    			elCont	= dojo.byId(ioArgs.args.container);
    			if (elCont) {
    				//if (typeof elCont.attr == 'function') {
    					elCont.attr('content', response.html);
    					console.debug('Used attr...');
    				//} else {
    				//	elCont.innerHTML	= response.html;
    				//}
    				dojo.parser.parse(elCont);
    			}
    		}
    		
    		return response;
    	},
		error: function(response, ioArgs) {
			hideProgress('FetchContents');
			
    		if (response.dojoType == 'timeout') {
    			error('This request has timed out.', 'Fetch-Timout', false);
    		} else {
    			error('An unexpected error has occurred while attempting to fetch this page.\n\nThis page will be reloaded.', 'fetch-Error', true);
    		}
    		console.debug(response);
    		
    		return response;
		},
		handle: function(response, ioArgs) {
		}
    };

  	var deferred = dojo.xhrGet(xhrArgs);
    
    
    return deferred;
}

function hideElement(el) {
	if (el) dojo.addClass(el, 'Hid');
}

function showElement(el) {
	if (el) dojo.removeClass(el, 'Hid');
}

function insertTextAtCursor(elTextBox, text) {
	if (document.selection) {
		//IE support
		elTextBox.focus();
		sel			= document.selection.createRange();
		sel.text	= text;
	} else if (elTextBox.selectionStart || elTextBox.selectionStart == '0') {
		//MOZILLA/NETSCAPE support
		var startPos	= elTextBox.selectionStart;
		var endPos		= elTextBox.selectionEnd;
		elTextBox.value	= elTextBox.value.substring(0, startPos) + text + elTextBox.value.substring(endPos, elTextBox.value.length);
	} else {
		elTextBox.value	+= text;
	}
}

function clearCheckboxes(parentID, prefix) {
	if (!parentID) return false;

	var	query		= 'input[type=checkbox]:checked';
	var	nodeList	= dojo.query(query, dojo.byId(parentID));
	
	for (var i = 0; i < nodeList.length; i++) {
    	if (!prefix || (nodeList[i].id.indexOf(prefix) !== -1 && nodeList[i].id.indexOf(prefix) == 0)) {
			nodeList[i].checked	= false;
    	}
	}
}
