
var ListingsManager = new Class({

	// fetchListingsData
	// Description: retrieves listings data based upon the current search form parameters
	// 				via an Ajax request.
	//
	// Parameters:
	//  asynch - refresh data asynchronously on return from Ajax call.
	//			 This is needed if using the Atom widget in order to avoid
	//           pausing in the ring expansion animation of the widget
	//           when drawing the new listing data. Ring expansion on the largest
	//			 ring takes approximately 1700 msec.
	// onListings - call-back function to use on receipt of listings data
	fetchListingsData: function (asynch, onListings) {

		var query = '';
		var form = $('searchForm');

		$A(form.elements).each(function(el){
			var val = null;

			if (!el.hasClass('search_criteria')) return;

			if (el.nodeName == 'INPUT') {
				switch (el.type) {
				case 'checkbox':
					val = el.checked;
					break;
				case 'radio':
					break;
				default:
					if (el.value)
						val = el.value;
				}
			}
			if (el.nodeName == 'SELECT') {
				val = el.options[el.selectedIndex].value;
			}

			if (val) {
				query += '&' + el.id + '=' + escape(val);
			}
		});

		if (query.length > 0) {
			var start = (new Date).getTime();

			var req = new XHR({
							 method: 'get',
						  onSuccess: function(response) {
									var diff = (new Date).getTime() - start;
									if (!asynch || diff > 1700) {
										window.listingsManager.updateListingsData(response, onListings);
									}
									else {
										var callwrapper = new CCallWrapper(
												window.listingsManager,
												1700 - diff,
												'updateListingsData',
												response, onListings);
										CCallWrapper.asyncExecute(callwrapper);
									}
							  },
						 onFailure: function(response) {
								  	alert('Fetching events failed.');
							  }

							}).send('index.php?option=com_mykidstime&task=listings.search' + query);
		}
	},

	updateListingsData: function ( response, onListings ) {

		var xmlDoc = null;
    	var notIE = false;

		if (response == null)
			return onListings(null);

		// Mount response details as XML doc

        try {//Internet Explorer
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        }
        catch(e) {
        	notIE = true;
        }

        if (notIE) {
//        try { //Firefox, Mozilla, Opera, etc.
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(response,"text/xml");
//        }
//        catch(e) {alert(e.message);}
        }
	    else {
			xmlDoc.async = "false";
			xmlDoc.loadXML(response);
	    }

        var listings = xmlDoc.getElementsByTagName('listings').item(0);
        return onListings(listings);
	}
} );



