//=======================================================================================//
//*** Javascript Class - AjaxLib - Prototype functions for AJAX use within javascript ***//
//=======================================================================================//

	//--------------------------------------------------------------------------
	//>>> MAIN STUB - AjaxLib - Creates a new instance of the AjaxLib object <<<
	//--------------------------------------------------------------------------
	function AjaxLib()
	{
		// Set object variables before creating the HTTPRequest object //
		this.ajaxStatus = '';
	
		try { this.req = new ActiveXObject('MSXML2.XMLHTTP.3.0'); }
		catch(er) { try { this.req = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch(er) { try { this.req = new XMLHttpRequest(); }
				catch(er) { alert('AjaxLib: ' + er.message); this.req = false; }
			}
		}
	}

	//------------------------------------------------------------------------------------
	//>>> PROTOTYPE - HttpStatus function - Tests the status of the httpRequest object <<<
	//------------------------------------------------------------------------------------
	AjaxLib.prototype.HttpStatus = function ()
	{
		//--- check XMLHttpRequest object status ---//
		if(this.req.readyState == 3) this.ajaxStatus = 'Downloading data';
	
		if(this.req.readyState == 4)
		{
			if (this.req.status == 200 && this.req.responseText.length>0)
			{
				//alert(this.req.responseText);		//=== D E B U G ===

				//--- Parse the ResponseText ---//
				try { this.xmlDoc = this.xmlParse(); }
				catch(e){ alert('PARSER ERROR'); return false; }
				
				this.ajaxStatus = 'loading';
				
				//--- Decode and build ---//
				AjaxLib.DecodeAndBuild( this.xmlDoc )
				
				this.ajaxStatus = 'complete';
			}
		}
	}

	//--------------------------------------------------------------------------
	//>>> PROTOTYPE - fileExists function - tests existence of a server file <<<
	//--------------------------------------------------------------------------
	AjaxLib.prototype.fileExists = function (filePath)
	{
		try
		{
			this.req.open("head", filePath, false);
			this.req.send(null);
			return true;
		}
		catch (er) { alert('fileExists: ' + er.message); return false; }
	}

	//------------------------------------------------------------------------
	//>>> PROTOTYPE - HTTPRequest function - Sends a HTTP request for data <<<
	//------------------------------------------------------------------------
	AjaxLib.prototype.HttpRequest = function (method, URL, requestParams)
	{
		try
		{
			var _this = this;
			
			//--- Decide how to handle the parameters based on the method ---//
			var page = method == 'POST' ? URL : URL + '?' + requestParams;

			//--- Start the request ---//
			this.req.open(method, page, true);

			//--- set http request header ---//
			this.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.req.setRequestHeader("Content-length", requestParams.length);
			this.req.setRequestHeader("Connection", "close");
			
			//--- Point to function to deal with request object state change ---//
			this.req.onreadystatechange = function() {_this.HttpStatus(); };
			this.req.send(requestParams);

			return true;
		}
		catch (er) { alert(er.message); return false; }
	}


	//--------------------------------------------------------------------------------------------------------
	//>>> PROTOTYPE - xmlParse function - Parses the return from httpRequest and returns a document object <<<
	//--------------------------------------------------------------------------------------------------------
	AjaxLib.prototype.xmlParse = function ()
	{
		try
		{
			//--- code for IE ---//
			if (window.ActiveXObject)
			{
				var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(this.req.responseText);
			}
			//--- code for Mozilla, Firefox, Opera, etc. ---//
			else
			{
				var parser=new DOMParser();
				var xmlDoc=parser.parseFromString(this.req.responseText,"text/xml");
			}
		}
		catch(e) { alert('PARSER ERROR'); return false; }
		
		return xmlDoc;
	}


	//=============================================================================
	//>>> APPLICATION-SPECIFIC - AjaxPostAndReturn - Return XML based on inputs <<<
	//=============================================================================
	AjaxLib.AjaxPostandReturn = function(ajaxObj, URL, method, params)
	{
		ajaxObj.HttpRequest(method, URL, params);
	}

	//=========================================================================================
	//>>> APPLICATION-SPECIFIC - DecodeAndBuild - Decode the XML and build what it contains <<<
	//=========================================================================================
	AjaxLib.DecodeAndBuild = function (xmlDoc)
	{
		//--- Send to buildThermometer function ---
		return buildThermometer ( xmlDoc );
	}	//>>> END DecodeAndBuild <<<//


	function createHtmlElement(ID, parent, html, elementType, classNm)
	{
		var newObj = document.createElement(elementType);
		if (ID != "") newObj.id = newObj.name = ID;
		if (html != "") newObj.innerHTML = html;
		if (classNm != "") newObj.className = classNm;
		parent.appendChild(newObj);
		return newObj;
	}
	

    function buildThermometer(xmlDoc)
	{
		var evt = 0; var evts = 0; var evfg = 0;
		var euvfg = 0; var euvt = 0; var euvts = 0;
		
		var includeOffline = true;
		var thermHeight = 200;

		//--- obtain the array of xmlElement's and loop through them ---
		var rows = window.ActiveXObject ? xmlDoc.childNodes[1].childNodes[0].childNodes : xmlDoc.childNodes[0].childNodes[1].childNodes;
		for (var iElem = 0; iElem < rows.length; iElem++) 
		{
			//--- Get the name and value of each child ---
			for (var iChild = 0; iChild < rows[iElem].childNodes.length; iChild++)
			{
				node = rows[iElem].childNodes.item(iChild);
				var colValue = window.ActiveXObject ? node.text : node.textContent;
				var colName = node.nodeName;

				if ( !isNaN(colValue) )
				{
					if (colName == "eventVerifiedTotalCollected") evt += parseFloat(colValue);
					if (colName == "eventVerifiedTotalSponsors") evts += parseFloat(colValue);
					if (colName == "eventVerifiedFundraisingGoal") evfg += parseFloat(colValue);
					if (colName == "eventUnVerifiedTotalCollected") euvt += parseFloat(colValue);
					if (colName == "eventUnVerifiedTotalSponsors") euvts += parseFloat(colValue);
					if (colName == "eventUnVerifiedFundraisingGoal") euvfg += parseFloat(colValue);
				}
			}
		}
				
		//--- Clean up the numbers before we move one ---						
		raisedN = (isNaN(evt)) ? 0 : evt;
		totalSponsors = (isNaN(evts)) ? 0 : evts;
		goalN = (isNaN(evfg)) ? 1 : evfg;
		offlineGoal = (isNaN(euvfg)) ? 0 : euvfg;
		offlineRaised = (isNaN(euvt)) ? 0 : euvt;
		offlineSponsors = (isNaN(euvts)) ? 0 : euvts;
		
		//--- Do all calculations now ---
		if (includeOffline == true) 
		{
			goalN = goalN + offlineGoal;
			raisedN = raisedN + offlineRaised;
		}

		goalN = parseInt(goalN);
		raisedN = parseInt(raisedN);
		var myPercent = Math.round(raisedN / goalN * 100);
		//if (myPercent > 100) myPercent = 100;
		
		goalN = goalN.toString();
		goalN = addCommas(goalN);

		raisedN = raisedN.toString();
		raisedN = addCommas(raisedN);

		//--- All percentages are rounded UP and in multiples of 5 - if rounding DOWN required, remove + 5 
		var pctPos = parseInt((myPercent-2.5)/5) * 5 + 5;
		if (pctPos >= 100) pctPos = 100;
		tStr = "000" + pctPos.toString(10);
		tStr = tStr.substr(tStr.length-3, 3);
		var thermGif = "url(thermometer/thermometer_" + tStr + ".gif)"; 


            var version = 0; var txtClass = "therm_foreground";
            if (navigator.appVersion.match("MSIE"))
            {
                        var arVersion = navigator.appVersion.split("MSIE");
                        var av = arVersion[1].split(";");
                        version = parseFloat(av[0]);
                               if ((version >= 5.5) && (version < 7)) txtClass = "pngfix";
            }
			
			var target = document.getElementById("thermometerHolder");
			
			//--- Replace the 3rd argument with a title if you want one ---
			//--- The 4th argument is for a class name (not used in this one) ---
			var thTitle = createHtmlElement("thermTitle", target, "", "DIV");
			createHtmlElement("", target, "", "DIV", "clear");
			
			var thWrap = createHtmlElement("thermWrapper", target, "", "DIV");
			var thHolder = createHtmlElement("therm_holder", thWrap, "", "DIV");
			var thMerc = createHtmlElement("thermometerpic", thHolder, "", "DIV", txtClass);
			thMerc.style.backgroundImage = thermGif;
			thMerc.style.width = "115px";
			thMerc.style.height = "250px";
			var thStats = createHtmlElement("stats_holder", thHolder, "", "DIV");
			var statsGoal = createHtmlElement("goal_holder", thStats, "Goal:", "DIV");
			createHtmlElement("target", statsGoal, goalN, "SPAN");
			var statsRaised = createHtmlElement("raised_holder", thStats, "Total raised so far: ", "DIV");
			createHtmlElement("totalraised", statsRaised, raisedN, "SPAN");
			var statsPct = createHtmlElement("percent_holder", thStats, "Percentage:", "DIV");
			createHtmlElement("percentage", statsPct, myPercent + "%", "SPAN");
 
    }


	var ajax = new AjaxLib;
	var URL = "/proxy.php";
	var method = "POST";
	var params = "eventID=9733&orgID=lfa";

	var ajax = new AjaxLib();
	AjaxLib.AjaxPostandReturn(ajax, URL, method, params);
	
    function addCommas(nStr) 
	{
		nStr += "";
		x = nStr.split(".");
		x1 = x[0];
		x2 = x.length > 1 ? "." + x[1] : "";
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) { x1 = x1.replace(rgx, "$1" + "," + "$2"); }
		return "$" + x1 + x2;
	}
