$(document).ready(function() {
	var firstDataEvent = true;
	var jsReadyCalled = false;
	var mapLoading = false;
	
	//since js is turned on we want to change the hrefs to javascript:; to disable them to stop reloading
	var count = 1;
	while(true){
		if($('a[name=anounderline' + count + ']').length == 0){
		  break;
		}
		
		if($.browser.msie && $.browser.version.substr(0,1) < 7) {
			$('a[name=anounderline' + count + ']').attr("href", "#");	
        } else {
        	$('a[name=anounderline' + count + ']').attr("href", "javascript:;");
        }
		
		count++;
	}
	//$('#tablelink').attr("href", "javascript:;")	
	
	$('.js-only').show();

	if (window.WRAPPERID) {
		
		var fo = new FlashObject(window.SWFURL, window.WRAPPERID, window.SWFWIDTH, window.SWFHEIGHT, "7", "#FFFFFF");
	    fo.write("flashcontent");
		
		// if the flash has been unable to load, show the hidden no-flash content
		$("#flashcontent:not(:has(object, embed))").html($("#no-flash-message").html());

		window.wrapper = RMXController.createWrapper(WRAPPERID);
		
		window.wrapper.addEventListener("legendurlavailable", function (args) {
			var url = args.legendurl + "?killcache=" + (new Date().getTime());
			$('img[class=map-legend-loading]').hide();
			$('#the-key-gif').attr('src', url);
		});

		// do this now incase it has already started up
		window.wrapper.addEventListener("mapReady", function (evt) {
			if (!jsReadyCalled) {
				jsReadyCalled = true;
				window.wrapper.callMethod("javascriptReady", []);
			}
		});
		
		window.wrapper.addEventListener("poiLoaded", function (evt) {
			if (!(evt.poiNames == null || evt.poiNames.length == 0)
					&& evt.featureCount == 0) {
				$('#map-message').fadeIn();
				$('#map-message-text').html(
						"No points of interest could be found for this neighbourhood");
			}
		});
		
		window.wrapper.addEventListener("regionClick", function (evt) {
			
			var url = document.URL;
			
			url = url.replace(/regioncode=[A-Z]{4}/, "regioncode=" + evt.code);
			url = url.replace(/&marker=(.)*\[(.)*\]/, "");
			location.href = url;
			window.wrapper.callMethod("showLoading", []);
		});
		
		window.wrapper.addEventListener("mapLoading", function (evt) {
			mapLoading = true;
			$('input[type=submit]').fadeTo(200, .5);
		});
		
		window.wrapper.addEventListener("mapLoaded", function (evt) {
			mapLoading = false;
			$('input[type=submit]').fadeTo(200, 1);

			if (firstDataEvent) {
				firstDataEvent = false;
				// set poi to client once it has all loaded up
				poi_apply();
			}
		});

		$('#select-poi').submit(function (evt) {

			if (mapLoading) {
				return false;
			}

			$('#map-message').fadeOut();
			var selPoi = [];
			$("[@id=select-poi] input[@checked]").each( function(idx, item) {
				selPoi.push(item.name);
			});

			window.wrapper.callMethod("setPoi", [ selPoi ]);
			return false;
		});
	}

});

function refreshPageForGraph(){
	var aId = $('.lihighlight').children('a').attr('id');
	var index = Number(aId.split('line')[1]) - 1;
	window.wrapper.callMethod("setQuestion", [index]);
}

function refreshPageForTable(){
	var url = $('#showtablelink').attr('href');
	var splitUrl = url.split('#the-table');
	var aId = $('.lihighlight').children('a').attr('name');
	var index = Number(aId.split('line')[1]) - 1;
	
	var newUrl = '';
	
	if(splitUrl[0].indexOf('questionIndex') != -1){
		var str = 'questionIndex=' + index;
		var re = new RegExp('questionIndex' + "=[^&#]+");
		newUrl = url.replace(re, str);
	} else {
		newUrl = splitUrl[0] + '&questionIndex=' +  index + "#the-table";
	}
	
	window.location = newUrl;
}

function updateSurveys(url){
	//table view
	if($('#show-table-li').attr('class') == 'on'){
		window.location = url + '&viewtab=table';
		return false;
	}
	//cause its index add one
	var questionNumber = url.substring(url.length - 1, url.length );
	//graph
	window.wrapper.callMethod("setQuestion", [questionNumber]);
	//highlight question
	var nameAttr = 'qli' + (Number(questionNumber) + 1);
	//switch off other
	$('.lihighlight').attr('class', 'linohighlight');
	$('dt[id=' + nameAttr + ']').attr('class', 'lihighlight');
	//change question title
	var title = $('a[name=anounderline' + (Number(questionNumber) + 1) + ']').attr('title');
	$('#ftdquestiontext').html('<strong>' +  title + '</strong>'); 
}

$(document).ready( function() {
	function addUpdateParamValue(url, name, value) {
		// Add a query part if it's missing
		if (url.indexOf('?') < 0) url += '?';
		// Extract the queryString
		var urlBits = url.split('?');
		var queryString = urlBits[1];
		// Create the new param string
		var str = name + "=" + value;
		// Find and replace the current param string if it exists
		var re = new RegExp(name + "=[^&#]+");
		if (queryString.search(re) > -1) {
			queryString = queryString.replace(re, str);
		} else {
			// it doesn't exist so replace it
			var params = queryString.split('&');
			params.unshift(str);
			queryString = params.join('&');
		}
		return urlBits[0] + "?" + queryString;
	}
	var viewtab;
	var tableDirty = false;
	// Handle hiding/showing view tabs on the client
	$('#map-table-selector').show().tabify( {
		prechange : function() {
			viewtab = $(this).find('a').param('viewtab');
			// Update the form action to point at the new view when a view tab is clicked
			$('#filter-by-crime').attr('action', function() {
				return addUpdateParamValue($(this).attr('action'), 'viewtab', viewtab);
			});
			// Track whether the table should be reloaded
			if (viewtab == 'table' && tableDirty) {
				$('#filter-by-crime').submit();
				return false;
			}
		}
	,
		postchange : function() {
			
			var hash = $(this).find('a').attr('hash');
			// remove leading # from anchor target
			hash = hash.substring(1)
			// only show toggled elements that are shown with the currently selected tab
			// (denoted by chart-table-toggled class and 
			var toggled = $('#crime-infos .chart-table-toggled'); 
			toggled.hide();
			toggled.filter("." + hash + '-only').show();
		}
	});
	// Show selected view tab
	$('#map-table-selector').children('li.on').click();
	
	var filtertab = $('#crimefilter ul.tabs li.on').find('a').param('filtertab');
	// Handle hiding/showing filter tabs on the client
	$('#crimefilter ul.tabs').tabify( {
		prechange : function() {
			filtertab = $(this).find('a').param('filtertab');
			// Update the form action to point at the new filter when a filter tab is clicked
			$('#filter-by-crime').attr('action', function() {
				return addUpdateParamValue($(this).attr('action'), 'filtertab', filtertab);
			});
			// Auto-commit the crimetype form if switching tabs
			$('#filter-by-crime input[name=filtertype]').val(filtertab);
			// Don't switch tabs if looking at the table
			if (viewtab == 'table') {
				return false;
			}
		},
		postchange : function() {
			$('#filter-by-crime').submit();
			filtertab = $(this).find('a').param('filtertab');
			$('#crime-infos .parent-type').hide();
			$('#crime-infos .' + filtertab).show();
		}
	});
	// Add shortcuts for no data links
	 $('#crimefilter a.nodata').shortcutify();
	// Add asynchronous loading of graph data
	$('#filter-by-crime').submit(function() {
		var codes = [];
		$('#filter-by-crime input:checked[name^="ct."], #filter-by-crime input:hidden[name^="ct."]').each(function(){
			var name = $(this).attr('name');
			codes.push(name.substr(name.indexOf('.') + 1)); 
		});
		var visibleCheckboxes = $("#filter-by-crime .tabpanel:visible input:checkbox");
		// Ensure that if there are visible checkboxes at least one is checked 
		if (visibleCheckboxes.length && !visibleCheckboxes.is(":checked")) {
			alert('Please select at least one crime type');
			return false;
		} else {
			// Remove change highlighting
			$('div.crime-filter li.changed').removeClass('changed');
			$('div.crime-filter li.change-info').hide();
			// if graph is currently selected then use asynchronous load
			if (viewtab == 'graph') {
				window.wrapper.callMethod("setCrimeTypes", [ filtertab, codes ]);
				tableDirty = true;
				$('img[class=map-legend]').hide();
				$('img[class=map-legend-loading]').show();
				// don't submit the form
				return false;
			}
		}
	});
	
	// Highlight dirty fields - don't handle tab changes as it auto-commits
	$('#filter-by-crime input:checkbox').click(function() {
		$(this).parents('li.crime-type').addClass('changed');
		$('div.crime-filter li.change-info').show();
	});
	
	// Handle select/deselect all
	//
	$('.crime-filter a.toggle-all').click( function() {
		var checkedInputs = $("#filter-by-crime .tabpanel:visible input[@checked]");
		var allInputs = $("#filter-by-crime .tabpanel:visible input");

		if ((checkedInputs.length * 2) > allInputs.length) {
			allInputs.removeAttr('checked').parent().parent().addClass('changed');
		} else {
			allInputs.attr('checked', 'checked').parent().parent().addClass('changed');
		}

		$('div.crime-filter li.change-info').show();

		return false;
	});
	// Map table tabs
	$('#table-switcher').tabify({
		postchange : function() {
			var filtertab = $(this).find('a').param('filtertab');
			$('#crime-infos .parent-type').hide();
			$('#crime-infos .' + filtertab).show();
		}
	});
});

/**
 * Extend jQuery to add parameter extraction support for anchor tags
 */
jQuery.fn.param = function(name, defaultValue) {
	var search = this.attr('search');
	if (search) {
		var matches = search.match(new RegExp(name+"=(\\w+)"));
		if (matches) {
			return matches[1];
		}
	}
	return defaultValue || '';
};

/**
 * Extend jQuery to add tab support. optional 
 * @param prechange specifies function to call before switching to a tab. 
 * 			Returning false from the function cancels the switch.
 * @param shortcuts specifies any additional anchor elements which provide 
 * 			shortcuts to tabs.
 */
jQuery.fn.tabify = function(params) {
	params = params || {};
	// Apply to each group of tabs (each ul)
	this.each(function() {
		var onClassName = (params && params.onClassName) || 'on';
		var tabs = $(this).children('li');
		var panels = [];
		tabs.each(function() {
			panels.push($(this).find('a').attr('hash'));
		});
		panels = $(panels.join(','));
		tabs.click(function() {
			if (!(params.prechange && (params.prechange.call(this) === false))) {
				var tab = $(this), panel = $(tab.find('a').attr('hash'));
				tabs.removeClass(onClassName);
				panels.hide();
				tab.addClass(onClassName);
				panel.show();
			}
			params.postchange && params.postchange.call(this);
			return false;
		});
	});
	return this;
};

/**
 * Extend jQuery to add support for shortcuts. A shortcut is an anchor who's href
 * hash is the id of the target element on the page. Click events are then
 * captured on the anchor and passed through to the target. N.B. Only jQuery
 * bound handlers will be called.
 */
jQuery.fn.shortcutify = function(params) {
	this.each(function() {
		$(this).click(function() {
			$($(this).attr('hash')).click();
			return false;
		});
	});
	return this;
};
