// Place the CapeEvents code into a CapeEvents namespace. This function will export
// just those methods that should be publically exposed, including:
//   
//   fetch
//   render
//   data
//   
// Of these, only fetch is important to clients. The render method and the data
// property are exposed for implementation reasons. 

var CapeEvents = new function(){
	
	// ID attribute of the HTML element containing our template.
	
	var _elementID = null;
	
	// Number of times we've checked to see if the CapeEvents data struct has been
	// returned.
	
	var _lookupAttempts = 0;
	 
	// Limits the number of times we check for the data structure. 100 at 10 per
	// second equals 10 seconds.
	
	var _maxLookupAttempts = 100;
	
	// Controls how long we wait inbetween checks to see if the data structure
	// has been returned.
	  
	var _interval = 100; // milliseconds
	
	var _MaxNumberOfEvents = 5; // max number of events to display
	
	
	// Fetches the data from the server. The data is serialized in a JSON data
	// structure. It will be eval'd into the CapeEvents.data member.
	
	function loadData(options) {
		
		var scriptElement = document.createElement("script");
		
		scriptElement.setAttribute("type", "text/javascript");
		
	  	scriptElement.setAttribute("language", "JavaScript");
	  	
	  	// Check for debug mode
	  	
	  	if (options.debugMode && (options.debugMode == "yes" || 
	  							  options.debugMode == "true" ||
	  							  options.debugMode == "1")) {
	  		var domain = "localhost";
	  	} else {
	  		var domain = "www.capeevents.com";
	  	}
	  		
		// Add a serialized timestamp value to the URL to prevent browsers from
		// caching the result.

		var ts = new Date();

		var url = "http://" + domain + "/widget.cfm?ts=" + ts.valueOf();
		
		if (options) 
			{
				if (options.MaxNumberOfEvents && !isNaN(options.MaxNumberOfEvents) && options.MaxNumberOfEvents > 0) 
					{
						url += "&maxrows=" + options.MaxNumberOfEvents;
					}
				
				if (options.TownID && !isNaN(options.TownID) && options.TownID > 0) 
				{
						url += "&Town_ID=" + options.TownID;						
				}
				
				if (options.CatID && !isNaN(options.CatID)) 
				{
						url += "&Cat_ID=" + options.CatID;	
				}
				if (options.EventIsFree && !isNaN(options.EventIsFree)) 
				{
						url += "&Event_IsFree=" + options.EventIsFree;	
				}
				if (options.EventPetsWelcome && !isNaN(options.EventPetsWelcome)) 
				{
						url += "&Event_PetsWelcome=" + options.EventPetsWelcome;	
				}
				if (options.FromDate && !isNaN(new Date(options.FromDate))) 
				{
						url += "&fromdate=" + options.FromDate;	
				}
				if (options.ToDate && !isNaN(new Date(options.ToDate))) 
				{
						url += "&todate=" + options.ToDate;	
				}
				if (options.Keywords) 
				{
						url += "&Keywords=" + options.Keywords;	
				}
				if (options.KeywordsSearchType) 
				{
						url += "&KeywordsSearchType=" + options.KeywordsSearchType;	
				}	
			}

		scriptElement.setAttribute("src", url);
		
		document.getElementsByTagName("head")[0].appendChild(scriptElement);
		
	}
	
	// Returns a reference to the container element into which the CapeEvents
	// data will be rendered.
	
	function getCapeEventsElement() {
		
		return document.getElementById(_elementID);
		
	}
	
	// Returns true if the CapeEvents data structure, CapeEvents element and template
	// elment (assuming there is one) have all been loaded. If so, then we can
	// begin rendering the CapeEvents.
	
	function isLoaded() {
		
		if (CapeEvents.data == null) {
			
			return false;
			
		}
		
		if (getCapeEventsElement() == null) {
			
			return false;
			
		}
		
		return true;
		
	}
	
	// Renders the CapeEvents data using either a custom, user-defined template or
	// the default template. The product is placed into the specified HTML
	// element (usually a div). This function loops, defering execution until
	// all dependencies have been loaded. Once the CapeEvents has been rendered,
	// the callback function is executed (if it has been defined).
	
	function render() {
		
		_lookupAttempts++;
		
		if (!isLoaded()) {
			
			if (_lookupAttempts <= _maxLookupAttempts) {
				
				window.setTimeout("CapeEvents.render()", _interval);
				
			} else {
				
				window.status = "Failed to load CapeEvents after " + _maxLookupAttempts + " attempts.";
				
			}
			
			return;
			
		}
		
		// The CapeEvents element is the HTML element into which we'll render the
		// CapeEvents.
		
		var CapeEventsElement = getCapeEventsElement();
		
		
		CapeEventsElement.innerHTML = CapeEvents.data;
		
	}
	
	// This is the main entry point for client applications. The only required
	// parameter is elementID. elementID is the HTML ID attribute of the element
	// which will contain the CapeEvents (usually a div).
	// 
	// If the document contains a custom template for rendering the content, the
	// ID of the template element can be specified. If no template ID is
	// specified, a default template is used.
	// 
	// Finally, if work needs to be done once the CapeEvents has been rendered, a
	// call back function can be supplied. This should be an actual function
	// reference, not the name of a function.
	
	function fetch(elementID,options) {

		loadData(options);
		
		_elementID = elementID;
		
		
		render();
		
	}
	
	// Expose our public interface. We'll expose the fetch method because that
	// is the entry point for client applications. We need to expose the render
	// method because that is called by the window.setTimeout() method. The
	// data property is exposed so that, when the browser loads the JavaScript
	// file with the JSON payload, it can be passed into this object.
	
	return {
		"fetch" : fetch,
		"render" : render,
		"data" : null
	};
	
};