var map = null;
var geocoder = null;
var currentPageDisplay = 1;
var lastPage = 10;
var pageSize = 8;
var baseIcon = null;
var referencePoint = null;
var referenceMarker = null;
var searchResults = [];
var currentPage = 1;


$(document).ready(pageLoad);
function pageLoad(){
	map = new GMap2($("#map_canvas").get(0));
	if (GBrowserIsCompatible()) {
        map.setCenter(new GLatLng(31.696685,-99.322921), 5);
        var mapControl = new GLargeMapControl();
        map.addControl(mapControl);

    }	
	geocoder = new GClientGeocoder();
	attacheEventHandlers();
	var options = { 
	    target:     '#contactForm', 
	    url:        'contactCourt.php', 
	    success:    function() { 
			alert('Thanks for your comment!'); 
		}
	}
 
	$("#contactForm").ajaxForm(options);
	$("div#contactCourt").dialog({autoOpen:false, height: "560",width:"500", modal:true,overlay:{background:"gray",opacity:0.5}});

	//$.ui.dialog({autoOpen:false, modal:true, position:'center'});
	// Create a base icon for all of our markers that specifies the
        // shadow, icon dimensions, etc.
        baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(20, 34);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
	$("#zipcode").select();
}
function attacheEventHandlers(){
	// $("#searchButton").bind("click", function(){
		// getLocationCoords();
	// })
	$("#searchButton").get(0).onclick = hideSearchArea;
	$("#nextPage").get(0).onclick = nextPage;
	$("#previousPage").get(0).onclick = previousPage;
	$(".searchResults").hide();
	$("#searchAgainButton").bind('click', function(){
		$("#searchAddress").hide();
		$("#searchAgainButton").hide();
		$("#searchButton").show();
		$("#searchAreaBody").show(500);
		$(".searchResults").hide();
		$(".searchResultPageControls").hide();
		$("#zipcode").select();
		if ($("#searchAreaBody #address").val().length > 0 || $("#searchAreaBody #zipcode").val().lentgh > 0){
			if ($("#zipcode").val().lentgh > 0){
				$("#zipcode").select();
			}
			else {
				$("#address").select();
			}
		}
		else {
			$("#zipcode").select();
		}
	});
	$("#zipcode").bind('keypress', function(){
		$("#messageArea").fadeOut(500);	
		$("#searchAreaBody #address").val("");
		$("#searchAreaBody #city").val("");
	});
	$("#searchAreaBody #address").bind('keypress', function(){
		$("#messageArea").fadeOut(500);	
		$("#searchAreaBody #zipcode").val("");
	});	
	$("#searchAreaBody #city").bind('keypress', function(){
		$("#messageArea").fadeOut(500);	
		$("#searchAreaBody #zipcode").val("");
	});
	$(document.body).bind('keypress', function(event){
		if (event.keyCode == 13 && $("#searchAreaBody").css("display") == 'block'){
			$("#searchButton").click();
		}
	});
	
	$("#contactCancel").bind('click', function(){
		closeCourtContact();
	});
	$("#contactSend").bind('click', function(){
		sendContactForm();
	});
}
function nextPage(event){
	//if (currentPage < lastPage){
		if ($("div.searchResultList div.searchResult").length == pageSize){
			currentPage += 1;
			getSearchResults(referencePoint)
			$("#nextPage").attr("disabled", false);
		}
		else {
			$("#nextPage").attr("disabled", true);
		}
		if (currentPage == 1){
			$("#previousPage").attr("disabled", true);	
		}
		else {
			$("#previousPage").attr("disabled", false);
		}		
	//}
}
function previousPage(event){
	if (currentPage > 1){
		currentPage -= 1;
		getSearchResults(referencePoint)
	}
	if ($("div.searchResultList div.searchResult").length == pageSize){
		$("#nextPage").attr("disabled", false);
	}
	else {
		$("#nextPage").attr("disabled", true);
	}
	if (currentPage == 1){
		$("#previousPage").attr("disabled", true);	
	}
	else {
		$("#previousPage").attr("disabled", false);
	}
}
function hideSearchArea(){
	// $("#searchButton").hide();
	// $("#searchAgainButton").show();	
	// $("#searchAddress").show();
		// $("#searchAreaBody").hide(500, getLocationCoords);

	// getLocationCoords();
	
	var zipcode = $("#zipcode").val();
	var streetAddress = $("#address").val();
	var city = $("#city").val();
	var state = "Texas";
	
	var isZipCodeSearch = zipcode.length == 5 ? true : false;
	var isAddressSearch = streetAddress.length > 0 && city.length > 0 ? true : false;
	var address = "";
	if (isZipCodeSearch){
		address = state+" "+zipcode;
	}
	else if (isAddressSearch){
		address = streetAddress +", "+ city +", "+ state;
	}
	var addressStatus = ValidateAddress(zipcode, streetAddress, city, isZipCodeSearch);
	if (addressStatus.isValid){
		$("#searchAreaBody").hide(500);
		$("#searchButton").hide();
		$("#searchAgainButton").show();	
		if (isZipCodeSearch) address = address.replace("Texas ","");
		$("#searchAddress").text(address);
		$("#searchAddress").show();
		
		// $("#searchAreaBody").hide(500, getLocationCoords);

		// getLocationCoords();
	
		geocoder.getLatLng(address, displayReferenceLocation);
	}
	else {
		$("#messageArea").html(addressStatus.message);
		$("#messageArea").fadeIn(100);
		$("#searchAgainButton").click();
	}
	return false;
	

}
function getLocationCoords(){

	var zipcode = $("#zipcode").val();
	var streetAddress = $("#address").val();
	var city = $("#city").val();
	var state = "Texas";
	
	var isZipCodeSearch = zipcode.length == 5 ? true : false;
	var isAddressSearch = streetAddress.length > 0 && city.length > 0 ? true : false;
	var address = "";
	if (isZipCodeSearch){
		address = state+" "+zipcode;
	}
	else if (isAddressSearch){
		address = streetAddress +", "+ city +", "+ state +", US";
	}
	var addressStatus = ValidateAddress(zipcode, streetAddress, city);
	if (addressStatus.isValid){
		$("#searchAreaBody").hide(500);
		geocoder.getLocations(address, displayReferenceLocation);
	}
	else {
		$("#messageArea").html(addressStatus.message);
		$("#messageArea").fadeIn(100);
		$("#searchAgainButton").click();
	}
	return false;
}

function ValidateAddress(zipcode, streetAddress, city){
	var status ={ isValid: true, message: ""};
	if (zipcode.length == 0 && (streetAddress.length == 0 && city.length == 0)){
		status.message += "<div>Please enter a zipcode or an address and city.</div>";
		status.isValid = false;
	}	
	else if (zipcode.length > 0){
		if (zipcode.length != 5){
			status.message += "<div>Zip code should have 5 digits.</div>";
			status.isValid = false;
		}
	}
	else {
		if (streetAddress.length == 0){
			status.message += "<div>The address is not valid.</div>";
			status.isValid = false;
		}
		if (city.length == 0){
			status.message += "<div>The city is not valid.</div>";
			status.isValid = false;
		}
	}
	return status;
}

function displayReferenceLocation(point){
	if (point == null){
		displayLocationNotFound();
		return;		
	}
	// if (referencePoint!= null && point.y != referencePoint.lng() && point.x != referencePoint.lat()){
		// map.removeOverlay(referenceMarker);
	// }
	// map.setCenter(point, 10);
	referencePoint = new GLatLng(point.y, point.x);
	referenceMarker = new GMarker(referencePoint);
	// map.addOverlay(referenceMarker);
	getSearchResults(referencePoint);

}
function getSearchResults(latlng){
	$("#searchResultArea").show();
	$(".searchResults").show();
	$(".searchResultPageControls").show();
	var queryParams = {};
	queryParams.latitude = latlng.lat();
	queryParams.longitude = latlng.lng();
	queryParams.page = currentPage;
	queryParams.pageSize = pageSize;
	$.get("courtSearch.php", queryParams, function(data){
	
		for(var i= 0; i <searchResults.length; i++){
			map.removeOverlay(searchResults[i].Marker);
		}
		searchResults = data;
	
		var resultList = $("#resultList").get(0);
		while (resultList.hasChildNodes()){
			resultList.removeChild(resultList.firstChild);
		}
		for(var i = 0; i < data.length; i++){
			// var searchResult = document.createElement("div");
			var searchResult = $('<div></div>');
			searchResult.addClass("searchResult");
			searchResult.attr("id","searchResult"+new String(i));
			searchResult.attr("itemNumber", i);
			// searchResult.setAttribute("class", "searchResult");
			// searchResult.setAttribute("id", "searchResult"+new String(i));
			// searchResult.setAttribute("itemNumber", i);
			
			// var markerArea = document.createElement("div");
			var markerArea = $('<div></div>');
			var marker = $('<img />');
			marker.attr("src", getMarkerIconImagePath(i));
			marker.attr("class", "markerArea");
			markerArea.append(marker);
			
			// marker.setAttribute("src", getMarkerIconImagePath(i));
			// markerArea.setAttribute("class", "markerArea");
			// markerArea.appendChild(marker);
			
			// var rowContainer = document.createElement("div");
			// rowContainer.setAttribute("class", "rowContainer");
			// var row1 = document.createElement("div");
			// row1.setAttribute("class", "resultRow");
			
			
			// var courtName = document.createElement("div");
			// courtName.setAttribute("class", "courtName");
			// $(courtName).text(data[i].CourtName);
			
			var courtName = $('<div></div>');
			courtName.addClass("courtName");
			courtName.text(data[i].CourtName);
			
			// var courtLabel = document.createElement("div");
			// courtLabel.setAttribute("class", "courtLabel");
			// $(courtLabel).text("Court: ");

			var courtLabel = $('<div></div>');
			courtLabel.addClass("courtLabel");
			courtLabel.text("Court: ");

			// var courtNumber = document.createElement("div");
			// courtNumber.setAttribute("class", "courtNumber");
			// $(courtNumber).text(data[i].CourtNumber);

			var courtNumber = $('<div></div>');
			courtNumber.addClass("courtNumber");
			courtNumber.text(data[i].CourtNumber);

			
			// var distance = document.createElement("div");
			// distance.setAttribute("class", "distance");
			// $(distance).text(data[i].Distance);

			var distance = $('<div></div>');
			distance.addClass("distance");
			distance.text(data[i].Distance);

			
			// searchResult.appendChild(markerArea);
			// row1.appendChild(courtName);
			// row1.appendChild(courtLabel);
			// row1.appendChild(courtNumber);
			// row1.appendChild(distance);
			
			var row1 = $('<div></div>');
			row1.addClass("resultRow");
			

			searchResult.append(markerArea);
			row1.append(courtName);
			row1.append(courtLabel);
			row1.append(courtNumber);
			row1.append(distance);
			
			var row2 = document.createElement("div");
			row2.setAttribute("class", "resultRow");
			
			var row2 =  $('<div></div>');
			row2.addClass("resultRow");
			
			// var address = document.createElement("div");
			// address.setAttribute("class", "address");
			var address =  $('<div></div>');
			address.addClass("address");

			if (data[i].StreetAddress.length > 0 ){
				address.text(data[i].StreetAddress);
			}
			else{
				address.html("&nbsp;");
			}

			var contactLinkArea =  $('<div></div>');
			var contactLink =  $('<a></a>');
			contactLink.attr("href", "#");
			contactLink.attr("resultNumber", i);
			contactLink.addClass("contactLink");
			contactLink.text("Contact this court");
			contactLinkArea.append(contactLink);
			var resultNumber = new Number(i);
			contactLink.bind('click', function(event){
				var resultNumber = $(this).attr("resultNumber");
				contactCourt(resultNumber); 
				return false;
			});
			
			
			// row2.appendChild(address);
			
			// rowContainer.appendChild(row1);
			// rowContainer.appendChild(row2);
			// searchResult.appendChild(rowContainer);
			
			row2.append(address);
			row2.append(contactLinkArea);

			var rowContainer = $('<div></div>');
			rowContainer.addClass("rowContainer");
			
			rowContainer.append(row1);
			rowContainer.append(row2);
			searchResult.append(rowContainer);
			
			// $("#resultList").get(0).appendChild(searchResult);
			$("#resultList").append(searchResult);

		
			// var latlng = new GLatLng(data[i].Latitude, data[i].Longitude);
			// var referencePoint = new GMarker(latlng);
			// map.addOverlay(referencePoint);
			// var marker = createMarker(latlng, i, data[i]);
			// map.addOverlay(marker);
			// searchResults[i].Marker = marker;
			// searchResults[i].MarkerContent = "<div><b>"+data[i].CourtName+"</b></div><div>"+data[i].StreetAddress+"</div><div>"+data[i].City+", Texas</div><div><a href='#' onclick='contactCourt("+i+"); return false;'>Contact this court</a></div>";
			$("#searchResult"+i).bind("click", function(event){
				var searchResultItem = $(event.target).find("searchResult").get(0);
				if (!searchResultItem){
					searchResultItem = $(event.target);
				}
				while($(searchResultItem).attr("class") != "searchResult"){
					searchResultItem = $(searchResultItem).parent().get(0);
				}
				var itemNumber = searchResultItem.getAttribute("itemNumber");
				var marker = searchResults[itemNumber].Marker;
				//marker.openInfoWindowHtml(searchResults[itemNumber].MarkerContent);

				var tab1 = new GInfoWindowTab("Court", searchResults[itemNumber].MarkerContent);
				var tab2 = new GInfoWindowTab("Meetings", searchResults[itemNumber].MarkerContent2);
				var tabs = [];
				tabs[0] = tab1;
				tabs[1] = tab2;
				marker.openInfoWindowTabsHtml(tabs);
			});
		}	
		$("#currentPageDisplay").text(currentPage);
		if ($("div.searchResultList div.searchResult").length == pageSize){
			$("#nextPage").attr("disabled", false);
		}
		else {
			$("#nextPage").attr("disabled", true);
		}

		resizeMap();
	},"json");

}

function resizeMap(){

	if (currentPage == 1){
		map.setCenter(referencePoint, 10);
	}
	else {
		map.setCenter(referencePoint, 8);
	}

	if (referenceMarker){
		map.removeOverlay(referenceMarker);	
	}
	referenceMarker = new GMarker(referencePoint);
	map.addOverlay(referenceMarker);

	// alert("search results count:"+searchResults.length);
	for(var i= 0; i <searchResults.length; i++){
// alert(i);
// alert(searchResults[i].Latitude+","+searchResults[i].Longitude);
			var latlng = new GLatLng(searchResults[i].Latitude, searchResults[i].Longitude);
			// alert("latlng created:"+latlng.lat()+","+latlng.lng());
			var marker = createMarker(latlng, i, searchResults[i]);
			searchResults[i].Marker = marker;
			searchResults[i].MarkerContent = "<div><b>"+searchResults[i].CourtName+"</b></div><div>"+searchResults[i].StreetAddress+"</div><div>"+searchResults[i].City+", Texas</div><div><a href='#' onclick='contactCourt("+i+"); return false;'>Contact this court</a></div>";			
			searchResults[i].MarkerContent2 = "<div>Place:"+searchResults[i].MeetingPlace+"</div><div>Time:"+searchResults[i].MeetingTime+"</div><div>Day:"+searchResults[i].MeetingDay+"</div><div>"+searchResults[i].Notes+"</div>";			

			// alert("marker created");
			map.addOverlay(marker);
	}
	
}
function getMarkerIconImagePath(characterNumber){
	var letter = String.fromCharCode("A".charCodeAt(0) + characterNumber);
	var imagePath = "http://www.google.com/mapfiles/marker" + letter + ".png";
	return imagePath;
}

function createMarker(point, index, court) {
	// Create a lettered icon for this point using our icon class
	var letter = String.fromCharCode("A".charCodeAt(0) + index);
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

	// Set up our GMarkerOptions object
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);
	marker.resultIndex = index;

	GEvent.addListener(marker, "click", function() {
		var tab1 = new GInfoWindowTab("Court", searchResults[marker.resultIndex].MarkerContent);
		var tab2 = new GInfoWindowTab("Meetings", searchResults[marker.resultIndex].MarkerContent2);
		var tabs = [];
		tabs[0] = tab1;
		tabs[1] = tab2;
		marker.openInfoWindowTabsHtml(tabs);		
		//marker.openInfoWindowHtml(searchResults[marker.resultIndex].MarkerContent);
		//marker.openInfoWindowHtml("<div><b>"+court.CourtName+"</b></div><div>"+court.StreetAddress+"</div><div>"+court.City+", Texas</div><div><a href='#' onclick='contactCourt("+index+"); return false;'>Contact this court</a></div>");
	});
	return marker;
}

function contactCourt(resultNumber){
	var court = searchResults[resultNumber];
	//$("div#contactCourt").css({position:"absolute",top:"50px",left:"50px"}).show();
	$("div#contactCourt").dialog({height: "660",width:"500", modal:true,overlay:{background:"gray",opacity:0.5}});
	$("div#contactCourt").dialog("open");
	
	$("#contactCourt .courtInfo #courtName").text(court.CourtName);
	$("#contactCourt .courtInfo #courtNumber").text(court.CourtNumber);
	$("#contactCourt .courtInfo #courtAddress").text(court.StreetAddress);
	$("#courtOfInterest").val(court.CourtNumber);
	$("#courtOfInterestName").val(court.CourtName);
}

function closeCourtContact(){
	$("#contactCourt").dialog("close");
	
	$("#contactCourt .courtInfo #courtName").text("");
	$("#contactCourt .courtInfo #courtNumber").text("");
	$("#contactCourt .courtInfo #courtAddress").text("");
}

function sendContactForm(){
	var querystring = $("#contactForm").formSerialize();
	$.post('contactCourt.php', querystring, function(data){
		ShowDialog(data.message);	
	}, "json");
	closeCourtContact();

}

function contactFormSent(data){
	var d = eval(data);
	var success = d.success;
	var message = d.message;
	ShowDialog(message);
}

function ShowDialog(message){
	alert(message);
}

function displayLocationNotFound(){
	$("#messageArea").text("The address was not found.");
	$("#messageArea").fadeIn(100);

	$("#searchAgainButton").click();
}
