var search_date = new Date();
var cookie_prefix = SEARCH_COOKIE_PREFIX + ':event:';
var default_days_around = 7;
var init_search;

function evtDateChanged(calendar)
{
	// This function is called even if the end-user only
	// changed the month/year. In order to determine if a date was
	// clicked use the dateClicked property of the calendar:
//	if (calendar.dateClicked) {
		// OK, a date was clicked
	search_date = calendar.date;

	key = String(search_date.getFullYear()) + String(search_date.getMonth());
	if (window.event_dates[key] == null) {
		setTimeout('getEventDates(' + search_date.getFullYear() + ', ' + search_date.getMonth() + ')', 1);
	}

	$('search_btn').click();

	return true;
}

function evtDateStatus(date, y, m, d) {
	if (dateHasEvent(date.getFullYear(), date.getMonth(), date.getDate())) {
		return "special";
	}
	else
		return false; // other dates are enabled
		// return true if you want to disable other dates
}

function dateHasEvent(y, m, d)
{
	key = String(y) + String(m);
	if (window.event_dates[key] == null) {
		return false;
	}
	return window.event_dates[key][d];
}

function getEventDates(y, m)
{
	var req = new XHR({
			method: 'get',
			onSuccess: function(response) {processEventDates(y, m, response);}
			//, onFailure: function(response) {alert('Loading event dates failed!');}
		}).send('index.php?option=com_mykidstime&task=listings.evtdates&y=' + y + '&m=' + (Number(m) + 1));
}

function processEventDates(y, m, response)
{
	key = String(y) + String(m);
	window.event_dates[key] = new Array(); //Object();
	result = window.event_dates[key];

	regex = /<day\>[0-9]{1,2}\<\/day>/g;
	arr = response.match(regex);

	$A(arr).each(function(d){result[((/>([0-9]*)</).exec(d))[1]] = true;});

	resetCalendar();

	return true;
}

function clearListings()
{
	$('results').innerHTML = 'Search Results';
	$('listings').innerHTML = '';
}

function updateEvents(listings)
{
	var lsts = $('listings');
	var evts = '';
	var recEvts = '';
	var otherRegEvts = '';

	var catname = $('cname').value;
	// Save the search criteria so it can be restored on returning to the page
	$A($('searchForm').elements).each(function(el){if (el.type != 'hidden' && el.type != 'submit') Cookie.set(cookie_prefix + el.id, getElementValue(el));});
	Cookie.set(cookie_prefix + 'search_date', search_date);

	// Clear current listing contents
	clearListings();

	// Add category name to search results heading of defined
	if ($chk(catname)) {
		$('results').innerHTML += ' for \'' + catname + '\'';
	}

	if (!listings || !listings.childNodes.length) {
		//lsts.innerHTML = 'There were no listings found for your search criteria.';
		lsts.innerHTML = 'We\'re sorry, we haven\'t found any listings for your search criteria. If you are a provider please visit the Contact Us area to submit a free listing for your business.';
		$('status').innerHTML = 'No results found';

		return false;
	}

	var srch_region = $('region').options[$('region').selectedIndex].value;
	var outputHeading = false;

	var hostname = window.location.hostname;
	hostname = 'www.' + hostname.substr(hostname.indexOf('mykidstime'));

	for (var i=0; i < listings.childNodes.length; i++) {

    	var node = listings.childNodes[i];
    	var elementOutput = '';
       	var recurring = (getNodeTextByName(node,'recurring_event') == '1');
       	var evtRegion = getNodeTextByName(node,'region_id');

		var enhanced = Number(getNodeTextByName(node,'enhanced'));
        var tn = getNodeTextByName(node,'thumbnail_image_url');
        var img = tn.length ? '<img width="32px" height="32px" src="' + tn + '"/>' : '';

        // Temporary fix until images supplied for event categories
        img = '';

        sdate = getNodeTextByName(node,'start_date');
        edate = getNodeTextByName(node,'end_date');

        rowColor = (i % 2) ? 'white' : 'green';

        var dateStr = formatDateRange(sdate, edate);
        if (!dateStr || recurring)
        	dateStr = 'See listing<br/>for times'
        elementOutput += '<div class="lst1_row_box_' + rowColor + ' ' + rowColor + '">';
        elementOutput += '  <div class="lst1_tlc"><div class="lst1_trc"><div class="lst1_blc"><div class="lst1_brc">';
        elementOutput += '	<div class="lst1_row_data' + (enhanced ? '_enh' : '') + '" >';
        elementOutput += '	  <div class="evt1_col1">' + img + '</div>';
        elementOutput += '	  <div class="evt1_col2">' + dateStr + '</div>';
        elementOutput += '	  <div class="evt1_col3"><a href="http://' + hostname + '/index.php?option=com_mykidstime&view=listing&lid=' + getAttrByName(node, 'id') + '&Itemid=' + listingItemid + '">' + getNodeTextByName(node,'name') + '</a></div>';
        elementOutput += '	  <div class="evt1_col4">' + formatLocation(node) + '</div>';
        if (enhanced) {
        	elementOutput += '  <div class="evt1_col5">' + getNodeTextByName(node,'description') + '</div>';
        }
        elementOutput += '	</div>';
        elementOutput += '  </div></div></div></div>';
        elementOutput += '</div>';

       	if (recurring) {
        	recEvts += elementOutput;
		}
       	else if (srch_region > 0 && evtRegion != srch_region) {
        	otherRegEvts += elementOutput;
		}
        else {
        	evts += elementOutput;
        }
    }

	lsts.innerHTML = evts;

	if (recEvts) {
		lsts.innerHTML += '<h4>Regularly occurring events</h4>';
		lsts.innerHTML += recEvts;
	}

	if (otherRegEvts) {
		lsts.innerHTML += '<h4>Events of interest in other regions</h4>';
		lsts.innerHTML += otherRegEvts;
	}

	$('status').innerHTML = listings.childNodes.length + ' results found';

	// Jump to the results if not just performing initial search
	if (init_search) {
		init_search = false;
	}
	else {
		TF.Scroller.anchorScrollManual($('results_link'));
//		var hashValue="#results";
//		if (location.hash!=hashValue)
//			location.hash=hashValue;
	}

	return true;
}

function formatLocation(node)
{
	result = '';
	loc = getNodeTextByName(node,'location_name');
	reg = getNodeTextByName(node,'region_name');
	searchReg = $('region').value;

	result = reg + (loc.length ? '<br/>(' + loc + ')' : '');

//	if (loc.length)
//		result = loc;
//	result += result.length ? '<br/>(' + reg + ')' : reg;

	return result;
}

function formatDateRange(sdate, edate)
{
	if (sdate && edate) {
		sdate = new Date(sdate.replace(/-/g, '/'));
		edate = new Date(edate.replace(/-/g, '/'));
		if (sdate.getMonth() == edate.getMonth()) {
			if (sdate.getDate() == edate.getDate()) {
				return sdate.format('dd mmm');
			}
			return sdate.format('dd') + ' - ' + edate.format('dd mmm');
		}
		else {
			return sdate.format('dd mmm') + ' - ' + edate.format('dd mmm');
		}
	}
	else if (sdate) {
    	return (new Date(sdate.replace(/-/g, '/'))).format('dd mmm');
    }
	else if (edate) {
   		return 'ends ' + (new Date(edate.replace(/-/g, '/'))).format('dd mmm');
    }

    return '';
}

function onfilterevents()
{
	// Set start and end date values for search
	$('start_date').value = search_date.format('yyyy-mm-dd');
	days_around = Number(getRadioValue($('searchForm'), 'days_around'));
	$('end_date').value = new Date(search_date.getFullYear(), search_date.getMonth(), search_date.getDate() + days_around).format('yyyy-mm-dd');

	$('status').innerHTML = 'Fetching events...';

	//Perform the search
	window.listingsManager.fetchListingsData(false, updateEvents);

	return false;
}

function resetCalendar()
{
	//return true;
	$('evt_calendar').innerHTML = '';

	Calendar.setup(
			{
				flat			: "evt_calendar",
				flatCallback	: evtDateChanged,
			//Temporarily removed the following until find a better solution.
				//dateStatusFunc	: evtDateStatus,
				weekNumbers		: false,
				displayArea		: "evtdate",
				showOthers		: true,
				date		    : search_date,
				daFormat		: "%Y-%m-%d"
				//range			:
			}
		);
}

function resetForm()
{
	form = $('searchForm');

	// Reset search date
	search_date = new Date();

	// Reset the calendar control - couldn't find a way to reach the original one, so just destroy it
	// Possibly leaves the old cal object laying around - not much can be done about it :-(
	resetCalendar();

	// Reset other fields
	$A(form.elements).each(function(el){
			if (el.nodeName == 'INPUT') {
				switch (el.type) {
				case 'checkbox':
					el.checked = false;
					break;
				case 'radio':
					setRadioValue(el.form, el.name, 0);
					break;
				case 'text':
					el.value = '';
					break;
				}
			}
			if (el.nodeName == 'SELECT') {
				el.selectedIndex = 0;
			}
		});

	// Reset region field using user's region cookie
	region = Cookie.get(REGION_COOKIE_LABEL);
	$A($('region').options).each(function(opt){if (opt.value == region) $('region').selectedIndex = opt.index;});
	onregionchange();

	// Reset 'Days Beyond' to default value
	setRadioValue(form, 'days_around', default_days_around);

	$('search_btn').click();
}

function onregionchange() {
	UpdateLocations($('region'), $('location'), locations);
}

//function onlocationchange() {
//	UpdateLocations($('location'), $('venue'), venues);
//}

window.addEvent('load', function() {

	// Check if any search criteria supplied in URI.
	// If so, use this in preference to any cookie values
	var query = parseQueryString();
	ext_search = false;
	$A($('searchForm').elements).each( function(el) {
			if ($(el).hasClass('search_criteria') && query[el.id] != undefined) {  // IE seems to require the $(el)... stupid IE!
				setElementValue(el, URLDecode(query[el.id]));
				if (el.id == 'start_date')
					search_date = new Date(query[el.id]);
				ext_search = true;
				init_search = false;
			}
		});


	if (!ext_search) {
		// Restore saved cookie settings
		$A($('searchForm').elements).each( function(el) {
				$(el);
				if (el.type != 'hidden' && el.type != 'submit') {
					setElementValue(el, Cookie.get(cookie_prefix + el.id));
					if (el.id == 'region') onregionchange();
				}
			});

		// Initialise search date from cookie if it exists
		search_date_cookie = Cookie.get(cookie_prefix + 'search_date');
		if (search_date_cookie != false) search_date = new Date(search_date_cookie);
	}

	// Initialise region field from GET request or user's nominated region if lstsch cookie not already set
	var region = '';
	if (!Cookie.get(cookie_prefix + 'region')) {
		query = window.location.search.split('&');
		$A(query).each(function(q){ vals = q.split('='); if (vals[0] == 'region') region = vals[1];});
		if (!region.length)
			region = Cookie.get(REGION_COOKIE_LABEL);
		$A($('region').options).each(function(opt){if (opt.value == region) $('region').selectedIndex = opt.index;});
		onregionchange();
	}

	window.listingsManager = new ListingsManager();
	window.event_dates = new Array();

	// Establish calendar control
	getEventDates(search_date.getFullYear(), search_date.getMonth());

	// Set filter onlick handler
	$('search_btn').onclick = onfilterevents;
	// Set filter onlick handler
	$('reset_btn').onclick = resetForm;

	// Register drop-down change events
	$('region').onchange = onregionchange;
//	$('location').onchange = onlocationchange;

	// Perform initial search
	init_search = true;
	$('search_btn').click();
});


