// PubQuest

function PQ(){}

PQ.SetPubID = function(id)
{
    PQ.PubID = id;
};

PQ.Init = function()
{
    //alert("PQ.Init - id = >" + PQ.PubID + "<");

    $(window).resize(function(){
      PQ.ResizeMap();
    });

	PQ.MapWidth = 400;
	PQ.NarrowMapWidth = 400;
	PQ.MapInfoWidth = 300;
	PQ.DistanceInfoWidth = 200;
	PQ.LeftInfoWidth = PQ.DistanceInfoWidth;
	PQ.CrntInfo = "";
	PQ.LeftInfoVisible = true;
	PQ.ListsVisible = false;
	PQ.DistanceInfoVisible = true;
	$("#lstCountry").attr("selectedIndex", 0);
	//$("#accordion").accordion({ autoHeight: false });

    PQ.ResizeMap();
	GM.Init();
	
	//setTimeout("PQ.HideInfo()", 10000);
    
    // Bind CR to address box (when you press carriage return it checks the address)
    $("#txtAddress").bind("keyup", function(e) { if (e.keyCode == 13) {PQ.ProcessAddress(); } } );
};

PQ.SetPubListIdx = function(pubKey, show)
{
    var pubIdx = -1;
	for (var idx = 0; idx < GM.Pubs.length; idx++)
	{
	    if (GM.Pubs[idx].key == pubKey)
		{
		    pubIdx = idx + 1; // idx 0 is select a brewery so add 1
			break;
		} 
	}
    document.getElementById("lstPub").selectedIndex = pubIdx;
	//alert("PQ.SetPubListIdx = " + pubKey + ", " + pubIdx + ", show = " + show + ", " + GM.Pubs[pubIdx].name);
	if (show) GM.DisplayInfo();
};

PQ.ToggleDistanceInfo = function()
{
    PQ.LeftInfoWidth = PQ.DistanceInfoWidth;
	PQ.NarrowMapWidth = PQ.MapWidth - PQ.LeftInfoWidth
    if (PQ.DistanceInfoVisible)
	{
	    $("#distance-info").hide();
	    $("#map").css("width", PQ.MapWidth);
		PQ.LeftInfoVisible = false;
		GM.Map.checkResize();
		$("#pubContainer a span").html("Show Distance List");
	} else {
	    $("#map-info").hide();
	    $("#distance-info").show();
	    $("#map").css("width", (PQ.NarrowMapWidth));
		PQ.LeftInfoVisible = true;
		$("#pubContainer a span").html("Hide Distance List");
	}
	PQ.DistanceInfoVisible = !PQ.DistanceInfoVisible;
};

PQ.ShowMapInfo = function(show)
{
    if (PQ.DistanceInfoVisible) PQ.ToggleDistanceInfo();

    PQ.LeftInfoWidth = PQ.MapInfoWidth;
	PQ.NarrowMapWidth = PQ.MapWidth - PQ.LeftInfoWidth
    if (show)
	{
	    $("#distance-info").hide();
	    $("#map-info").show();
	    $("#map").css("width", PQ.NarrowMapWidth);
		PQ.LeftInfoVisible = true;
	} else {
	    $("#map-info").hide();
	    $("#map").css("width", PQ.MapWidth);
		PQ.LeftInfoVisible = false;
		GM.DirectionsPolyline = null;
		GM.Map.checkResize();
	}
};

PQ.ShowInfo = function(info)
{
	if (PQ.CrntInfo == "#" + info) return;
	
	if (PQ.CrntInfo != "") $(PQ.CrntInfo).hide();
	
	PQ.CrntInfo = "#" + info;
	$(PQ.CrntInfo).slideDown("normal");
	//$(PQ.CrntInfo).show("drop", {}, 500);
};
PQ.HideInfo = function()
{
    //$(PQ.CrntInfo).slideUp("slow");
	$(PQ.CrntInfo).hide("drop", {}, 500);
	PQ.CrntInfo = "";
};

PQ.ShowListContainer= function()
{
	//alert("PQ.ShowListContainer = " + $("#list-button a span").text() );
	if (PQ.ListsVisible)
	{
		$("#list-button a span").text("Search by list");
		$("#list-container").hide();
		PQ.ListsVisible = false;
	}else{
		$("#list-button a span").text("Hide search lists");
		$("#list-container").show();
		PQ.ListsVisible = true;
	}
}; 

PQ.ProcessCountry = function()
{
	//alert("PQ.ProcessCountry=" + $("#lstCountry").val() );
	
	var vals = $("#lstCountry").val().split(",");
	
	GM.Map.clearOverlays();

	GM.CenterMap(vals[2], vals[1], parseInt(vals[3]));

	if (vals[0] == "ALL")
	{
    	$("#stateContainer").hide();
    	$("#cityContainer").hide();
    	$("#pubContainer").hide();
	}else{
    	$.ajax(
    	{
    		type: "GET",
    		url: "includes/location.asp",
    		data: "data=state&country=" + vals[0],
    		dataType: "html",
    		error: PQ.AjaxError,
    		success: PQ.LoadStates
    	});
	}
};
PQ.LoadStates = function(data, status)
{
	$("#stateContainer").html(data);
	$("#stateContainer").show();
	$("#cityContainer").hide();
	$("#pubContainer").hide();
};

PQ.ProcessState = function()
{
	//alert("PQ.ProcessState=" + $("#lstState").val() );
	var vals = $("#lstState").val().split(",");

	GM.Map.clearOverlays();

	$.ajax(
	{
		type: "GET",
		url: "includes/location.asp",
		data: "data=city&state=" + vals[0],
		dataType: "html",
		error: PQ.AjaxError,
		success: PQ.LoadCities
	});
	
	GM.CenterMap(vals[2], vals[1], parseInt(vals[3]));
};
PQ.LoadCities = function(data, status)
{
	$("#cityContainer").html(data);
	$("#cityContainer").show();
	$("#pubContainer").hide();
};

PQ.ProcessCity = function()
{
	//alert("PQ.ProcessCity=" + $("#lstCity").val() );
	var vals = $("#lstCity").val().split(",");
	
	if ($("#lstCity").attr("selectedIndex") == 0)
	{
    	$("#cityContainer").hide();
    	$("#pubContainer").hide();
	}
	
	GM.Map.clearOverlays();
	GM.PrevZoom = 0;

	GM.CenterMap(vals[2], vals[1], parseInt(vals[3]));
};

PQ.BreweryChanged = function(e)
{
    //alert("PQ.BreweryChanged");
	$("#brewery-error").hide();
	$("#brewery-list-container").hide();
	$("#addr-list-container").hide();
	if ($("#txtBrewery").val().length < 3)
	{
		$("#brewery-button").hide();
	}else{
		$("#brewery-button").show();
		if (e.keyCode == 13) PQ.GetBrewery();
	}
};

PQ.GetBrewery = function()
{
    var name = $("#txtBrewery").val().replace(/%/g, "");
	$.ajax(
	{
		type: "GET",
		url: "includes/brewery.asp",
		data: "name=" + name,
		dataType: "json",
		error: PQ.AjaxError,
		success: PQ.ProcessBrewery
	});
};

PQ.ProcessBrewery = function(data, status)
{
	//alert("PQ.ProcessBrewery = " + data.count);

	switch (true)
	{
	    case data.count == 0:
    	    $("#brewery-error").html("No breweries found");
    	    $("#brewery-error").show();
			return;
    		break;

	    case data.count == 1:
    	    GM.PrevZoom = 0;
			GM.InfoWindowMove = false;
    		GM.CrntBreweryID = data.brewery[0].ID;
    	    GM.CenterMap(data.brewery[0].X, data.brewery[0].Y, 14);
    		return;
			break;

	    case data.count > 1:
    	    $("#brewery-list-container .addr-list-title").html(data.count + " Breweries Found");
    		break;
	}
	
	PQ.Breweries = data.brewery;
	PQ.BreweryIdx = 0;
	PQ.BreweryCount = data.count;
	
	PQ.BuildBreweryList(0);
};

PQ.BuildBreweryList = function(startIdx)
{
	//alert("PQ.BuildBreweryList = " + startIdx);
	var endIdx = startIdx + 5;
	if (endIdx > PQ.BreweryCount) endIdx = PQ.BreweryCount;
	
    var itms = "", sn = "", nav = "";
	for (var idx = startIdx; idx < endIdx; idx++)
	{
		//sn = PQ.Breweries[idx].NAME.replace(/'/g, "");
		if (idx > startIdx) itms += "<img name='hdiv' src='images/body/divider.jpg' width='150px' height='2px' border='0' alt=''><br />";
    	itms += "<br /><a onclick=\"PQ.BrewerySelected(" + PQ.Breweries[idx].ID + "," + PQ.Breweries[idx].X + "," + PQ.Breweries[idx].Y + ");\"><strong>" + PQ.Breweries[idx].NAME + "</strong><br />" + PQ.Breweries[idx].ADDRESS + "<br />" + PQ.Breweries[idx].CITY + "</a>";
	}
	
	if (PQ.BreweryCount > 5)
	{
	    // 0-4  5-9  10-14
		var first, last, spacer = '';
    	nav = '<img name="hdiv" src="images/body/divider.jpg" width="150px" height="2px" border="0" alt="">';
	    nav += '<div id="brewery-list-nav">';
    	if (startIdx > 4)
    	{
    	    first = startIdx - 5;
    	    nav += '<a onclick="PQ.NextBrewery(' + first + ');">\< prev (' + (first + 1) + ' - ' + (first + 5) + ')</a>';
			spacer = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    	} 
    	if (startIdx + 5 < PQ.BreweryCount)
    	{
    	    first = startIdx + 5;
			last = first + 5;
			if (last > PQ.BreweryCount) last = PQ.BreweryCount;
			nav += spacer;
    	    nav += '<a onclick="PQ.NextBrewery(' + first + ');">(' + (first + 1) + ' - ' + (last) + ') next \></a>';
    	}
		nav += '</div>';
	} 
	 
	$("#brewery-list").html(itms + nav);
	$("#brewery-list-container").show();
	$("#brewery-button").hide();
};

PQ.NextBrewery = function(idx)
{
	//alert("PQ.NextBrewery = " + idx);
	PQ.BuildBreweryList(idx);
};

PQ.BrewerySelected = function(id, x, y)
{
	//alert("PQ.BrewerySelected = " + id);
	GM.PrevZoom = 0;
	GM.InfoWindowMove = false;
    GM.CrntBreweryID = id;
    GM.CenterMap(x, y, 14);
};

PQ.AddressChanged = function()
{
    //alert("KeyPress = " + e.keyCode);
	$("#addr-list-container").hide();
	$("#brewery-error").hide();
	$("#brewery-list-container").hide();
	if ($("#txtAddress").val() == "")
	{
		$("#addr-button").hide();
	}else{
		$("#addr-button").show();
	}
};
PQ.ProcessAddress = function()
{
	//alert("PQ.ProcessAddress=" + $("#txtAddress").val() );
	
	var address = $("#txtAddress").val();
	GM.Geocoder.getLocations(address, function(response)
	{
        if (!response || response.Status.code != 200) {
            alert(address + " not found, status code = " + response.Status.code);
        } else {
		    if (response.Placemark.length > 1)
			{
			    PQ.ShowAddressList(response.Placemark);
			}else{
    		    var addr, place;

    		    place = response.Placemark[0];
				if (place.AddressDetails.Accuracy > 5)
				{
				    addr = place.address; 
				    //addr = place.AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName + ", "
					//     + place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName + ", "
					//     + place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
				} else {
				    addr = place.address; 
				}
				if (GM.AddrMarker) GM.Map.removeOverlay(GM.AddrMarker);
				GM.StartAddress = addr;
    			GM.AddrPoint = new google.maps.LatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
                GM.Map.setCenter(GM.AddrPoint, 12);
                GM.AddrMarker = GM.CreateAddressMarker("addr", GM.AddrPoint, GM.StartAddress);
                GM.Map.addOverlay(GM.AddrMarker);
                //GM.AddrMarker.openInfoWindowHtml(addr);
				
				$("#addr-button").hide();
			}
        }
    });
};
PQ.ShowAddressList = function(places)
{
    //alert("PQ.ShowAddressList = " + places[0].AddressDetails.Accuracy + " -- " + places[0].AddressDetails.Country.AdministrativeArea.Locality);
    var s = "", b = "";
    for (var idx = 0; idx < places.length; idx++)
    {
		if (places[idx].AddressDetails.Accuracy > 5)
		{
		    // No Locality?????
		    //addr = places[idx].AddressDetails.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName + ", "
			//     + places[idx].AddressDetails.Country.AdministrativeArea.Locality.LocalityName + ", "
			//     + places[idx].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
		    addr = places[idx].address;
		} else {
		    addr = places[idx].address; 
		}
		if (idx > 0) s += "<img name='hdiv' src='images/body/divider.jpg' width='150px' height='2px' border='0' alt=''><br />";
    	s += "<br /><a onclick=\"PQ.AddressSelected('" + addr + "'," + places[idx].Point.coordinates[1] + "," + places[idx].Point.coordinates[0] + ");\">" + places[idx].address + "</a>";
	}
	$("#addr-list").html(s);
	$("#addr-list-container").show();
	$("#addr-button").hide();
};
PQ.AddressSelected = function(addr, y, x)
{
    //alert("PQ.AddressSelected = " + addr + ", " + y + ", " + x);
	if (GM.AddrMarker) GM.Map.removeOverlay(GM.AddrMarker);
	GM.StartAddress = addr;
    GM.AddrPoint = new google.maps.LatLng(y, x);
    GM.Map.setCenter(GM.AddrPoint, 12);
    GM.AddrMarker = GM.CreateAddressMarker("addr", GM.AddrPoint, GM.StartAddress);
    GM.Map.addOverlay(GM.AddrMarker);
    //GM.AddrMarker.openInfoWindowHtml(addr);
	
	$("#addr-list-container").hide();
};

PQ.MemberChanged = function()
{
    //alert("KeyPress = " + e.keyCode);
	$("#member-thx").hide();
	$("#member-error").hide();
};

PQ.ProcessMembership = function()
{
    var name = $.trim($("#mem-name").val());
    if (name == "") {
	    $("#member-error").html("Error: Must enter your name");
		$("#member-error").show();
		return;
	}
    var email = $.trim($("#mem-email").val());
    if (email == "") {
        $("#member-error").html("Error: Must enter an email address");
        $("#member-error").show();
        return;
    }
    var addr = $.trim($("#mem-address").val());
    if (addr == "") {
        $("#member-error").html("Error: Must enter a mailing address");
        $("#member-error").show();
        return;
    }
    var city = $.trim($("#mem-city").val());
    if (city == "") {
        $("#member-error").html("Error: Must enter a city");
        $("#member-error").show();
        return;
    }
    var state = $.trim($("#mem-state").val());
    if (state == "") {
        $("#member-error").html("Error: Must enter a state or province");
        $("#member-error").show();
        return;
    }
    var zip = $.trim($("#mem-zip").val());
    if (zip == "") {
        $("#member-error").html("Error: Must enter a ZIP code");
        $("#member-error").show();
        return;
	}
	
	var vals = "name=" + name
			 + "&email=" + email
			 + "&charity=" + $.trim($("#mem-charity").val())
			 + "&address=" + addr
			 + "&address2=" + $.trim($("#mem-address2").val())
			 + "&city=" + city
			 + "&state=" + state
			 + "&zip=" + zip;
	//alert("PQ.ProcessMembership = " + vals);

	$.ajax(
	{
		type: "GET",
		url: "includes/member.asp",
		data: vals,
		dataType: "html",
		error: PQ.AjaxError,
		success: PQ.MemberComplete
	});
};
PQ.MemberComplete = function(data, status)
{
	//alert("PQ.MemberComplete = " + data + ", " + status );
	
	$("#mem-name").val("");
	$("#mem-email").val("");
	$("#mem-charity").val("");
	$("#mem-address").val("");
	$("#mem-address2").val("");
	$("#mem-city").val("");
	$("#mem-state").val("");
	$("#mem-zip").val("");
	
	$("#member-thx").show();
};

PQ.ResizeMap = function()
{
    var offBottom = 43 + 4 + 20;
	var offFooter = 15;
    var winSize = PQ.GetClientSize();

    // Calc the map size
	PQ.MapWidth = winSize.x - 262;
	PQ.NarrowMapWidth = PQ.MapWidth - PQ.LeftInfoWidth; // Google adds 5px of padding to directions div + 2px for the border 
    $("#main").css("width", PQ.MapWidth);
    $("#footer").css("width", PQ.MapWidth);

    $("#map").css("height", winSize.y - offBottom - offFooter);
	if (PQ.LeftInfoVisible)
	{
	    $("#map").css("width", PQ.NarrowMapWidth);
	} else {
        $("#map").css("width", PQ.MapWidth);
	}

    $(".putting").css("left", winSize.x / 2 - 143);
    $(".locator").css("left", winSize.x - 250);
	$(".link-container").css("left", winSize.x - 247);
};
PQ.GetClientSize = function()
{
    var size = new PQ.Coord(0, 0);
    
    if(self.innerWidth)
    {
        size.x = self.innerWidth;
        size.y = self.innerHeight;
    } else if(document.documentElement && document.documentElement.clientWidth) {
        size.x = document.documentElement.clientWidth;
        size.y = document.documentElement.clientHeight;
    } else if(document.body) {
		size.x = document.body.clientWidth;
		size.y = document.body.clientHeight;
	}
    
    return size;
};
PQ.Coord = function(x, y)
{
    this.x = x;
    this.y = y;
};

/* When the DOM is ready, initialize the js libraries */
$(document).ready(PQ.Init);
