    var latitudeOutput = "";
    var longitudeOutput = "";


    // TODO: get the userid perhaps from a cookie
    now = new Date();
    userId = now.getTime();
    requestId = 0;
    // the level from which upward to log
    // 1 .. debug, 2 .. info, 3 .. warn, 4 .. error, 5 .. fatal
    // Use debug only if really debugging as a lot of logging requests
    // will be made
    loglevel = 1;

    // ################################
    // Allgemeine Functions

    // Sends a log message to the server, if the configured level of the
    // logger is not higher than the level provided.
    // The level has to be either debug, info, warn, error or fatal.
    // Optionally a logger name may be provided if the log message is to
    // be logged into a special location. Otherwise the logger logs to the
    // default client server log.
    function clientServerLog(message, level, logger) {
        var levelAsInt = 0;
        if (level == 'debug') {
            levelAsInt = 1;
        }
        if (level == 'info') {
            levelAsInt = 2;
        }
        if (level == 'warn') {
            levelAsInt = 3;
        }
        if (level == 'error') {
            levelAsInt = 4;
        }
        if (level == 'fatal') {
            levelAsInt = 5;
        }
        if (loglevel > levelAsInt) {
            return;
        }

        requestId++;
        dojo.xhrPost({
            url: 'clientlogging.html',
            timeout: 1000,
            handleAs: "json",
            content: {
                message: message,
                logger: logger,
                level: level,
                userId: userId,
                requestId: requestId
            }
        });
    }

    // This method is to be called for sending asynchronuous requests to the
	// server
    // The method will also provide the logging for the request being sent.
    // In the provided callback methods logging has to be implemented however.
    // The request object parameter is the same object, expected by
	// dojo.xhrPost()
    // --> see http://api.dojotoolkit.org/jsdoc/1.3.2/dojo.__XhrArgs
    function sendPostRequest(requestObject) {
        var message = 'Sending request to ' + requestObject['url'];
        try {
            try {
                if (requestObject['load'] != null) {
                    message = message + ' - Callback: ' + requestObject['load'].name;
                }
                if (requestObject['error'] != null) {
                    message = message + ' - ErrorCallback: ' + requestObject['error'].name;
                }
            } catch (error) {
                // do nothing
            }
            message = message + ' - Parameter: ' + serializeParameterList(requestObject['content']);
            clientServerLog(message, 'debug', null);
        } catch (error) {
            // do nothing
        }
        var result = dojo.xhrPost(requestObject);
        return result;
    }


    // Serializes the provided hashmap into a single string
    function serializeParameterList(aMap) {
        var result = "";
        for (key in aMap) {
            result = result + key + " - " + aMap[key] + "; ";
        }
        return result;
    }

    function defaultHandleErrorMessage(response, ioArgs){
        var msg = "";
        if (response.Error == 1){
            msg = "Eingabe-Fehler:\n";
            for (var i = 0; i < response.ErrorMessages.length; i++){
                msg = msg + response.ErrorMessages[i] + "\n";
            }
            // alert(msg);
        } else {
           // alert("An error occurred: " + response.ErrorMessage);
        }
        clientServerLog('defaultHandleErrorMessage called with: ' + serializeParameterList(response), 'warn', null);
    }


       // Load Dojo's code relating to the Button widget
       dojo.require("dojo.parser");
       dojo.require("dijit.form.Button");
       dojo.require("dijit.Dialog");
       dojo.require("dijit.form.TextBox");
       dojo.require("dijit.form.TimeTextBox");
       dojo.require("dijit.form.Button");
       dojo.require("dijit.form.DateTextBox");
       dojo.require("dijit.form.ComboBox");
       dojo.require("dijit.form.ValidationTextBox");
       dojo.require("dijit.form.Form");
       dojo.require("dijit.form.DateTextBox");
       dojo.require("dijit.ProgressBar");

        dojo.addOnLoad(function(){
        console.debug("submit");
        var myForm = dijit.byId("myFormTwo");
        dojo.connect(myForm, "onSubmit", function(e){
            e.preventDefault();
            if (myForm.isValid()){

                console.debug("valid");
                registerFormSubmit();
                dijit.byId('registerFormTankstelle').hide();
            }
          });
        });

    function getNewTankstellenFilterResultSubmit(searchType){
        var params = new Array();
        params['dispatcherAction'] = 'getTankstellenResultJSON';
        params['searchType'] = searchType;
        params['searchQuery'] = document.getElementById('tankstellensearch').value;
        params['searchQueryProfi'] = document.getElementById('profiSearch').value;
        params['searchOrgTyp'] = document.getElementById('profiOrgTyp').value;
        params['searchSteckerType'] = document.getElementById('profiSteckerType').value;
        params['searchOeffnungszeitenType'] = document.getElementById('profiOeffnungszeitenType').value;
        params['searchKostenTyp'] = document.getElementById('profiKostenTyp').value;
        params['searchRadius'] = document.getElementById('profiRadius').value;
        params['searchZugang'] = document.getElementById('profiZugang').value;
        params['searchTsTyp'] = document.getElementById('profiTyp').value;
        params['searchGeeignet'] = document.getElementById('profiGeeignet').value;
        params['searchSteckerVolt'] = document.getElementById('profiSteckerVolt').value;
        params['searchSteckerAmpere'] = document.getElementById('profiSteckerAmpere').value;
        
        
        
        var deferred = sendPostRequest({
           url: 'Elektrotankstellen.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: handleNewTankstellenResult,
           error: defaultHandleErrorMessage,
           sync: false
        });
        return false;
    }

    function handleNewTankstellenResult(response, ioArgs){

        clientServerLog('Callback handleNewTankstellenResult called', 'debug', null);
        try {
            // code to show a multiple address response instead of a list of
			// results
            if (response.multipleAddresses != null) {
            document.getElementById("multipleHandler").style.display="none";
                var tankstellenFilterOutput = dojo.byId("tankstellenFilterOutput");
                tankstellenFilterOutput.innerHTML = response.multipleAddresses;
                
                // if search box minimized open it after specified time so users can see the multiple address list
                window.setTimeout("if (searchResultBoxClosed == 1) { searchboxResultsOpen(); }", 2000);
                
                max_resultspages = 1;
                resultsPaging(1);
                return;
            }else{
            	document.getElementById("multipleHandler").style.display="block";
            }

            var tankstellenFilterOutput = dojo.byId("tankstellenFilterOutput");
            tankstellenFilterOutput.innerHTML = response.tankstellenFilter;

            var tankstellenFilterSummeOutput = dojo.byId("tankstellenFilterSummeOutput");
            tankstellenFilterSummeOutput.innerHTML = response.tankstellenFilterSumme;


            // reset all the markers of the last search back to default
            var resetIds = markers.Get(-1);
            if (resetIds != null) {
                // call reset code
                for (i = 0; i < resetIds.length; i++) {
                    // mark status in the marker array
                    var tmpMarker = markers.Get(resetIds[i]);
                    tmpMarker[2] = 'default';
                    // update overlay color back to default
                    gmarkers[resetIds[i]].setImage("templates/images/etf_map_icon.png");
                }
            }
            var bounds = new GLatLngBounds();
            for (i = 0; i < response.tankstellenIds.length; i++) {
                // mark the changed status in the marker array
                var tmpMarker = markers.Get(response.tankstellenIds[i]);
                tmpMarker[2] = 'highlighted';
                // update overlay color to new value
                gmarkers[response.tankstellenIds[i]].setImage("templates/images/etf_map_icon_orange.png");
                bounds.extend(tmpMarker[0]);
            }
            var zoom = map.getBoundsZoomLevel(bounds) - 1;
            if (zoom > 15) {
                zoom = 15;
            }

			// if there are results update the map, otherwise do not change the
			// currently displayed map in any way.
			if (response.tankstellenIds != "") {
	            map.setZoom(zoom);
	            map.setCenter(bounds.getCenter());
	            markers.Set(-1, response.tankstellenIds);
	        }

            max_resultspages = Math.ceil(response.tankstellenIds.length / 10);
            resultsPaging(1);
        } catch (error) {
            clientServerLog('Exception in handleNewTankstellenResult: ' + error.message, 'error', null);
        }

    }
    
   function getCoordinatesFromRegisterForm(){
        var params = new Array();
        params['dispatcherAction'] = 'getCoordinatesFromRegisterFormJSON';
        try {
            params['mainPageForm.tankstelle.address.land'] = document.getElementById('ts_land').value;
            if (params['mainPageForm.tankstelle.address.land'].substring(1) == 'sterreich') {
                params['mainPageForm.tankstelle.address.land'] = 'Austria';
            }

            params['mainPageForm.tankstelle.address.ort'] = document.getElementById('ts_ort').value;
            params['mainPageForm.tankstelle.address.strasse'] = document.getElementById('ts_strasse').value;
            params['mainPageForm.tankstelle.address.hausNummer'] = document.getElementById('ts_hausnummer').value;
            params['mainPageForm.tankstelle.address.plz'] = document.getElementById('ts_plz').value;

        } catch (error) {
            clientServerLog('Exception in getCoordinatesFromRegisterForm: ' + error.message, 'error', null);
        }

        var deferred = sendPostRequest({
           url: 'Register.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: handleCoordinatesJSONResultRegistration,
           error: defaultHandleErrorMessage
        });
    }

   function getPageByIdSubmit(pageId){
        var params = new Array();
        params['dispatcherAction'] = 'getPageByPageIdJSON';
        params['pageId'] = pageId;

        var deferred = sendPostRequest({
           url: 'Elektrotankstellen.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: handlePageByIdResult,
           error: defaultHandleErrorMessage
        });
        return false;
    }

    function handlePageByIdResult(response, ioArgs){
        clientServerLog('Callback handlePageByIdResult called', 'debug', null);
        try {
            var pageByIdOutput = dojo.byId("pageByIdOutput");
            pageByIdOutput.innerHTML = response.pageByIdContent;
        } catch (error) {
            clientServerLog('Exception in handleNewTankstellenResult: ' + error.message, 'error', null);
        }
    }

    function handleCoordinatesJSONResultRegistration(response, ioArgs){
        clientServerLog('Callback handleCoordinatesJSONResultRegistration called', 'debug', null);
        try {


            longitudeOutput.innerHTML = response.longitudeContent;
            latitudeOutput.innerHTML = response.latitudeContent;
            
            document.getElementById('latHidden').value = response.latitudeContent;
            document.getElementById('lonHidden').value = response.longitudeContent;

            // default div for displaying the verification map
            var regmapdiv = "mapRegDiv1";

            // if multiple probable addresses were found
            if (response.status == 'found many') {
                    regmapdiv = "mapRegDiv2";
                    document.getElementById("mapRegDiv2_addr").innerHTML = response.addresses;
                    document.getElementById("mapRegDiv1").style.display="none";
                    document.getElementById("mapRegDiv2_addr").style.display="block";
                    document.getElementById("mapRegDiv2").style.display="block";
            }

            // update regmap initial lat/lang javascript variables
            if ((document.getElementById("longitude").value != "") && (document.getElementById("latitude").value != "")) {
                lat = document.getElementById("latitude").value;
                lon = document.getElementById("longitude").value;
            } else {
                lat = response.latitudeContent;
                lon = response.longitudeContent;
            }

            // update lat/lng hidden fields. This will be the final lat/lng
			// stored in the DB.
            document.getElementById("usermaplat").value=lat;
            document.getElementById("usermaplng").value=lon;


            // initialize user verification map
            initializeRegMap(regmapdiv);
        } catch (error) {
            clientServerLog('Exception in handleCoordinatesJSONResultRegistration: ' + error.message, 'error', null);
        }
    }

   function getTopNews(){
        var params = new Array();
        params['dispatcherAction'] = 'getTopNewsJSON';

        var deferred = sendPostRequest({
           url: 'Elektrotankstellen.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: handleTopNewsResult,
           error: defaultHandleErrorMessage
        });
        return false;
    }

   function validateCaptchaRegistration(jCaptchaResponse){
   	
        var params = new Array();
        params['dispatcherAction'] = 'validateCaptchaRegistrationJSON';
        params['jCaptchaResponse'] = jCaptchaResponse;

        var deferred = sendPostRequest({
           url: 'Register.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: handleCaptchaResultRegistration,
           error: defaultHandleErrorMessage,
           sync: true
        });
    }

   function validateCaptchaContact(jCaptchaResponse){
        var params = new Array();
        params['dispatcherAction'] = 'validateCaptchaContactJSON';
        params['jCaptchaResponse'] = jCaptchaResponse;

        var deferred = sendPostRequest({
           url: 'Elektrotankstellen.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: handleCaptchaResultContact,
           error: defaultHandleErrorMessage,
           sync: true
        });
    }

    function handleTopNewsResult(response, ioArgs){
        try {
            clientServerLog('Callback handleTopNewsResult called', 'debug', null);
            var topNewsOutput = dojo.byId("topNewsOutput");
            topNewsOutput.innerHTML = response.topNewsContent;
        } catch (error) {
            clientServerLog('Exception in handleTopNewsResult: ' + error.message, 'error', null);
        }
    }

    function handleCaptchaResultRegistration(response, ioArgs){
        try {
            clientServerLog('Callback handleCaptchaResultRegistration called', 'debug', null);
            var captchaOutputRegistration = dojo.byId("mainPageForm.tankstelle.captchaOutput");
            captchaOutputRegistration.innerHTML = response.captchaContentRegistration;
            if ($("#captchaResultRegistration").val() != 'true') {
                onLoad();
            }
        } catch (error) {
            clientServerLog('Exception in handleCaptchaResultRegistration: ' + error.message, 'error', null);
        }
    }

    
     function validateRegisterFormField(fieldKey, value, field){
    	//alert(fieldKey + "|" + value + "|" + field);
    	var params = new Array();  
        params['dispatcherAction'] = 'validateRegisterFormFieldJSON';
        params[fieldKey] = value;
        params['registerForm.fieldToVaildate'] = field;
        //params['registerForm.landValue'] = land;
        //params['registerForm.fieldToVaildate'] = tsLandValue;

		var resp;
		
        var deferred = sendPostRequest({
           url: 'Register.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: function (response, ioArgs){      
        	if(response.userEmailCheck!=null){
        	  userEmailValidationManager(response.userEmailCheck);
        	}
			resp = response;
		         },
           error: defaultHandleErrorMessage,
           sync: true
        });

        return resp;
    }
     function userEmailValidationManager(status){
      	//alert("if user do not exist return 0 - if exist but user double_opt_in is false return 1 - if exist and user double_opt_in is true return 2");
      	// alert(status);

     	 if (status == 0) {
     		 hideshow('absendenButton','show');
     		 hideshow('useremailstatusOutput','hide');
     	 }
     	 
     	 if ((status == 1) || (status == 2)) {
     		 hideshow('absendenButton','hide');
     		 var useremailstatusOutput = dojo.byId("useremailstatusOutput");
     		 if (status == 1) {
     			 hideshow('useremailstatusOutput','show');
     			 
     			 useremailstatusOutput.innerHTML = "Sie haben sich bereits angemeldet. Bitte best&auml;tigen Sie die Anmeldung mit dem Link den Sie per E-Mail erhalten haben. <a href='Register.html?dispatcherAction=requestAccountVerification&email="+document.getElementById('email').value+"'>E-Mail nochmals versenden</a>";
     		 }
     		 if (status == 2) {
     			 hideshow('useremailstatusOutput','show');
     			 useremailstatusOutput.innerHTML = "Mit dieser E-Mail Adresse wurde bereits ein User registriert.";
     		 }
     	 }
      }

    function handleCaptchaResultContact(response, ioArgs){
        try {
            clientServerLog('Callback handleCaptchaResultContact called', 'debug', null);
            var captchaOutputContact = dojo.byId("contact.captchaOutput");
            captchaOutputContact.innerHTML = response.captchaContentContact;
            if ($("#captchaResultContact").val() != 'true') {
                onLoad();
            }
        } catch (error) {
            clientServerLog('Exception in handleCaptchaResultContact: ' + error.message, 'error', null);
        }
    }

    /**
     * New Url: no Query params, only hash params with searchTerm and page.
     * @param searchTerm the searchTerm
     * @param page the page, starting with 0
     * @return
     */
    function triggerSearchBySearchTerm(searchTerm, page) {
    	document.location = $.param.fragment($.param.querystring(document.location.href,"",2),"#page=" + page + "&searchTerm=" + searchTerm,2);
    }

    /**
     * New Url: no Query params, no hash params.
     * @return
     */
    function triggerDeleteNewsFilter(){
    	document.location = $.param.fragment($.param.querystring(document.location.href,"",2),"",2);
    }

    /**
     * Tell the browser to jump to the beginning of the page using document.location.hash='#sitestart';
     * @return
     */
    function jumpToSiteStart() {
    	document.location.hash='#sitestart';
    }
    
    function getTankstellenMapSubmit(firstResult) {
        var params = new Array();
        params['dispatcherAction'] = 'getTankstellenMapJSON';
        params['firstResult'] = firstResult;
        
        var deferred = sendPostRequest({
           url: 'Elektrotankstellen.html',
           timeout: 30000,
           handleAs: 'json',
           content: params,
           load: handleTankstellenMap,
           error: defaultHandleErrorMessage,
           sync: false
        });
        return false;
    }

    /**
     * adds the list of tankstellen to the map
     */
    function handleTankstellenMap(response, ioArgs) {
    	var tankstellen = response.tankstellen;
    	for ( var i = 0; i < tankstellen.length; i++) {
			var tankstelle = tankstellen[i];
			var lMarker = new GLatLng(parseFloat(tankstelle.lat), parseFloat(tankstelle.long));
			var lContent = '<div style="width:350px;">' +
	    		'<a target="_top" href="Details.html?tankstellen-id=' + tankstelle.tankstellenId + '" rel="nofollow">' +
	    		'<img src="' + tankstelle.mainImageUrl + '" align="right" width="100" vspace="10" hspace="10" />' +
	    		'</a><strong>' + tankstelle.name + '</strong><br />' +
	    		tankstelle.address1 + '<br />' +
	    		tankstelle.address2 + '<br />' +
	    		tankstelle.tel + '<br />' +
	    		'<a href="' + tankstelle.link + '" target="_blank" rel="nofollow"></a><br />' +
	    		'&Ouml;ffnungszeiten: ' + tankstelle.opening + '<br /><br />' +
	    		tankstelle.comment + '<br /><br />' +
	    		'<a href="javascript:void(0);" onclick="javascript:showTsDetailPage(' + tankstelle.tankstellenId + 
	    		')" target="_top" rel="nofollow">mehr Infos &raquo;</a>' +
	    		'<br />' +
	    		'</div>';
			
			markers.Set(tankstelle.tankstellenId, Array(lMarker, lContent));
			map.addOverlay(create_gmarker(tankstelle.tankstellenId, lMarker, lContent, markerOptions));
		}
    	
    	var textElement = document.getElementById('progress_indicator_text');
    	if (response.hasMoreResults == true) {
    		var completed = Math.round((response.nextResult / response.itemCount) * 100);
    		textElement.innerHTML = 'Lade Tankstellen: ' + completed + '%';
/*    		jsProgress.update({
                maximum: response.itemCount,
                progress: response.nextResult
            }); */
    		
    		getTankstellenMapSubmit(response.nextResult);
    		
    	} else {
/*    		jsProgress.update({
                maximum: response.itemCount,
                progress: response.itemCount
            }); */	
    		textElement.innerHTML = 'Lade Tankstellen: 100%';
    		hideshow('progress_indicator_text', 'hide');
    		hideshow('progress_indicator', 'hide');


		// read saved search phrase cookie
		if (document.location.href.indexOf("search=") != -1) { 
			// if URL includes search parameter start search
			setPreviousSearch(unescape(getURLParam('search')));
		} else {
			if (readCookie("searchphrase") != null) { if (readCookie("searchphrase") != "") {
				// if cookie contains searchphrase set that searchphrase again and submit search 
				// setPreviousSearch(readCookie("searchphrase"));
			} }
		}


    	}
    }

