/*global $, thirdparty, showHtmlSubmitButton */

var objOption = false;

Array.prototype.indexOf = function (obj) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == obj) {
			return i;
		}
	}
	return -1;
};

Array.prototype.has = function (obj) {
	return this.indexOf(obj) >= 0;
};

var hvs_menu_obj = {
	buslines: {},
	rPlace: /(.+) \(([vanf t/m0-9]*)\)/
};

/**
 * Initiates the javascript functionality of the page elements
 */
function startSearch() {

	$('#hvsform').submit(function () {
		if (submittable() === false) {
			return false;
		}
	});

	selectModality();
	$('select#modality').change(selectModality);

	// ========= START OF THE BUS CODE =======
	$("input[name='bus_select_start']").change(function () {
		if ($("input[name='bus_select_start']").val() === '') {
			resetForm();
		}
	});
	
	var formatTown = function (item) {
		name = item.name;
		if (item.hasOwnProperty('daterange') && item.daterange!='') {
			dateRange = item.daterange;
			name += ' (' + dateRange + ')';
		}
		return name;
	};

	$("input[name='bus_select_start']").autocomplete('hvs_startPoint.php', {
		minChars: 3,
		limit: 100,
		matchCase: true,
		extraParams: {
			scenario: function () {
				return getModality();
			}
		},
		formatItem: function (row) {
			var item = eval("(" + row + ")");
			return formatTown(item);
		}
	})
	.result(function (event, item) {
		var modality = getModality();
		item = eval("(" + item + ")");
		$("input[name='" + modality + "_select_start']").val(formatTown(item));
		$("input[name='" + modality + "_start_id']").val(item.stops);
		$("input[name='" + modality + "_select_end']").val('');
		$("input[name='" + modality + "_end_id']").val('');
		$("div#" + modality + "_line_container").show();

		// bus only
//		$("#bus_line_container").hide();
		$("select[name='bus_select_line'] option").remove();

		// (re-)activate the autocomplete
		setBusEndPointAutoselect();

		loadBusSelect(item.lines, true);

		$("input[name='" + modality + "_select_end']").focus();

	});

	$("select[name='bus_select_line']").change(function () {
		var busline = $("select[name='bus_select_line']").val();
		$("input[name='bus_line']").val(busline);
		$("div#bus_endpoint_container").show();

		if (hvs_menu_obj.buslines['line_'+busline]) {
			$("input[name='Direction']").val(hvs_menu_obj.buslines['line_'+busline].direction);
		} else {
			$("input[name='Direction']").val(1);
		}
	});

	// ========= START OF THE TREIN CODE =======
	$("input[name='trein_select_start']").change(function () {
		if ($("input[name='trein_select_start']").val() === '') {
			resetForm();
		}
	});

	$("input[name='trein_select_start']").autocomplete('hvs_startPoint.php', {
		minChars: 3,
		limit: 20,
		matchCase: true,
		extraParams: {
			scenario: function () {
				return getModality();
			}
		},
		formatItem: function (row) {
			var item = eval("(" + row + ")");
			return item.name;
		}
	})
	.result(function (event, item) {
		var modality = getModality();
		item = eval("(" + item + ")");
		$("input[name='" + modality + "_select_start']").val(item.name);
		$("input[name='" + modality + "_start_id']").val(item.stops);
		$("input[name='" + modality + "_select_end']").val('');
		$("input[name='" + modality + "_end_id']").val('');
		$("div#" + modality + "_endpoint_container").show();

		// (re-)activate the autocomplete
		setTreinEndPointAutoselect();

		$("input[name='" + modality + "_select_end']").focus();
	});

	return true;
} // end startSearch

/**
 * Activates (or reactivates) the autocomplete on the bus endpoint
 * @return true;
 */
function setBusEndPointAutoselect() {
	$("input[name='bus_select_end']").autocomplete('hvs_endPoint.php', {
		minChars: 0,
		max: 0,
		matchCase: true,
		extraParams: {
			scenario: function () {
				return getModality();
			},
			startPoint: function () {
				return $("input[name='bus_start_id']").val();
			},
			lineId: function () {
				return $("select[name='bus_select_line']").val();
			},
			dateRange: function () {
				dateRange = $("input[name='bus_select_start']").val(); 
				dateRange = dateRange.replace(hvs_menu_obj.rPlace, "$2");
				return dateRange;
			},
			dateRange2: function () {
				dateRange = $("select[name='bus_select_line'] :selected").text(); 
				dateRange = dateRange.replace(hvs_menu_obj.rPlace, "$2");
				return dateRange;
			},
			place: function() {
				place = $("input[name='bus_select_start']").val(); 
				place = place.replace(hvs_menu_obj.rPlace, "$1");
				return place;
			}
		},
		formatItem: function (row) {
			var item = eval("(" + row + ")");
			return item.name;
		}
	})
	.result(function (event, item) {

		item = eval("(" + item + ")");
		// example singel: {"name":"Handel, Pastoor Castelijnsstraat","stops":"5994","lines":"311:2"}
		// example multiple: {"name":"Nistelrode, Weverstraat","stops":"3930","lines":"329:2,338:2"}

		$("input[name='bus_select_end']").val(item.name);
		$("input[name='bus_end_id']").val(item.stops);
		$('#bus_line_container, #showinfo, #showtable').show();

//		loadBusSelect(item.lines);
	})
	.bind(($.browser.opera ? "keypress" : "keyup"), function(event) {
		if ($(this).val() == '') {
			loadAllStartBusLines();
		}
	})
	;

	loadAllStartBusLines();
	return true;
}

function loadAllStartBusLines() {
	return;

	$.post('hvs_busLines.php',
			{
				'limit':0,
				'scenario': 'bus',
				'startPoint': $("input[name='bus_start_id']").val(),
				'version': 2
			},
			function (data) {
				for (i in data) {
					item = data[i];
					if (typeof(item) == 'object' && item.name == '') {
						loadBusSelect(item.lines);
					}
				}
			},
			'json'
	);
}

function loadBusSelect(lines, keepHidden)
{
	var longlines = lines.split(',');
	var lineparts;
	var shortlines = [];

	keepHidden = false || keepHidden;

	for (var i=0; i < longlines.length; i++) {
		lineparts = longlines[i].split(':');
		hvs_menu_obj.buslines['line_' + lineparts[0]] = {
				lineID: lineparts[0],
				direction: lineparts[1]
		};
		shortlines.push(lineparts[0]);
	}

	// the next line loads a html snippet with option tags!!!
	$("select[name='bus_select_line']").load('hvs_stopLines.php',
			{
				LineIDs: shortlines.join(','),
				dateRange: function () {
					dateRange = $("input[name='bus_select_start']").val(); 
					dateRange = dateRange.replace(hvs_menu_obj.rPlace, "$2");
					return dateRange;
				}
	}, function () {
		$('#showinfo, #showtable').hide();

		if (typeof(showHtmlSubmitButton) !== 'undefined' && showHtmlSubmitButton === true && !keepHidden) {
			$("#showinfo, #showtable").show();
		}

		//  Beware, the first option is empty
		$("select[name='bus_select_line'] option:first").html('Kies een lijn');

		if ($("select[name='bus_select_line'] option").length  ===  2) {
			$("select[name='bus_select_line'] option:first").remove();
			$("input[name='bus_line']").val($("select[name='bus_select_line']").val());
			$("input[name='Direction']").val(lineparts[1]);
		}
		else {
			$("input[name='bus_line']").val('');
		}

		$("input[name='bus_select_end']").focus().change(function () {
			$("input[name='submitbutton']").focus();
		});
	})
	.change(function() {
		$('input[name="bus_select_end"]').val('').flushCache();
		$('#bus_line_container, #showinfo, #showtable').show();
		});
}

/**
 * Activates (or reactivates) the autocomplete on the trein endpoint
 * @return true;
 */
function setTreinEndPointAutoselect() {
	$("input[name='trein_select_end']").autocomplete('hvs_endPoint.php', {
		minChars: 0,
		max: 0,
		matchCase: true,
		extraParams: {
			scenario: function () {
				return getModality();
			},
			startPoint: function () {
				return $("input[name='trein_start_id']").val();
			},
			lineId: function () {
				return '';
			}
		},
		formatItem: function (row) {
			var item = eval("(" + row + ")");
			return item.name;
		}
	})
	.result(function (event, item) {

		if (typeof(showHtmlSubmitButton) !== 'undefined' && showHtmlSubmitButton === true) {
			$("#showinfo, #showtable").show();
		}
		item = eval("(" + item + ")");
		// example: {"name":"Groningen","stops":"6291","lineIDs":"110,111"}

		$("input[name='trein_select_end']").val(item.name);
		$("input[name='trein_end_id']").val(item.stops);
		$("input[name='trein_lines']").val(item.lines);
		$("input[name='submitbutton']").focus();
	});
	return true;
}

/**
 * Gets the value of the modality dropdown
 * @return string the modality or ''
 */
function getModality() {
	return $("select[name='modality']").val();
}

/**
 * resets the form
 * @return true;
 */
function resetForm() {
	var modality = getModality();
	selectModality();
	if (modality !== '') {
		$("form#hvsform input[name='" + modality + "_select_start']").val('');
		$("form#hvsform input[name='" + modality + "_select_end']").val('');
		$("form#hvsform input[name='" + modality + "_end_id']").val('');
		$("form#hvsform div#" + modality + "_endpoint_container").hide();
		$("form#hvsform div#" + modality + "_line_container").hide();
	}
	$("form#hvsform input[name='bus_line'] option").val('');
	$("form#hvsform input[name='trein_lines'] option").val('');
	$("form#hvsform #bus_line_container").hide();
	$("form#hvsform select[name='bus_select_line'] option").remove();
	$("form#hvsform .hvsform-submit, form#hvsform #submitbutton, #showinfo, #showtable").hide();
	// $(this).focus();
	return true;
}

/**
 * shows the blocks that go with the active modality (bus|trein)
 * @return true;
 */
function selectModality() {
	var modality = getModality();
	$('#modality_select_bus, #modality_select_trein').hide();
	if (modality === 'bus' || modality === 'trein') {
		$('#modality_select_' + modality).show();
	}

	if (modality == 'bus') {
		$('#trein_select_start, #trein_select_end').val('');
	}

	if (modality == 'trein') {
		$('#bus_select_start, #bus_select_line, #bus_select_end').val('');
	}

	return true;
}

/**
 * Checks if the form is ready to be submitted
 * @return bool formValid
 */
function submittable() {
	var modality = $("select[name='modality']").val();
	if (modality !== 'bus' && modality !== 'trein') { return false; }
	if ($("input[name='" + modality + "_start_id']").val() === '') { return false; }
	if (modality !== 'bus' && $("input[name='" + modality + "_end_id']").val() === '') { return false; }
	if (modality === 'bus' && $("input[name='bus_line']").val() === '') { return false; }
//	if (modality === 'bus' && $("input[name='bus_select_end']").val() === '') { return false; }
	if (modality === 'trein' && $("input[name='trein_lines']").val() === '') { return false; }
	return true;
}


