var IE = (/msie/i).test(navigator.userAgent);
var sess = null;
var vars = [];
var dfd;
var image_list = [];
var dr = 0;
var res = 0;
var stylesheets = [];
var initial_data;
var layout = null;
//var lastURL = window.location.href;
//var pollID = window.setInterval("pollHash();",1000);
//var popup = openWin("debug.html","popup");

function object(o)
{
	function F() {}
	F.prototype = o;
	return new F();
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function pollHash()
{
	var req = createRequest();
	req.open("POST","test/geturl.php",false);
	req.send(null);
	var URL = (IE) ? document.URL : window.location.href;
	if (lastURL != URL)
	{
	//alert(lastURL + "\n" + URL);
		//alert('hash has changed...');
		if (!URL.match(new RegExp("#","i")))
		{
			//URL
		}
	}
	lastURL = URL;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function bodyLoad(evt)
{
	//windowResize(null);
	//window.onresize = function() { windowResize(evt); };
	if (IE)
	{
		try
		{
			document.execCommand("BackgroundImageCache",false,true);
		}
		catch(e)
		{
		}
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function dataframeLoad(evt)
{
	try
	{
		dfd = (window.frames.dataframe.document || dgi('dataframe').contentDocument);
		if (initial_data)
		{
			dfd.getElementById('dataframe_data').value = initial_data;
			initial_data = null;
		}
		data = (dfd.getElementById('dataframe_data').value || "");
		data_input = (dfd.getElementById('dataframe_data_input').value || "");
		if (data.length > 0 && data_input.length > 0)
		{
			request("POST","?",data + "&history=true");
		}
	}
	catch (ex)
	{
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function fileframeLoad(evt)
{
	var s;
	try
	{
		ffd = (window.frames.fileframe.document || dgi('fileframe').contentDocument);
		s = ffd.getElementById("response").value;//.replace(new RegExp("\<\/?(head|title|body)\>","gi"),"");
		if (s.length > 0)
		{
			process(s);
		}
	}
	catch (ex)
	{
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function disableStyle(ssArray)
{
	var t;
	var disable = "(t=='" + ssArray.join("' || t=='") + "')";
	for (var i = 0; i < stylesheets.length; i++)
	{
		t = stylesheets[i].title;
		if (eval(disable))
		{
			if (!stylesheets[i].disabled)
			{
				stylesheets[i].disabled = true;
			}
		}
	}	
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function applyStyle(ssArray,overwrite)
{
	var t;
	var enable = "(t=='" + ssArray.join("' || t=='") + "')";
	for (var i = 0; i < stylesheets.length; i++)
	{
		t = stylesheets[i].title;
		if (eval(enable))
		{
			if (stylesheets[i].disabled)
			{
				stylesheets[i].disabled = false;
				//alert("ENABLED " + stylesheets[i].title);
			}
		}
		else if (overwrite)
		{
			if (!stylesheets[i].disabled)
			{
				stylesheets[i].disabled = true;
				//alert("DISABLED " + stylesheets[i].title);
			}
		}
	}
} 

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function saveHistory(data)
{
	dfd.getElementById('dataframe_data_input').value = data;	
	dfd.getElementById('dataframe_form').submit();
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function makeRequest(evt, sender, method, url, data, save)
{
	//saveHistory(data);
	request(method, url, data);
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function openWin(url,name)
{
	features = "height=300,width=600,location=no,menubar=no,toolbar=no,resizable=yes,scrollbars=yes,status=no";
	popup = window.open(url,name,features);
	popup.focus();
	return popup;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function popup(url,name,settings)
{
	var ht = settings.height || 300;
	var wd = settings.width || 600;
	var lb = settings.location || 'no';
	var mb = settings.menubar || 'no';
	var tb = settings.toolbar || 'no';
	var rs = settings.resizable || 'no';
	var sb = settings.scrollbars || 'yes';
	var st = settings.status || 'no';
	features = 'height=' + ht + ',width=' + wd + ',location=' + lb + ',menubar=' + mb + ',toolbar=' + tb + ',resizable=' + rs + ',scrollbars=' + sb + ',status=' + st + '';
	var p = window.open(url,name,features);
	p.focus();
	return p;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function windowResize(evt)
{
	if (IE)
	{
		removeFocusOnAllLinks();
		resizeStrict(document);
	}
	
	switch (layout)
	{
		case "normal" :
			positionFooter();
			break;
		case "fill" :
			break;
		case "fixed" :
			break;
		case "normal-fill" :
			break;
	}
	document.documentElement.style.visibility = 'visible';
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function positionFooter()
{
	var p = dgi('page');
	var f = dgi('footer');
	var lm = dgi('leftmenu');
	var rm = dgi('rightmenu');
	var e = dgi('everything');
	
	var bottomOfLeftmenu = (parseInt(lm.offsetHeight,10) || 0) + (parseInt(style(lm).top,10) || 0);
	var bottomOfRightmenu = (parseInt(rm.offsetHeight,10) || 0) + (parseInt(style(rm).top,10) || 0);
	var bottomOfPage = (parseInt(p.offsetHeight,10) || 0) + (parseInt(style(p).top,10) || 0);
	
	var lowestPoint = Math.max(Math.max(bottomOfRightmenu,bottomOfLeftmenu),bottomOfPage);
	var anchorPosition = document.documentElement.clientHeight - extraHeight(style(e))/2 - (parseInt(style(f).height,10) || 0);
	f.style.display = "block";
	if (anchorPosition > lowestPoint)
	{
		//dgi('footer').style.top = "auto";
		//dgi('footer').style.bottom = "0px";
		dgi('footer').style.top = lowestPoint + "px";
	}
	else
	{
		dgi('footer').style.top = lowestPoint + "px";
	}	
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function debug(msg,__FILE__,__LINE__)
{
	if (typeof popup != "undefined")
	{
		/*
		d = document.createElement("div");
		d.innerHTML = "<span style='color:#cccccc;'>" + now() + "</span> : " + msg;
		s = "<div style='padding:5px 0px;";
		if (++dr % 2 == 0)
		{
			s += ";background:#eeeeee;";
		}
		s += "'><span style='color:#cccccc;'>" + now() + "</span> : " + msg + "</div>";
		popup.document.body.innerHTML += s;
		*/
		popup.document.write(msg);
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function now()
{
		re = new RegExp("^([0-9]){1}$","i");
		var d = new Date();
		var Y = d.getFullYear().toString();
		var M = d.getMonth().toString().replace(re,"0$1");
		var D = d.getDay().toString().replace(re,"0$1");
		var h = d.getHours().toString().replace(re,"0$1");
		var m = d.getMinutes().toString().replace(re,"0$1");
		var s = d.getSeconds().toString().replace(re,"0$1");
		var f = d.getMilliseconds().toString();
		if (f.length == 1)
		{
			f = '00' + f;
		}
		else if (f.length == 2)
		{
			f = '0' + f;
		}
		return Y + "-" + M + "-" + D + " " + h + ":" + m + ":" + s + "." + f;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function timestamp()
{
		var d = new Date();
		var u = d.getFullYear().toString() + "-" + d.getMonth().toString() + "-" + d.getDay().toString() + " " + d.getHours().toString() + ":" + d.getMinutes().toString() + ":" + d.getSeconds().toString() + "." + d.getMilliseconds().toString();
		return (d.getHours()*3600000 + d.getMinutes()*60000 + d.getSeconds()*1000 + d.getMilliseconds());
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function unique()
{
		var r1 = Math.round(Math.random()*1000000);
		var r2 = Math.round(Math.random()*1000000);
		return r1.toString() + timestamp().toString() + r2.toString();
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function parametersToArray(parameterString)
{
    var splitIndex;
    var x = [];
    var parameterArray = [];
    var eq;
    
    if (parameterString.charAt(0) == "#" || parameterString.charAt(0) == "?")
    {
        splitIndex = 1;
    }
    else
    {
        splitIndex = 0;
    }
    
    if (parameterString.indexOf("&") >= 0)
    {
        x = parameterString.slice(splitIndex).split("&");
    }
    else
    {
        x.push(parameterString);
    }
    
    for (i in x)
    {
        eq = x[i].indexOf("=");
        parameterArray[x[i].slice(0,eq)] = x[i].slice(eq+1);
    }
    return parameterArray;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function showFormData(formName)
{
	var formData = [];
	var f = dgi(formName);
	var amp = "";
	var p = "";
	if (f)
	{
		for (i=0; i<(f.elements.length || 0); i++)
		{
			p = getInputData(f.elements[i]);
			if (p)
			{
				formData.push(p);
			}
		}
		if (formData.length > 0)
		{
			amp = "&";
		}
		return amp + formData.join("&");
	}
	else
	{
		return "";
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function getInputData(input)
{
	var data = "";
	var n = input.name;
	var v = input.value;
	var t = input.type.toUpperCase();
	var normal = (t=="HIDDEN" || t=="TEXT" || t=="PASSWORD" || t=="SUBMIT" || t=="BUTTON" || t=="RESET" || t=="SELECT-ONE" || t=="TEXTAREA" || t=="IMAGE");
	var checkable = (t=="RADIO" || t=="CHECKBOX");
	var multiple = (t=="SELECT-MULTIPLE");
	var file = (t=="FILE");

	if (n)
	{
		if (normal)
		{
			data = encode(n) + "=" + encode(v);
		}
		else if	(checkable)
		{
			if (input.checked)
			{
				data = encode(n) + "=" + encode(v);
			}
		}
		else if	(multiple)
		{
			d = [];
			for (c=0; c<input.options.length; c++)
			{
				if (input.options[c].selected || (/_selected/i).test(input.id))
				{
					d.push(encode(n) + "=" + encode(input.options[c].value));
				}
			}
			data = d.join("&");
		}
		else if	(file)
		{
			data = "";
		/*
			data = n + "=" + v;
			ff = document.createElement("form");
			ff.setAttribute("enctype","multipart/form-data");
			ff.setAttribute("action",window.location.href);
			ff.setAttribute("method","post");
			ff.setAttribute("target","fileframe");
			ff.setAttribute("style","display:block;");
			ff.setAttribute("name","binaryForm");
			ff.setAttribute("id","binaryForm");

			_f = document.createElement("input");
			_f.setAttribute("type","hidden");
			_f.setAttribute("name","f");
			_f.setAttribute("value","propertyImageCommit");
			ff.appendChild(_f);

			_ajax = document.createElement("input");
			_ajax.setAttribute("type","hidden");
			_ajax.setAttribute("name","ajax");
			_ajax.setAttribute("value","1");
			ff.appendChild(_ajax);

			_maxfilesize = document.createElement("input");
			_maxfilesize.setAttribute("type","hidden");
			_maxfilesize.setAttribute("name","MAX_FILE_SIZE");
			_maxfilesize.setAttribute("value","100000000");
			ff.appendChild(_maxfilesize);

			p = input.parentNode;
			newinput = input.cloneNode(false);
			ff.appendChild(input);
			p.appendChild(newinput);
			
			document.body.appendChild(ff);
			ff.submit();
		*/
		}
	}
	return data;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function runScripts(code)
{
	var s = code;
	scriptOpen = s.match(new RegExp("<script[^>]*>","i"));
	scriptClose = s.match(new RegExp("<\/script>","i"));
	var scripts = "";
	while (scriptOpen && scriptClose)
	{
		script = s.slice(s.indexOf(scriptOpen[0])+scriptOpen[0].length,s.indexOf(scriptClose[0]));
		eval(script);
		s = s.slice(s.indexOf(scriptClose[0])+scriptClose[0].length);
		scriptOpen = s.match(new RegExp("<script[^>]*>","i"));
		scriptClose = s.match(new RegExp("<\/script>","i"));
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function getResponseTag(s)
{
	re = new RegExp("<responsetag>.+</responsetag>","im");
	matches = re.exec(s);
	if (matches)
	{
		for (i=0; i<matches.length; i++)
		{
			id = matches[i].replace(/(<responsetag>)(.+)/i,"$2").replace(/<\/responsetag>/i,"");
			return id;
		}
	}
	return null;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function removeFocusOnAllLinks()
{
	for(i=0 ; i < document.links.length ; i++)
	{
		document.links[i].onfocus = blurLink;
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function blurLink()
{
	if (IE)
	{
		this.blur();
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function encodeParameterString(s)
{
	var d = [];
	var pairs = s.split("&");
	for (var i=0; i<pairs.length; i++)
	{
		nv = pairs[i].split("=");
		d.push(encodeURIComponent(nv[0]) + "=" + encodeURIComponent(nv[1]));
	}
	return d.join("&");
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function encode(s)
{
	return encodeURIComponent(s);
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function hide(evt,id)
{
	dgi(id).style.display = 'none';
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function show(evt,id)
{
	dgi(id).style.display = 'block';
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function list(e)
{
	var q = (arguments.length > 1) ? arguments[1] : "";
	var d = [];
	var re, p;
	for (p in e)
	{
		try
		{
			re = new RegExp(q,"gi");
			if (!q || re.test(p))
			{
				d.push(" [ " + (typeof e[p]) + " ] " + p + " = " + e[p]);
			}
		}
		catch (ex)
		{
			//alert(ex.name + " : " + ex.message);
		}
	}
	return d;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function style(e)
{
	var s = null;
	if (window.getComputedStyle)
	{
		try
		{
			s = window.getComputedStyle(e,null);
		}
		catch(ex)
		{
			alert(e.nodeName + " '" + e.id + "'\n\n" + ex.message);
		}
	}
	
	if (s)
	{
		return s;
	}
	else if (e.currentStyle)
	{
		return e.currentStyle;
	}
	else
	{
		return null;
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function positionedParent(e)
{
	var pn = e.parentNode;
	while (pn.nodeType == 1 && style(pn) && !style(pn).position.match(new RegExp("absolute|relative|fixed","i")))
	{
		pn = pn.parentNode;
	}
	return pn;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function extraWidth(css)
{
	return	(parseInt(css.borderLeftWidth,10) || 0) +
			(parseInt(css.borderRightWidth,10) || 0) +
			(parseInt(css.paddingLeft,10) || 0) +
			(parseInt(css.paddingRight,10) || 0) +
			(parseInt(css.marginLeft,10) || 0) +
			(parseInt(css.marginRight,10) || 0) +
			(parseInt(css.left,10) || 0) +
			(parseInt(css.right,10) || 0);
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function extraHeight(css)
{
	return	(parseInt(css.borderTopWidth,10) || 0) +
			(parseInt(css.borderBottomWidth,10) || 0) +
			(parseInt(css.paddingTop,10) || 0) +
			(parseInt(css.paddingBottom,10) || 0) +
			(parseInt(css.marginTop,10) || 0) +
			(parseInt(css.marginBottom,10) || 0) +
			(parseInt(css.top,10) || 0) +
			(parseInt(css.bottom,10) || 0);
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function width(e)
{
	var css = style(e);
	var pn = positionedParent(e);
	var pnw = (pn.clientWidth) ? pn.clientWidth : e.clientWidth;
	var ew = extraWidth(css);
	if (!(parseInt(css.width,10) >= 0) && (parseInt(css.left,10) >= 0 && parseInt(css.right,10) >= 0))
	{
		return Math.max(pnw - ew,0) + "px";
	}
	else
	{
		return css.width;
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function height(e)
{
	var css = style(e);
	var pn = positionedParent(e);
	var pnh = (pn.clientHeight) ? pn.clientHeight : e.clientHeight;
	var eh = extraHeight(css);	
	if (!(parseInt(css.height,10) >= 0) && (parseInt(css.top,10) >= 0 && parseInt(css.bottom,10) >= 0))
	{
		return Math.max(pnh - eh,0) + "px";
	}
	else
	{
		return css.height;
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function left(e)
{
	var css = style(e);
	var pn = positionedParent(e);
	var pnw = (pn.clientWidth) ? pn.clientWidth : e.clientWidth;
	var ew = extraWidth(css);
	if (css.marginLeft == "auto" && css.marginRight == "auto")
	{
		return Math.max(Math.round((pnw - (parseInt(css.width,10) || 0) - ew) / 2),0) + "px";
	}
	else
	{
		return e.style.left;
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function resize(e)
{
	resetInlineStyle(e);
	e.style.width = width(e);
	e.style.height = height(e);
	e.style.left = left(e);
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function resizeStrict(p)
{
	if (p.nodeType == 1 && style(p) && style(p).position.match(new RegExp("absolute","i")))
	{
		resize(p);
	}
		
	for (var i = 0; i < p.childNodes.length; i++)
	{
		if (p.childNodes[i].nodeType == 1 && !p.childNodes[i].nodeName.match(new RegExp("img","i")))
		{
			resizeStrict(p.childNodes[i]);
		}
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function resetInlineStyle(e)
{
	e.style.cssText = null;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function loadImages(evt,images,last_image)
{
	if (images)
	{
		alert(image_list.join("\n"));
	}
	for (i in image_list)
	{
		if ((image_list[i].match(new RegExp(last_image,"i")) || !last_image) && image_list[i+1])
		{
			dgi('image_bucket').src = image_list[i+1];
		}
	}
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function histAnchor(evt, u)
{
	a = document.createElement("a");
	a.setAttribute("id",u);
	a.setAttribute("name",u);
	//a.setAttribute("onclick","return false;");
	a.style.display = "block";
	t = document.createTextNode("history link for hash " + u);
	a.appendChild(t);
	return a;
}

//////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////
function process(response)
{
	e = dgi(getResponseTag(response));
	if (e)
	{
		e.innerHTML = response;
		runScripts(response);
	}
}

function dgi(id)
{
	return document.getElementById(id);
}

function dgtn(tag)
{
	return document.getElementsByTagName(tag);
}

function dce(tag)
{
	return document.createElement(tag);
}

function dct(text)
{
	return document.createTextNode(text);
}

function loading()
{
	var w = parseInt(dgi('readystate').style.width,10);
	if (w < parseInt(style(dgi('block_loading_control')).width,10))
	{
		dgi('readystate').style.width = (w + 1) + "px";
		setTimeout(loading,10);
	}
	else
	{
	}
}

function fadeout(e)
{
	var o = parseInt(e.style.opacity,10);
	if (o < 100)
	{
		e.style.opacity = (o + 1);
		setTimeout(function(){fadeout(e);},100);
	}
}

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

function parentForm(e)
{
	if (e.parentNode)
	{
		if (e.parentNode.tagName)
		{
			if (e.parentNode.tagName.toUpperCase()=="FORM")
			{
				return e.parentNode;
			}
			else
			{
				return parentForm(e.parentNode);
			}
		}
		else
		{
			return null;
		}
	}
	else
	{
		return null;
	}
}//////////////////////////////////////////////////////////////
//
//	NAME		:	request(_STRING_ , _STRING_ , _STRING_ , _STRING_)
//
//	DESCRIPTION	:	OPEN THE REQUEST OBJECT CONNECTION; 
//					ASSIGN THE RESPONSE EVENT HANDLER
//					FUNCTION; 
//					SEND THE REQUEST
//
//	PARAMETERS	:	url ::	ABSOLUTE OR RELATIVE URL WITH
//							WITH QUERY STRING APPENDED
//					vars :: QUERY STRING WITHOUT LEADING '?'
//					id :: ELEMENT ID TO RECEIVE DATA;
//					      PASS null FOR NO RESPONSE
//
//	RETURN		:	NONE
//
//	NOTES		:	url MUST BE FROM THE ORIGINAL SERVER
//					OR A SECURITY WARNING WILL POP UP;
//
//	AUTHOR		:	JOHNATHAN HEBERT
//
//	DATE		:	2006-03-17
//
//////////////////////////////////////////////////////////////
function request(method, url, data)
{
	try
	{		
		// DEFINE THE REQUEST VARIABLE
		var req = createRequest();
		
		var postdata = null;
		
		if (req)
		{
			// DEFAULT VALUE OF postdata IS null
			postdata = null;
			
			// SET THE POST DATA BASED ON THE METHOD PASSED IN
			if (method.toUpperCase() == "POST")
			{
				postdata = data;
			}
			else if (method.toUpperCase() == "GET")
			{
				if (url.indexOf("?") == -1)
				{
					url += "?";
				}
				url += data;
			}

			// OPEN THE CONNECTION ASYNCHRONOUSLY
			req.open(method.toUpperCase(), url, true);

			// ASSIGN THE RESPONSE EVENT HANDLER FUNCTION
			req.onreadystatechange = function() 
			{
		        response(req);
		    };

			// SET REQUEST HEADER FOR POST REQUESTS
			if (method.toUpperCase() == "POST")
			{
				req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			}
			
			// SEND THE REQUEST
			req.send(postdata + "&x=" + unique());
		}
		else
		{
			msg  = "ERROR!!!\n\n";
			msg += "REQUEST OBJECT COULD NOT BE CONSTRUCTED";
			throw new Error(msg);
		}
		
		// RETURN FALSE SO THAT PAGE WILL NOT BE REFRESHED
		return false;
	}
	catch (ex)
	{
		alert("EXCEPTION WAS THROWN IN REQUEST METHOD :\n\n" + ex.name + " :\n" + ex.message);
	}
}

//////////////////////////////////////////////////////////////
//
//	NAME		:	response(_OBJECT_ , _OBJECT_)
//
//	DESCRIPTION	:	EVENT HANDLER FOR THE REQUEST OBJECT THAT
//					WILL CHECK THE readyState PROPERTY AND 
//					status PROPERTY BEFORE PROCESSING DATA
//
//	PARAMETERS	:	req :: REQUEST OBJECT
//					e :: ELEMENT TO RECEIVE DATA
//
//	RETURN		:	NONE
//
//	NOTES		:	readyState EQUAL TO 4 SIGNIFIES A COMPLETE
//					RESPONSE FROM THE SERVER
//
//	AUTHOR		:	JOHNATHAN HEBERT
//
//	DATE		:	2006-03-17
//
//////////////////////////////////////////////////////////////
function response(req) 
{
	// WAIT FOR COMPLETE AND OK RESPONSE BEFORE HANDLING DATA
	if (req.readyState == 4)
	{
		// REMOVE THE EVENT HANDLER FOR IE BUG
		req.onreadystatechange = function () {};
		
		// CREATE THE RESPONSE DATA VARIABLE
		var response = "";
		
		// IMPORT EACH LINE OF HEADER INTO AN ARRAY
		var headerArray = req.getAllResponseHeaders().split(/\r?\n/);
		
		// INITIALIZE AN ASSOCIATIVE HEADER ARRAY
		var headers = new Array();
		
		// CREATE EACH HEADER ARRAY ELEMENT LIKE headers["headerName"] = "headerValue"		
		for (var i = 0; i < headerArray.length; i++)
		{
			hc = headerArray[i].split(/:\s?/);
			headers[hc[0].toUpperCase()] = hc[1];
		}
		
		// CHECK REQUEST STATUS AND DISPLAY APPROPRIATE DATA
		if (req.status == 200)
		{
			response = req.responseText;
		}
		else
		{
			response  = "ERROR CODE : " + req.status + "<br>" +
						"ERROR MESSAGE : " + req.statusText + "<hr><br><br>" +
						req.responseText;
		}
		
		process(response);
	}
	else
	{
		// DO SOMETHING WHILE REQUEST IS NOT YET COMPLETE
	}
}

//////////////////////////////////////////////////////////////
//
//	NAME		:	createXMLHttpRequest()
//
//	DESCRIPTION	:	CREATE REQUEST OBJECT IF POSSIBLE
//
//	PARAMETERS	:	NONE
//
//	RETURN		:	VALID REQUEST OBJECT OR null OBJECT
//
//	NOTES		:	EACH BROWSER HAS A DIFFERENT WAY OF
//					INSTANTIATING THE REQUEST OBJECT
//
//	AUTHOR		:	JOHNATHAN HEBERT
//
//	DATE		:	2006-03-17
//
//////////////////////////////////////////////////////////////
function createRequest()
{
	// DEFINE ARRAY OF ALL MICROSOFT XMLHTTPREQUEST OBJECTS
	var requestVersions = 	[
							"MSXML2.XMLHttp.5.0",
							"MSXML2.XMLHttp.4.0",
							"MSXML2.XMLHttp.3.0",
							"MSXML2.XMLHttp",
							"Microsoft.XMLHttp"
							];
	
    // ATTEMPT TO CREATE MOZILLA XMLHTTPREQUEST
    if (typeof(XMLHttpRequest) != "undefined")
    {
        return new XMLHttpRequest();
    }

	// ATTEMPT TO CREATE MICROSOFT XMLHTTPREQUEST REQUEST
	for (var i = 0; i < requestVersions.length; i++)
	{
		try
		{
			return new ActiveXObject(requestVersions[i]);
		}
		catch (ex)
		{
			// DO NOTHING
		}
	}
	
	// RETURN null OBJECT UPON FAILURE TO CREATE OBJECT
	return null;
}function calendar()
{
	this.date = new Date();
	this.month_names = new Array(null,"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	this.day_names = new Array(null,"sunday","monday","tuesday","wednesday","thursday","friday","saturday");
	this.month = this.date.getMonth() + 1;
	this.day = this.date.getDate();
	this.year = this.date.getFullYear();
	this.id = null;
	
	this.node = function()
	{
		var cal = dce("table");
		var cal_body = dce("tbody");
		var tr,td,th;
		
		var c = new calendar();
		c.year = dgi(this.id + "[year]").value;
		c.month = dgi(this.id + "[month]").value;
		c.day = dgi(this.id + "[day]").value;
		var month_day = 0;
		var day_num = 0;
		var prev_days = c.previous_days();
		var prev_month_day = (++prev_days - c.first_day_num());
		var next_month_day = 0;
				
		tr = dce("tr");
		td = dce("td");
		td.appendChild(dct("-"));
		tr.appendChild(td);
		td = dce("td");
		td.setAttribute("colspan","5");
		td.appendChild(dct(c.month_name() + " " + c.year));
		tr.appendChild(td);
		td = dce("td");
		td.appendChild(dct("+"));
		tr.appendChild(td);
		cal_body.appendChild(tr);

		tr = dce("tr");
		td = dce("td");
		td.appendChild(dct("<"));
		tr.appendChild(td);
		td = dce("td");
		td.appendChild(dct("<"));
		tr.appendChild(td);
		td = dce("td");
		td.setAttribute("colspan","3");
		tr.appendChild(td);
		td = dce("td");
		td.appendChild(dct(">"));
		tr.appendChild(td);
		td = dce("td");
		td.appendChild(dct(">"));
		tr.appendChild(td);
		cal_body.appendChild(tr);
		
		for (rows=1; rows<=6; rows++)
		{
			tr = dce("tr");
			for (cols=1; cols<=7; cols++)
			{
				td = dce("td");
				++day_num;
				var text = null;
				if (day_num < c.first_day_num())
				{
					text = ++prev_month_day;
					td.setAttribute("class","disabled");
				}
				else if (day_num >= (c.first_day_num() + c.days()))
				{
					text = ++next_month_day;
					td.setAttribute("class","disabled");
				}
				else
				{
					text = ++month_day;
				}
				td.appendChild(dct(text));
				tr.appendChild(td);
			}
			cal_body.appendChild(tr);
		}

		cal.appendChild(cal_body);
		cal.setAttribute("id",this.id);
		cal.setAttribute("class","minical");
		return cal;
	}
	
	this.show_days = function(ddl_month,ddl_day,ddl_year)
	{
		this.month = ddl_month.value;
		this.year = ddl_year.value;
		var c = new calendar();
		c.month = this.month;
		c.year = this.year;
		if (this.month>0)
		{
			for (i=1; i<=31; i++)
			{
				if (i>this.days())
				{
					//alert(i + " : " + list("",ddl_day.options[i]).join());
					//ddl_day.removeChild(ddl_day.options[i]);
				}
				ddl_day.options[i].style.cssText = (i<=this.days()) ? "display:block;" : "display:none;";
			}
		}
		if (ddl_day.value > c.days())
		{
			ddl_day.selectedIndex = 0;
		}
	}
	
	this.leap_year = function()
	{
		if ((this.year % 4) == 0)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	this.days = function()
	{
		var m = this.month;
		if (m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12)
		{
			return 31;
		}
		else if (m==4 || m==6 || m==9 || m==11)
		{
			return 30;
		}
		else if (m==2)
		{
			return (this.leap_year()) ? 29 : 28;
		}
		else
		{
			return null;
		}
	}
	
	this.day_num = function()
	{
		d = new Date(this.year,this.month - 1,this.day);
		return d.getDay() + 1;
	}
	
	this.first_day_num = function()
	{
		var c = new calendar();
		c.month = this.month;
		c.day = 1;
		c.year = this.year;
		return c.day_num();
	}
	
	this.month_name = function()
	{
		return this.month_names[this.month];
	}
	
	this.day_name = function()
	{
		return this.day_names[this.day];
	}
	
	this.previous_month = function()
	{
		return (this.month == 1) ? 12 : (this.month - 1);
	}
	
	this.previous_month_year = function()
	{
		return (this.month == 1) ? (this.year - 1) : this.year;
	}
	
	this.previous_year = function()
	{
		return this.year - 1;
	}

	this.previous_days = function()
	{
		var c = new calendar();
		c.month = this.previous_month();
		c.year = this.previous_month_year();
		return c.days();
	}

	this.next_month = function()
	{
		return (this.month == 12) ? 1 : (this.month + 1);
	}
	
	this.next_month_year = function()
	{
		return (this.month == 12) ? (this.year + 1) : this.year;
	}
	
	this.next_year = function()
	{
		return this.year + 1;
	}

	this.next_days = function()
	{
		var c = new calendar();
		c.month = this.next_month();
		c.year = this.next_month_year();
		return c.days();
	}
}

	

