// list of xml nodes describing the locations
var locationList = null;
var locationCount = null;
var useSuggest = false;
var enterOverwrite = false;

// Zeigt die gegebene Fehlermeldung an --%>
function showLocationError(message) {
    jQuery("#locationErrorSpan").show();
    jQuery("#locationErrorSpan").text(message);
   }

// Behandelt den Fall, dass keine PLZ/Ort-Kombination gefunden wurde --%>
function showNoLocationFoundError() {
    showLocationError("Der eingegebene Ort wurde nicht gefunden. Bitte überprüfen Sie Ihre Eingabe.");
}

// Entfernt die Fehlermeldung --%>
function hideLocationError() {
    jQuery("#locationErrorSpan").hide();
}

// zeigt die Auswahlbox mit den auf die Suchanfrage passenden PLZ/Ort-Kombinationen an --%>
function showLocationDropDown() {
	var selectElement = document.getElementById("locationDropDown");
    selectElement.options.length = 0;
    var index=0;
    var optionEmpty = new Option("----- Bitte wählen -----", "");
    if (jQuery.browser.msie) {
        selectElement.add(optionEmpty);
    } else {
        selectElement.add(optionEmpty, null);
    }
    for(index=0; index<locationCount; index++) {
        var location = locationList[index];
        var zip = location.attr("zip");
        var city = location.text();
        var option = new Option(zip + " " + city, index);
        if (jQuery.browser.msie) {
           selectElement.add(option);
        } else {
           selectElement.add(option, null);
        }
    }
	$(selectElement).show();
}

// versteckt die Auswahlbox mit den auf die Suchanfrage passenden PLZ/Ort-Kombinationen --%>
function hideLocationDropDown() {
	//alert("hide location dropdown");
    jQuery("#locationDropDownDiv").hide();
}

// kopiert den indizierten Ort aus dem DropDown in das Eingabefeld --%>
function copyLocationFromDropdown(selectElement) {
    var index = selectElement.value;
    if (index!="") {
        // ort wurde ausgewählt
        var location = locationList[index];
        var zip = location.attr("zip");
        var city = location.text();
        jQuery("#zipCity").val(zip + " " + city);
        //alert("Auswahl: " + zip + " " + city);
    }
}

// behandelt die Auswahl des Auswahl-DropDowns --%>
function handleLocationDropDown() {
    var selectElement = document.getElementById("locationDropDown");
    copyLocationFromDropdown(selectElement);
    hideLocationDropDown();
    submitZipCity();
}

// Schreibt die gegebene PLZ/Ort-Kombination in die Session und lädt die Seite neu oder springt auf die Ausstiegsseite --%>
function jumpToLocation(zip, city) {
//	alert("jumpToLocation(" + zip + ", " + city + ")");
    jQuery.ajax({
        type: "GET",
        url: "/region?method=updateSession&section=P&zip="+zip+"&city="+escape(city),
        data: "",
        dataType: "xml",
        success: function(xml){
    	if (top.location.href.indexOf("geschaeftskunde")>-1) {
    		top.location.href="geschaeftskunde-ortseingabe.html";
    	} else {
    		top.location.href="privatkunde-ortseingabe.html";
    	}
        }
    });
}

// handle form submit --%>
function submitZipCity() {
    //alert("submitZipCity");
    if (useSuggest) {
    	enterOverwrite = true;
		return false;
    }

    hideLocationError();
    $("#productOrderBoxForm .wrap").css("background-image","url('/sc/img/ajax-loader_smale.gif')");
    var search = jQuery("#productOrderBoxForm input").val();
    if (search.match(/^ *$/)) {
       showLocationError("Bitte geben Sie eine Postleitzahl oder einen Ort an.");
    } else {


    	// Methode "getLocations()" aufrufen --%>
        jQuery.ajax({
            type: "GET",
            url: "/region?method=getLocations&section=P&search="+escape(search),
            data: "",
            dataType: "xml",
            success: function(xml){
        	   //alert("callback handler");

            // alle gefundenen PLZ/Ort-Kombinationen in Array schreiben --%>
                //This function will loop for each match on addresses/address
                locationCount = 0;
                locationList = new Array();
                jQuery("LocationList Location", xml).each(function(){
                    var location = $(this);
                    locationList[locationCount] = location;
                    var zip = location.attr("zip");
                    var city = location.text();
                    //alert("zip = " + zip + ", city = " + city);
                    locationCount++;
                });
                $("#productOrderBoxForm .wrap").css("background-image","none");

		/*
		
		Je nach Anzahl der gefundenen PLZ/Ort-Kombinationen:
		0: Fehlermeldung anzeigen
		1: PLZ und Ort speichern, eventuell auf Ausstiegsseite springen, ansonsten Tarifansicht freigeben
		>1: DropDown mit Auswahlmöglichkeit anzeigen
		
		*/
                if (locationCount==0) {
                    showNoLocationFoundError();
                    hideLocationDropDown();
                } else if (locationCount==1) {
                    hideLocationDropDown();
                    var location = locationList[0];
                    //alert("location = " + location);
                    var zip = location.attr("zip");
                    var city = location.text();
                    jumpToLocation(zip, city);
                } else {
                    showLocationDropDown();
                }


            }
        });   
    }
    return false;
}


// Vorschlagsliste - Script nachladen
$(document).ready(function() {
	hideLocationDropDown();
	$.getScript('/sc/js/jquery.suggest.js', function(){
		useSuggest = true;
		$("#zipCity").suggest("/region?method=getLocations&section=P&search=",{
			//onSelect: function() {$("#locationDropDown").hide();},
			minchars: 5,
			delay: 0
		});
	});
});
