var servlet_url;
var locale;
var vehicleDefaultOption;
var productClassDefaultOption;
var brandDefaultOption;
var regionDefaultOption;
var subsegmentDefaultOption;
var brandLoading = false;
var subsegmentLoading = false;
var ptypeLoading = false;


function initDealerLocator(servleturl) {
	servlet_url = servleturl;
	locale = $('#lang').val();
	locale = locale.substring(0,3) + locale.substring(3,5).toUpperCase();

	vehicleDefaultOption = $('#vtype > option:eq(0)').html();
	productClassDefaultOption = $('#ptype > option:eq(0)').html();
	brandDefaultOption = $('#brand > option:eq(0)').html();
	regionDefaultOption = $('#region > option:eq(0)').html();
	subsegmentDefaultOption = $('#subsegment > 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');
	initPrimarySelects();
}
function initPrimarySelects() {
	/*languagesSelect = $('#languages').val();*/
	languagesSelect = locale.split("-")[0];
	if (!$('#languages').hasClass('hidden')) {
		$('#languages').load(servlet_url, {
			locale : locale,
			countrygroup : $('#countrygroup').val(),
			get : "languages"
		}, function(rt, ts, xr) {
			$('#languages').change(onSelectLanguage);
			selectOption('#languages', languagesSelect);
		});
	}
	$('#subsegment').empty().append('<option name="default" value="none">' + subsegmentDefaultOption + '</option>');
	$('#brand').empty().append('<option name="default" value="none">' + brandDefaultOption + '</option>');
	$('#region').empty().append('<option name="default" value="none">' + regionDefaultOption + '</option>');
	$('#ptype').empty().append('<option name="default" value="none">' + productClassDefaultOption + '</option>');

	$('#groupcountries').attr('disabled', 'disabled');
	$('#vtype').attr('disabled', 'disabled');
	$('#ptype').attr('disabled', 'disabled');
	$('#region').attr('disabled', 'disabled');
	$('#brand').attr('disabled', 'disabled');
	$('#subsegment').attr('disabled', 'disabled');

	initSecondarySelects();
}

function initSecondarySelects() {
	groupcountry = $('#groupcountries').val();
	if (!groupcountry) {
		groupcountry = locale.split("-")[0];
	}
	if (!$('#groupcountries').hasClass('hidden')) {
		$('#groupcountries').load(servlet_url, {
			locale : locale,
			countrygroup : $('#countrygroup').val(),
			get : "groupcountries"
		}, function(rt, ts, xr) {
			if ($('#groupcountries > option').length >= 2) {
				$('#groupcountries').removeAttr('disabled');
				$('#groupcountries').show();
				$('#groupcountries').parent().show();
				$('#groupcountries').change(onSelectCountry);
				selectOption('#groupcountries', groupcountry);
			}
		});
	}
	initTertiarySelects();
}
function initTertiarySelects() {
	brandLoading = false;
	subsegmentLoading = false;
	ptypeLoading = false;
	$('#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(function() {
				onSelectVehicle(false);
			});
			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();
				$('#region').parent().parent().removeClass('temporary_hidden');
			} else {
				$('#region').hide();
				$('#region').parent().hide();
				$('#region').parent().parent().addClass('temporary_hidden');
			}
		} else {
			// alert(ts + ": " + rt);
		}

	});

	/** ********************************************************************************** */
}
function setTwoInARow(threshold) {
	if ($('#locationSelection .inputdiv:not(.hidden)').length >= threshold) {
		$('#locationSelection').addClass('twoinarow');
	} else {
		$('#locationSelection').removeClass('twoinarow');
	}
}
function onSelectLanguage() {
	groupcountry = locale.split("-")[1];
	locale = $('#languages').val() + "-" + groupcountry;

	initPrimarySelects(locale);
}
function onSelectCountry() {
	language = locale.split("-")[0];
	locale = language + "-" + $('#groupcountries').val();
	// alert(locale);

	initPrimarySelects(locale);
}
function onSelectVehicle(subsegmentSelection) {
	var vehicleIsSubSegment = false;
	var vehicleID = $('#vtype > option:selected').attr("value");
	var subsegment = $('#subsegment > option:selected').attr("value");
	if (subsegmentSelection && subsegment && (subsegment != "") && (subsegment != "none")) {
		if (!$('#subsegment').hasClass('hidden')) {
			vehicleID = subsegment;
			vehicleIsSubSegment = true;
		}
	}
	var productID = $('#ptype > option:selected').attr("value");
	if (vehicleID != "none") {
		if (!ptypeLoading) {
			ptypeLoading = true;
			$('#ptype').empty();
			$('#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>');
								/*
								bug: don't select previous selection, always select none
								if ((productID != 'none') && (productID != 'null'))
									selectOption('#ptype', productID);
								else
								*/
									selectOption('#ptype', 'none');
							}
						} else {
							selectOption('#ptype', pdefault);
						}
						$('#ptype').change(onSelectProductClass);
						if ($('#ptype > option').length < 1) {
							$('#ptype').attr('disabled', 'disabled');
							$('#ptype').empty().append('<option name="default" value="none">' + productClassDefaultOption + '</option>');
							;
						}
						checkMandatorySelects();
					} else {
						alert(ts + ": " + rt);
					}
					ptypeLoading = false;
				}
			);
		}
	}
	// subsegment is reloaded only if vehicle (segment) selection changed!
	if (!vehicleIsSubSegment && vehicleID != "none") {
		if (!$('#subsegment').hasClass('hidden') && (vehicleID != "none") && !subsegmentLoading) {
			subsegmentLoading = true;
			$('#subsegment').empty().load(
					servlet_url,
					{
						locale : locale,
						vtype : vehicleID,
						get : "subsegment"
					},
					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 ($('#subsegment > option').length > 0) {
									$('#subsegment').removeAttr('disabled');
									$('#subsegment').show();
									$('#subsegment').parent().show();
									$('#subsegment').parent().parent().removeClass('temporary_hidden');
									if (subsegmentDefaultOption != null) {
										$('#subsegment> option:eq(0)').before(
												'<option name="default" value="none">' + subsegmentDefaultOption + '</option>');
										selectOption('#subsegment', 'none');
									}
									$('#brand').hide();
									$('#brand').parent().hide();
									$('#brand').parent().parent().addClass('temporary_hidden');
									$('#subsegment').change(function() {
										onSelectVehicle(true);
									});
								} else {
									$('#subsegment').attr('disabled', 'disabled');
									$('#subsegment').hide();
									$('#subsegment').parent().hide();
									$('#subsegment').parent().parent().addClass('temporary_hidden');
									initBrands(vehicleID);
								}
								checkMandatorySelects();
								subsegmentLoading = false;
							}, 250);
						} else {
							alert(ts + ": " + rt);
						}
					});
		} else {
			initBrands(vehicleID);
		}
	} else {
		$('#ptype').attr('disabled', 'disabled');
		$('#brand').attr('disabled', 'disabled');
		if (!vehicleIsSubSegment)
			initBrands(vehicleID);
		checkMandatorySelects();
	}
}

function initBrands(vehicleID) {
	if (!$('#brand').hasClass('hidden') && (vehicleID != "none") && !brandLoading) {
		brandLoading = true;
		$('#brand').empty().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();
						$('#brand').parent().parent().removeClass('temporary_hidden');
						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();
						$('#brand').parent().parent().addClass('temporary_hidden');
					}
					checkMandatorySelects();
					brandLoading = false;
				}, 250);
			} else {
				alert(ts + ": " + rt);
			}
		});
	}

}
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).parent().parent().hasClass("temporary_hidden")) {
			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')) && !$(this).is(':hidden')) {
			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,
			ptype : $('#ptype').val()
		};

		var vehicleID = $('#vtype').val();
		if (!$('#subsegment').is(':hidden') && !$('#subsegment').hasClass('hidden'))
			vehicleID = $('#subsegment').val();
		else
			getParam(v, 'brand');

		v['vtype'] = vehicleID;
		getParam(v, 'zip');
		getParam(v, 'city');
		getParam(v, 'street');
		getParam(v, 'region');

		
		/*webkit fix*/
		var popUpSuccess = false;
		var popUpUrl;
		
		$.ajax( {
			url : servlet_url + '?get=search',
			data : v,
			async: false,/*webkit fix*/
			dataType : 'text',
			success : function(rData) {
				/*webkit fix*/
				popUpSuccess = true;
				popUpUrl = rData;
				//showSearchResult(rData);
			}
		});
		
		/*webkit fix*/
		if(popUpSuccess) {
			showSearchResult(popUpUrl);
			popUpSuccess = false;
		}
	}
	return false;
}
function showSearchResult(responseData) {
	// alert(responseData);
	window.open(responseData + "&ind=WB", "_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);
}

