$(document).ready(function() {
	//get url values for autocomplete url
	var url1 = $('#url1').val();
	var url2 = $('#url2').val();
	var url3 = $('#url3').val();

    $("#autocompleteBuildingTitle").autocomplete({

    	//.autocomplete does not have any error handling, so we wrap a regular ajax request, which does have error handling, in the source
        source: function( request, response ) {
			$.ajax({
				url: "api/buildings.json?URL1=" + url1 + "&URL2=" + url2 + "&URL3=" + url3,
				data: {
					term: request.term
				},
				success: function( data ) {
					//ensure the response is json
					data = $.parseJSON(data); //why i have to do this, i don't know +1 for MooTools
					if(typeof data == 'object') {
						response( $.map( data, function( item ) {
							return {
								label: item.label,
								value: item.label,
								id: item.id
							}
						}));
					} else {
						handleError('An error occurred');
					}
				},
				timeout: 5000,
                error:function($xhr, $error){
                    if($xhr.status == 0) {
                        $report_text = 'You are offline!! Please check your network.';
                    }else if($xhr.status == 404){
                        $report_text = 'Requested URL not found.';
                    }else if($xhr.status == 500){
                        $report_text = 'Internal server error.';
                    }else if($error == 'parsererror'){
                        $report_text = 'Error. Parsing JSON request failed.';
                    }else if($error == 'timeout'){
                        $report_text = 'Request timed out.';
                    }else {
                        $report_text = 'An unknown error has occured. '+$xhr.responseText;
                    }
                    // Display message
                    if($report_text != '') {
                    	handleError($report_text);
                    }
                }
			});
		},
        minLength: 2,
        open: function(event, ui) {

        },
        select: function(event, ui) {
          $("#autocompleteBuildingId").val(ui.item.id);
        }

    });
});

/**
 * stop the loading indicator and display the error message to the user
 * @param $errorMessage
 */
function handleError($errorMessage) {
	//hide indicator
	$('#autocompleteBuildingTitle').removeClass('ui-autocomplete-loading');

	//display message to user
	$('#content').prepend('<div class="warn2">' + $errorMessage + '</div>');
}

/**
 * test if the string is valid json or not
 * it could be an error message
 * @param string
 * @returns {Boolean}
 */
function isJSON(string) {
	try {
	   jQuery.parseJSON(string);
	} catch(e) {
	    return false;
	}
	return true;

}
$("#change a").click(function(e){
	e.preventDefault();
	document.location.href = 'logout.html?really=yes';
	return false;
});



