var servlet_url;
var locale;
var vehicleDefaultOption;
var productClassDefaultOption;
var brandDefaultOption;
var regionDefaultOption;

function initDealerLocator(servleturl) {
	servlet_url = servleturl;
	locale = $('#lang').val();
	
	$('input.text_overlayed').css('display', 'none');

	vehicleDefaultOption = $('#vtype > option:eq(0)').html();
	productClassDefaultOption = $('#ptype > option:eq(0)').html();
	brandDefaultOption = $('#brand > option:eq(0)').html();
	regionDefaultOption = $('#region > option:eq(0)').html();

	$('inputdiv.mandatory:parent .ismandatory').css('visibility', 'visible');
	// $('input.mandatory.text_overlayed').after('<span
	// class="ismandatory">*</span>');
	setTwoInARow(5);
	// alert(vehicleDefaultOption);

	$('input.text_overlayed').select(onTextFieldSelect);
	$('input.text_overlayed').focus(onTextFieldSelect);
	$('input.text_overlayed').click(onTextFieldSelect);

	$('input.text_overlayed').blur(onTextFieldDeSelect);
	$('.typetextoverlay').focus(onOverlaySelect);
	$('.typetextoverlay').click(onOverlaySelect);

	$('#submit').click(checkSubmit);

	// $('input.text_overlayed').live('focusout', onTextFieldDeSelect);
	// debugSelector('input.text_overlayed');

	$('#vtype')
			.load(
					servlet_url,
					{
						locale : locale,
						get : "vtype"
					},
					function(rt, ts, xr) {
						if (ts == "success") {
							vdefault = $('#vtypedefault').val();
							$('#vtype').removeAttr('disabled');
							if (vdefault == "") {
								$('#vtype > option:eq(0)')
										.before(
												'<option name="default" value="none">' + vehicleDefaultOption + '</option>');
								selectOption('#vtype', 'none');
							} else {
								selectOption('#vtype', vdefault);
								onSelectVehicle();
							}
							$('#vtype').change(onSelectVehicle);
							checkMandatorySelects();
						} else {
							// alert(ts + ": " + rt);
						}

					});
	$('#region')
			.load(
					servlet_url,
					{
						locale : locale,
						get : "region"
					},
					function(rt, ts, xr) {
						if (ts == "success") {
							vdefault = $('#regiondefault').val();
							if ($('#region > option').length > 0) {
								$('#region').removeAttr('disabled');
								if (vdefault == "") {
									$('#region > option:eq(0)')
											.before(
													'<option name="default" value="none">' + regionDefaultOption + '</option>');
									selectOption('#region', 'none');
								} else {
									selectOption('#region', regiondefault);
								}
								$('#region').show();
								$('#region').parent().show();
							} else {
								$('#region').hide();
								$('#region').parent().hide();
							}
							$('#region').change(onSelectVehicle);
						} else {
							// alert(ts + ": " + rt);
						}

					});

	/** ********************************************************************************** */
}
function setTwoInARow(threshold) {
	if ($('#locationSelection .inputdiv:not(.hidden)').length >= threshold) {
		$('#locationSelection').addClass('twoinarow');
	} else {
		$('#locationSelection').removeClass('twoinarow');
	}
}
function onSelectVehicle() {
	var vehicleID = $('#vtype > option:selected').attr("value");
	var productID = $('#ptype > option:selected').attr("value");
	if (vehicleID != "none") {
		$('#ptype')
				.load(
						servlet_url,
						{
							locale : locale,
							vtype : vehicleID,
							get : "ptype"
						},
						function(rt, ts, xr) {
							if (ts == "success") {
								$('#ptype').removeAttr('disabled');
								pdefault = $('#ptypedefault').val();
								if (pdefault == "") {
									if (productClassDefaultOption != null) {
										$('#ptype > option:eq(0)')
												.before(
														'<option name="default" value="none">' + productClassDefaultOption + '</option>');
										if ((productID != 'none')
												&& (productID != 'null'))
											selectOption('#ptype', productID);
										else
											selectOption('#ptype', 'none');
									}
								} else {
									selectOption('#ptype', pdefault);
								}
								$('#ptype').change(onSelectProductClass);

								checkMandatorySelects();
							} else {
								alert(ts + ": " + rt);
							}
						})
		if (!$('#brand').hasClass('hidden')) {
			$('#brand')
					.load(
							servlet_url,
							{
								locale : locale,
								vtype : vehicleID,
								get : "brand"
							},
							function(rt, ts, xr) {
								if (ts == "success") {
									/*
									 * IE 6 needs it to execute the following
									 * code asynchronous, or it will not repaint
									 * the form ...
									 */
									window
											.setTimeout(
													function() {
														if ($('#brand > option').length > 0) {
															$('#brand')
																	.removeAttr(
																			'disabled');
															$('#brand').show();
															$('#brand')
																	.parent()
																	.show();
															if (brandDefaultOption != null) {
																$(
																		'#brand> option:eq(0)')
																		.before(
																				'<option name="default" value="none">' + brandDefaultOption + '</option>');
																selectOption(
																		'#brand',
																		'none');
															}
															$('#brand')
																	.change(
																			onSelectProductClass);
														} else {
															$('#brand')
																	.append(
																			'<option name="default" value="none">' + brandDefaultOption + '</option>');
															$('#brand').attr(
																	'disabled',
																	'disabled');
															// $('#brand').hide();
															// $('#brand').parent().hide();
														}
														checkMandatorySelects();
													}, 250);
								} else {
									alert(ts + ": " + rt);
								}
							})
		}
	} else {
		$('#ptype').attr('disabled', 'disable');
		$('#brand').attr('disabled', 'disable');
		checkMandatorySelects();
	}
}

function debug(text) {
	$('#debug').append(text);
}

function debugln(text) {
	debug(text);
	debug("<br />");
}

function debugSelector(selector) {
	debug('<h4>Selector "' + selector + '" matches the following elements:</h2>');
	$(selector).each(
			function() {
				debugln("&lt;" + $(this).context.nodeName + " #"
						+ $(this).context.id + " /&gt;");
			});
	debugln('<i>*** end of selector ***</i>');
}

function checkMandatorySelects() {
	var ok = true;
	$('select.mandatory').each(
			function() {
				debug($(this).context.name + " is mandatory ");
				if (($(this).attr('disabled') == "disabled")
						|| ($(this).attr('disabled') == true)) {
					ok = false;
					debug('disabled ');
				} else {
					if ($(this).val() == "none") {
						ok = false;
						// $(this).addClass("invalid");
						debug("none selected, disabled == "
								+ $(this).attr('disabled'));
					}
				}
				debugln('---');
			});
	if (ok) {
		$('#zip').removeAttr('readonly').removeClass('readonly');
		$('#city').removeAttr('readonly').removeClass('readonly');
		$('#street').removeAttr('readonly').removeClass('readonly');
		$('#zip_overlay').removeAttr('readonly').removeClass('readonly');
		$('#city_overlay').removeAttr('readonly').removeClass('readonly');
		$('#street_overlay').removeAttr('readonly').removeClass('readonly');

		return true;
	} else {
		/*
		 * $('#zip').attr('readonly', 'readonly').addClass('readonly');
		 * $('#city').attr('readonly', 'readonly').addClass('readonly');
		 * $('#street').attr('readonly', 'readonly').addClass('readonly');
		 * $('#zip_overlay').attr('readonly', 'readonly').addClass('readonly');
		 * $('#city_overlay').attr('readonly', 'readonly').addClass('readonly');
		 * $('#street_overlay').attr('readonly',
		 * 'readonly').addClass('readonly');
		 */
		return false;
	}
}

function checkMandatory() {
	if (checkMandatorySelects()) {

	}
}
function onSelectProductClass() {
	var productID = $('#ptype > option:selected').attr("value");
	checkMandatorySelects();
}

function onTextFieldSelect() {
	var id = $(this).context.id;
	$('#' + id + '_overlay').hide();
	$('#' + id).show();
	debug("selected " + id + "<br />");
}
function onTextFieldDeSelect() {
	debug('deselected field!<br />');
	var id = $(this).context.id;
	if ($(this).val() == "") {
		$('#' + id).hide();
		$('#' + id + '_overlay').show();
	}
	debug("deselected " + id + "<br />");
}
function onOverlaySelect() {
	var id = $(this).context.id;
	id = id.split('_')[0];
	$('#' + id).focus();
}

function checkSubmit() {
	isValid = true;
	$('select.mandatory').each(function() {
		if ('disabled' != $(this).attr('disabled')) {
			if (($(this).val() == "none") || ($(this).val() == "")) {
				$(this).parent().addClass('invalid');
				isValid = false;
			} else {
				$(this).parent().removeClass('invalid');
			}
		}
	});
	$('input.text_overlayed.mandatory').each(function() {
		var id = $(this).context.id;
		if ($(this).val() == "") {
			$(this).addClass("invalid");
			debugln('invalid text field:' + id);
			$('#' + id + '_overlay').addClass("invalid");
			isValid = false;
		} else {
			$(this).removeClass("invalid");
			$('#' + id + '_overlay').removeClass("invalid");
		}
	});
	if (!isValid) {
		$('#errortext').show();
	} else {
		$('#errortext').hide();
		var v = {
			get : 'search',
			locale : locale,
			vtype : $('#vtype').val(),
			ptype : $('#ptype').val()
		};
		getParam(v, 'brand');
		getParam(v, 'zip');
		getParam(v, 'city');
		getParam(v, 'street');

		$.ajax( {
			url : servlet_url + '?get=search',
			data : v,
			dataType : 'text',
			success : function(rData) {
				showSearchResult(rData);
			}
		});

	}
	return false;
}
function showSearchResult(responseData) {
	// alert(responseData);
	window.open(responseData, "_blank");
}

function getParam(data, elemId) {
	var val = $('#' + elemId).val();
	if (val == "")
		return;
	if (val == "none")
		return;

	data[elemId] = val;
}

function selectOption(selectid, optvalue) {
	window.setTimeout(function() {
		$(selectid).val(optvalue);
	}, 5);
}
