function setupCalendar() {
	var formdateobj = document.getElementById('startdate');
	if ( formdateobj != null ) {
		Calendar.setup({
	 	   inputField : "startdate", // ID of the input field
	 	   ifFormat : "%Y-%m-%d", // the date format
	 	   //ifFormat : "%m-%d-%Y",
	 	   button : "startdatebutton" // ID of the button
	 	   });
	     Calendar.setup({
	 	   inputField : "enddate", // ID of the input field
	 	   ifFormat : "%Y-%m-%d", // the date format
	 	  //ifFormat : "%m-%d-%Y",
	 	   button : "enddatebutton" // ID of the button
	 	   });
	}
     return true;
}

function miniSetupCalendar(fieldId, buttonId) {
	var buttondateobj = document.getElementById(buttonId);
	var fielddateobj = document.getElementById(fieldId);
	if ( buttondateobj != null && fielddateobj != null ) {
		Calendar.setup({
	 	   inputField : fieldId, // ID of the input field
	 	   ifFormat : "%Y-%m-%d", // the date format
	 	   //ifFormat : "%m-%d-%Y",
	 	   button : buttonId // ID of the button
	 	   }); 
	}
     return true;
}

function setupHTML(html_type) {
	if ( html_type == 'math' ) {
		var allHTMLTags = getElementByClass("AM");  
		if (allHTMLTags != undefined && allHTMLTags.length>0) { 
			for (i in allHTMLTags) {  
				var n = allHTMLTags[i];
				var str = n.innerHTML;			
				if (str.indexOf("mimetex") == -1 || str.indexOf("cgi-bin") == -1) {
					n.innerHTML = '';
					str = str.replace("`", "") ;
					var texstring = str.replace("`", "") ;				
					n.appendChild( AMTparseMath(texstring) );  
				}  
			}  
		}
	}
	
	if ( html_type == 'svg' )
		drawPics();
	
	return true; 
}

function getElementByClass(theClass) {
	var result = new Array();
	var allHTMLTags = new Array(); 
	var allHTMLTags = document.getElementsByTagName('*');  
	if (allHTMLTags != undefined && allHTMLTags.length>0) { 
		var j = 0;
		for (i=0; i<allHTMLTags.length; i++) { 
			if (allHTMLTags[i].className==theClass) { 
				result[j]=allHTMLTags[i];
				j++;
			}
		} 
	}  
	return result ; 
}

function ajaxRequest(){
	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		  return new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]; //activeX versions to check for in IE
		//Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
		for (var i=0; i<activexmodes.length; i++){
			try{
				return new ActiveXObject(activexmodes[i]);
			}
			catch(e){}
		}
	}
	else
	  return false;
}

function ajaxGetpage(divid, url, useasync) {
	if ( typeof useasync == 'undefined' )
		useasync = true;
	return ajaxPostform(divid, url, '', useasync);
}

function checkServerError(ret_text, printerror) {
	if ( typeof ret_text == 'undefined' )
		return true;
	if (ret_text == '')
		return true;
	if ( typeof printerror == 'undefined' )
		printerror = true;
	var errorTag = '<!---:ajproto_ERROR_TaG:--->';
	var noSessionTag = '<!---:ajproto_REDIRECTHOME_TaG:--->';
	if ( !(typeof ajaxAppErrorTag == 'undefined') && ajaxAppErrorTag != '' )
		errorTag = ajaxAppErrorTag;
	if ( !(typeof ajaxAppNoSessionTag == 'undefined') && ajaxAppNoSessionTag != '' )
		noSessionTag = ajaxAppNoSessionTag;
	var errorindex = ret_text.search(errorTag);
	if ( errorindex == 0 ||  errorindex == 1 ) {
		error_text = ret_text.replace(errorTag, '');
		if ( printerror )
		printErrorWindow(error_text);
		return false;
	}
	var errorindex = ret_text.search(noSessionTag);
	if ( errorindex == 0 ||  errorindex == 1 ) {
		error_text = ret_text.replace(noSessionTag, '');
		if ( printerror )
		printErrorWindow(error_text, '350', '250', true);
		return false;
	}
	return true;
}

/* 
 * if divid is '' then return text and implies useasync = false
 * if formname is '' then no params to post
 * if printerror is false then useasync can be true even when divid is empty string
 * Most programmers don't really understand async/multi-thread env. so set default to sync most of the time
 * It will act slower to the user in some cases but it will not break...
 */
var ajax_is_running = 0;
function ajaxPostform(divid, url, formname, useasync, printerror){
	if ( ajax_is_running < 0 )
		ajax_is_running = 0;
	ajax_is_running++;;
	var parameters = '';
	if ( typeof useasync == 'undefined' )
		useasync = true;
	//Only the session check sets printerror to false
	if ( divid == '' && !printerror )
		useasync = false;
	if ( typeof printerror == 'undefined' )
		printerror = true;
	var mypostrequest=new ajaxRequest();
	var errorMsg = "An error has occured while accessing the server";
	if ( !(typeof ajaxServerError == 'undefined') && ajaxServerError != '' )
		errorMsg = ajaxServerError;
	mypostrequest.onreadystatechange = function(){
		if (useasync && mypostrequest.readyState==4){
			if (mypostrequest.status==200){
				if ( checkServerError (mypostrequest.responseText, printerror) ) {
					if ( divid != '' ) {
					document.getElementById(divid).innerHTML=mypostrequest.responseText;
					doJscriptProcess(mypostrequest.responseText);
				}
			}
			}
			else {
			  if ( printerror )
				  printErrorWindow(errorMsg);
			  return false;
			}
		 }
	}

	if ( formname != '' )
		parameters=getPostQueryString(formname);
	if (parameters == '')
		parameters = 'bustcache=' + new Date().getTime();
	else
		parameters += '&bustcache=' + new Date().getTime();
	try {
		mypostrequest.open("POST",url, useasync);
		mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		mypostrequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		mypostrequest.send(parameters);
	}
	catch(e) {
		if ( printerror )
			printErrorWindow(errorMsg);
		ajax_is_running--;
		return false;
	}
	if ( ! useasync ) {
		if ( mypostrequest.status==200 ) {
			var error_check = checkServerError (mypostrequest.responseText, printerror);
			if ( typeof divid == 'undefined' || divid == '' ) {
				ajax_is_running--;
				if ( error_check )
					return mypostrequest.responseText;
				else
					return false;
			}
			else {
				if ( error_check ) {
					if ( divid != '' ) {
					document.getElementById(divid).innerHTML = mypostrequest.responseText;
					doJscriptProcess(mypostrequest.responseText);
					}
					ajax_is_running--;
					return true;
				}
				else {
					ajax_is_running--;
					return false;
				}
			}
		}
		else {
			if ( printerror )
				printErrorWindow(errorMsg);
			ajax_is_running--;
			return false;
		}
	} /*
	else {
		if (divid != '') {
			document.getElementById(divid).innerHTML =
				'<img src="'  + appHomeUrl + 'images/wait16trans.gif' + '" />';
		}
	}*/
	ajax_is_running--;
	return true;
}

function hideDiv(name) {
	var divs = document.getElementsByTagName('div');
	for(var i=0;i<divs.length;i++){
		if(divs[i].id.match(name)){//if they are 'see' divs
			if (document.getElementById) // DOM3 = IE5, NS6
				divs[i].style.visibility="hidden";// show/hide
			else if (document.layers) // Netscape 4
				document.layers[divs[i]].display = 'hidden';
			else // IE 4
				document.all.hideShow.divs[i].visibility = 'hidden';
		}
	}
}

function showDiv(name) {
	//document.getElementById('')
	var divs = document.getElementsByTagName('div');
	for(var i=0;i<divs.length;i++){
		if(divs[i].id.match(name)){
		if (document.getElementById)
			divs[i].style.visibility="visible";
		else if (document.layers) // Netscape 4
			document.layers[divs[i]].display = 'visible';
		else // IE 4
			document.all.hideShow.divs[i].visibility = 'visible';
		}
	}
}

function getDivobj(name) {
	var divs = document.getElementsByTagName('div');
	for(i=0;i<divs.length;i++){
		if(divs[i].id.match(name))
			return divs[i];
	}
	return false;
}

function getPostQueryString(formname) {
	var theform = document.forms[formname];
	var reqStr = '';
	var elementname = '';
	var elementName = '';
	var sel;
	if (typeof(theform) == 'undefined')
		return '';
	var ampchar = '';
	for(var i=0; i < theform.elements.length; i++) {
		elementname = theform.elements[i].name;
		if ( typeof(elementname) == 'undefined' || elementname == '' )
			elementname = theform.elements[i].id;
		if ( typeof(elementname) == 'undefined' || elementname == '' )
			continue;
		elementName = theform.elements[i].tagName.toLowerCase();
		switch (elementName) {
		case "input":
			switch (theform.elements[i].type) {
				case "text":
				case "hidden":
					reqStr += ampchar + elementname + "=" + 
							  encodeURIComponent(theform.elements[i].value);
					break;
				case "checkbox":
					if (theform.elements[i].checked)
					{
					reqStr += ampchar + elementname + "=" + theform.elements[i].value;
					}else{
					reqStr += ampchar + elementname + "=";
					}
					break;
				case "radio":
					if (theform.elements[i].checked) {
						reqStr += ampchar + elementname + "=" + theform.elements[i].value;
					}
			}
			break;
		case "textarea":
			reqStr += ampchar + elementname + "=" +
					  encodeURIComponent(theform.elements[i].value);
			break;
		case "select":
			sel = theform.elements[i];
			for (var j=0; j<sel.options.length; j++) {
				if (sel.options[j].selected) {
					reqStr += ampchar + elementname + "=" + encodeURIComponent(sel.options[j].value);
					ampchar = '&';
				}
			}
			break;
		}
		if ( reqStr != '' )
			ampchar = '&';
	}
	return reqStr;
}

function doJscriptProcess(htmltext) {
	if ( htmltext.search(/id=['"]datebutton["']/i) > 0) {
		miniSetupCalendar('fielddate','datebutton');
	}
	if ( htmltext.search(/id=['"]startdatebutton["']/i) > 0) {
		setupCalendar();
	}
	if ( htmltext.search(/<span class=['"]am["']>/i) > 0) {
		setupHTML('math');
	}
	if ( htmltext.search(/type=['"]image.svg.xml["']/i) > 0) {
		setupHTML('svg');
	}
	//This is for template date
	var count=1;
	var datebutton='templatedatebutton';
	var datetext='templatedatetext';
	var regexobj=new RegExp('id=[\'"]' + datebutton + count + '["\']','i');
	while (true) {
		if ( htmltext.search(regexobj) > 0) {
			miniSetupCalendar(datetext+count, datebutton+count);
		}
		else {
			break;
		}
		count++;
		regexobj=new RegExp('id=[\'"]' + datebutton + count + '["\']','i');
	}
}

function closeDhtmlWindow(divid) {
	modDhtmlWindow(divid,1);
}

function hideDhtmlWindow(divid) {
	modDhtmlWindow(divid,2);
}

function showDhtmlWindow(divid) {
	modDhtmlWindow(divid,3);
}

function printErrorWindow(errortext, winwidth, winheight, doRedirect) {
	if ( typeof winwidth == 'undefined' ) {
		winwidth = '400';
		winheight = '250';
	}
	if ( typeof doRedirect == 'undefined')
		doRedirect = false;
	if ( doRedirect ) {
		if ( typeof appHomeUrl == 'undefined' )
			appHomeUrl = '/';
		errortext = '<br /><font color="red"><center>' + errortext +
		'<br /><br /><!-- input type="button" class="btn" value="Close" onClick="closeDhtmlWindow(\'errorwin_div\'); ' +
		'window.location="' + appHomeUrl + '"; return false;" onMouseover="if(this.className) this.className=\'btnhov\';" ' +
		'onMouseout="if(this.className) this.className=\'btn\'" / --></center></font>';
		setTimeout('window.location="' + appHomeUrl + '"', 10000);
	}
	else {
		errortext = '<br /><font color="red"><center>' + errortext +
				'<br /><br /><input type="button" class="btn" value="Close" onClick="closeDhtmlWindow(\'errorwin_div\'); ' +
				'return false;" onMouseover="if(this.className) this.className=\'btnhov\';" ' +
				'onMouseout="if(this.className) this.className=\'btn\'" /></center></font>';
	}
	newDhtmlWindow_text('Message', winwidth, winheight, 'errorwin_div', errortext);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Begin code for DHTMLX Windows
function get_dhxWinsParentObj() {
	if ( typeof get_dhxWinsParentObj.myobject == 'undefined' ) {
		get_dhxWinsParentObj.myobject = new dhtmlXWindows();
		//Should make skin configurable from PHP
		get_dhxWinsParentObj.myobject.setSkin(gDhtmlxwindowsSkin);
		get_dhxWinsParentObj.myobject.setImagePath(appIncludePath + "js/dhtmlxwindows/codebase/imgs/");
	}
	return get_dhxWinsParentObj.myobject;
}

function window_size_array() {
	var width = 0;
	var height = 0;
	if(!window.innerWidth) {
		if(!(document.documentElement.clientWidth == 0)) {
			width = document.documentElement.clientWidth;
			height = document.documentElement.clientHeight;
		}
		else {
			width = document.body.clientWidth;
			height = document.body.clientHeight;
		}
	}
	else {
		width = window.innerWidth;
		height = window.innerHeight;
	}
	return {width:width, height:height};
}

function viewscreen_center(width, height) {
	var x_pos = 0;
	var y_pos = 0;
	var offsetX = 0;
	var offsetY = 0;
	if(!window.pageYOffset) {
		if(!(document.documentElement.scrollTop == 0)) {
			offsetY = document.documentElement.scrollTop;
			offsetX = document.documentElement.scrollLeft;
		}
		else {
			offsetY = document.body.scrollTop;
			offsetX = document.body.scrollLeft;
		}
	}
	else {
		offsetX = window.pageXOffset;
		offsetY = window.pageYOffset;
	}
	
	var winsize = window_size_array();
	x_pos = ((winsize.width - width) / 2) + offsetX;
	y_pos = ((winsize.height - height) / 2) + offsetY;
	if ( x_pos < 0 ) {
		x_pos = 0;
	}
	if ( y_pos < 0 ) {
		y_pos = 0;
	}
	return{x:x_pos, y:y_pos};
}

function newDhtmlWindow(url, title, width, height, id) {
	var uniqueid = 'dhtmlwin_' + id;
	if ( typeof id=="undefined" ) {
		uniqueid = 'winid' + Math.random();
	}
	return create_dhtmlxwindow(uniqueid, title, width, height, url, true);
}

function newDhtmlWindowTop(url, title, width, height, id) {
	//Not using windows to go to the top so always use the center one
	return newDhtmlWindow(url, title, width, height, id);
}

function newDhtmlWindow_text(title, width, height, id, text) {
	var obj = newDhtmlWindow('', title, width, height, id);
	if ( typeof obj != 'undefined' ) {
		obj.attachHTMLString(text);
		doJscriptProcess(text);
		return obj;
	}
}
/* No longer used
//This will check for the math formula and svg graph
function newDhtmlWindowCheckGraph(url, title, width, height, id) {
	var rethtml = ajaxGetpage('', url, false);
	newDhtmlWindow_text(title, width, height, id, rethtml);
	doJscriptProcess(rethtml);
}
*/
function newIframeWindow(url, title, width, height, id) {
	var uniqueid = 'dhtmlwin_' + id;
	if ( typeof id=="undefined" ) {
		uniqueid = 'winid' + Math.random();
	}
	return create_dhtmlxwindow(uniqueid, title, width, height, url, false);
}

function create_dhtmlxwindow(uniqueid, title, width, height, url, isajax){
	var new_height = parseInt(height) + gDhtmlxwindowsExtraheight;
	var dhxParentObj = get_dhxWinsParentObj();
	var uniqueWin = dhxParentObj.window(uniqueid);
	//We can't use uniqueWin.centerOnScreen() since it simply does not work, do our own here
	var getcenter = viewscreen_center(width, new_height);
	var htmlpage_str = false;
	
	if ( typeof url != 'undefined' && url != '' && isajax ) {
		htmlpage_str = ajaxGetpage('', url);
		if ( htmlpage_str == false ) {
			return false;
		}
	}
	
	if ( !isDhtmlxObject(uniqueWin) ) {
		uniqueWin = dhxParentObj.createWindow(uniqueid, getcenter.x, getcenter.y, width, new_height);
	}
	else {
		uniqueWin.setDimension(width, new_height);
		uniqueWin.setPosition(getcenter.x, getcenter.y);
	}
	if ( !isDhtmlxObject(uniqueWin) ) {
		alert(gGeneralJavasriptError);
		exit;
	}
	uniqueWin.button("minmax1").hide(); // hide maximum button
	//Just in case if it is hidden
	uniqueWin.show();
	//Set the window title
	uniqueWin.setText(title);
	if ( htmlpage_str != false ) {
		uniqueWin.attachHTMLString(htmlpage_str);
		doJscriptProcess(htmlpage_str);
	}
	else {
		uniqueWin.attachURL(url, false); // second parameter of attachURL is FALSE, mean using iframe 
	}
	var tmp = dhxParentObj._engineGetWindowHeader(uniqueWin);
	if ( typeof tmp.ondblclick != 'undefined' ) {
		tmp.ondblclick = null; //disable feature double click to maxmimize
	}
	return uniqueWin;
}

function modDhtmlWindow(divid,action) {
	var dhxParentObj = get_dhxWinsParentObj();
	var winObj = dhxParentObj.window('dhtmlwin_' + divid);
	if ( typeof winObj == 'undefined' )	{
		return;
	}
	if ( action == 1 ) {
		winObj.close();
	}
	else if ( action == 2 ) {
		winObj.hide();
	}
	else if ( action == 3 ) {
		winObj.show();
	}
}

function getDhtmlWindowById(id) {
	var dhxParentObj = get_dhxWinsParentObj();
	var obj = dhxParentObj.window('dhtmlwin_' + id);
	if ( typeof obj != 'undefined'  && obj != null ) {
		return obj;
	}
	return null;
}

//Our own function to check for the Dhtmlx windows object, can break if they take out property idd
//This should be used in sys.js only
function isDhtmlxObject(obj) {
	return (obj != null && obj != false && typeof obj == 'object' && typeof obj.idd != 'undefined' )
}

function winobjAttachHtml(obj, html) {
	if ( isDhtmlxObject(obj) ) {
		obj.attachHTMLString(html);
		doJscriptProcess(html);
		return true;
	}
	return false;
}

//End code for DHTMLX Windows
/////////////////////////////////////////////////////////////////////////////////////////////////////////

/* no longer used
function printMsgWindow(msgtext, title, winwidth, winheight) {
	if ( typeof title == 'undefined' )
		title = 'Message Window';
	if ( typeof winwidth == 'undefined' ) {
		winwidth = '400';
		winheight = '150';
	}
	msgtext = '<br /><font color="blue"><center>' + msgtext +
				'<br /><br /><input type="button" class="btn" value="Close" onClick="closeDhtmlWindow(\'msgwin_div\'); ' +
				'return false;" onMouseover="if(this.className) this.className=\'btnhov\';" ' +
				'onMouseout="if(this.className) this.className=\'btn\'" /></center></font>';
	this.center_position(winwidth, winheight);
	newwindow = dhxWins.createWindow('dhtmlwin_msgwin_div', this.xpos, this.ypos, winwidth, winheight);
	newwindow.setText(title);
	newwindow.button("minmax1").hide();
	newwindow.attachHTMLString(msgtext);
}
*/
