﻿/* ---------------------------------------------------------------------

SusQtech Events Near Me Distance Calulator
Written by SusQtech
www.susqtech.com

* requires: 
	jQuery 1.3.2 or later
	Google Map api 3.0 reference
--------------------------------------------------------------------- */
var webpart = "events near me";
var webpartid = "32417f6c-340f-45bd-8353-b4452261bc95";
var loadingimage = "/design/ajax-loader.gif";
var searchimage = "/_layouts/images/gosearch.gif";	
var maxDistance, location1, location2, distance, eventCount;
var debug = false;
var zipLatitude = 0.00;
var zipLongitude = 0.00;

$(document).ready(function() {
    try {
        logger(webpart + ":: started");
        // check for the web part on the page
        $('.NATPEventsNearMe:first').each(function() {
            // output the form
            var formHTML = '\n' +
			'<div id="NATPEventsNearMe" class="EventsInMyAreaWebPart">\n' +
			'	<div id="NATPEventsNearMeForm">\n' +
			'	   Zip&nbsp;<input type="text" id="tbxNATPEventsNearMeZip" style="width:50px;" maxlength="5" value="" />&nbsp;\n' +
			'	   Miles&nbsp;<input type="text" id="tbxNATPEventsNearMeDistance"  style="width:30px;" maxlength="3" value="" />\n' +
			'	   <img id="btnNATPEventsNearMeGo" style="cursor: pointer; border-width: 0px;" src="' + searchimage + '" alt="Find Events" title="Find Events"/>' +
			'	</div>\n' +
			'	<div id="NATPEventsNearMeContainer"></div>\n' +
			'	<div id="NATPEventsNearMeSummary"></div>\n' +
			'</div>\n' +
			'<div id="NATPZipCodeLookup"></div>\n' +
			'';
            $(this).before(formHTML);
            // add onclick functionality to the form
            $("#btnNATPEventsNearMeGo").click(function() {
            	alert('x');
                if ($("#btnNATPEventsNearMeGo").attr("src") != loadingimage) {
                    var zip = $("#tbxNATPEventsNearMeZip").val();
                    var maxDistance = $("#tbxNATPEventsNearMeDistance").val();

                    if (maxDistance > 400) {
                        //alert("Please enter a search distance of less than 400 miles.");
                        var eventHTMLErr = '\n' +
                            '<div class="EventsNearMeSpacer">&nbsp;</div>\n' +
							'<div class="EventsNearMeEventError">\n' +
							'		<span class="NATPEventsNearMeErrorMessage">Please enter a search distance of less than 400 miles.</span>\n' +
							'</div>\n';
                        $(this).after(eventHTMLErr);
                        return;
                    }
                    if (zip != "" && maxDistance != "") {
                        // show the loading icon
                        $("#btnNATPEventsNearMeGo").attr("src", loadingimage);
                        // get the zip code location from ZipCodeLookup List
                        GetZipCodeLocation(zip);
                        var zipLat = $("div#ziplatitude").text();
                        zipLatitude = parseFloat(zipLat);
                        var zipLng = $("div#ziplongitude").text();
                        zipLongitude = parseFloat(zipLng);
                        $("div#NATPZipCodeLookup").hide();
                        // clear events
                        $("#NATPEventsNearMeContainer").html("");
                        // get total number of events
                        eventCount = $(".NATPEventDetails").size();
                        // loop through upcoming events
                        var eventCounter = 0;
                        $(".NATPEventDetails").each(function() {
                            var eventTitle = $(this).children('.NATPEventDetailTitle').text();
                            var hotelName = $(this).children('.NATPHotelName').text();
                            var address = $(this).children('.NATPHotelAddress').text();
                            var city = $(this).children('.NATPHotelCity').text();
                            var hotelZip = $(this).children('.NATPHotelZip').text();
                            var state = $(this).children('.NATPHotelState').text();
                            var latfield = $(this).children('.NATPLatitude').text();
                            var lngfield = $(this).children('.NATPLongitude').text();
                            var eventDetailUrl = $(this).children('.NATPHotelDetailUrl').text();
                            var eventStartDate = $(this).children('.NATPEventStartDate').text();
                            // format the date better
                            eventStartDate = eventStartDate.substring(5, 7) + "/" + eventStartDate.substring(8, 10) + "/" + eventStartDate.substring(0, 4);

                            var eventHTML = '\n' +
							'<div class="EventsNearMeEventWrapper">\n' +
							'	<div class="EventsNearMeEventDetailTitle">' +
							'		<a href="' +eventDetailUrl+ '" title="Event Detail - ' + hotelName + '">' + eventTitle + '</a>&nbsp;(<span class="NATPEventDistance">[distance]</span> mi)\n' +
							'	</div>\n' +
							'	<div class="EventsNearMeEventDetailStartDate">Date: ' + eventStartDate + '</div>\n' +
							'</div>\n';

                            var eventAddress = address + " " + city + ", " + state + " " + hotelZip;
                            eventCounter = eventCounter + 1;
                            var d = ComputeDistance(latfield, lngfield, zipLatitude, zipLongitude);
                            var evtHtml = eventHTML.replace("[distance]", d);

                            var eventInRangeCount = 0;
                            eventInRangeCount = $(".EventsNearMeEventWrapper").size();
                            logger("eventInRangeCount ::" + eventInRangeCount);

                            if (parseFloat(d) <= parseFloat(maxDistance)) {
                                eventInRange = true;
                                logger("eventCount :: " + eventCount);
                                // add the event to the event list
                                logger("location within distance range");
                                // determine where it goes in the list based on distance
                                // first so just add it
                                if (eventInRangeCount == 0) {
                                    logger("adding first event " + d);
                                    $("#NATPEventsNearMeContainer").prepend(evtHtml);
                                }
                                else {
                                    var currentEventIndex = 1;
                                    // loop events
                                    logger("looking for spot for :: " + d);
                                    $(".EventsNearMeEventWrapper").each(function() {
                                        var eDistance = $(this).find(".NATPEventDistance").text();
                                        logger("iterating event=" + currentEventIndex + " d=" + eDistance);
                                        // if the new distance is greater than the current and is the last item
                                        if (parseFloat(d) > parseFloat(eDistance)) {
                                            logger("new event " + d + " > " + eDistance);
                                            if (currentEventIndex >= eventInRangeCount) {
                                                logger("last item in list " + currentEventIndex + " >= " + eventInRangeCount);
                                                $(this).after(evtHtml);
                                                logger("greater than the current and is the last");
                                            }
                                            else {
                                                logger("not the last item move next");
                                            }
                                        }
                                        else {
                                            // insert before the current distance
                                            $(this).before(evtHtml);
                                            logger("closer than the current distance");
                                        }
                                        currentEventIndex = currentEventIndex + 1;
                                    });
                                }
                            }
                            else {
                                logger("location out of distance range");
                            }
                            //end
                            $("#btnNATPEventsNearMeGo").attr("src", searchimage);
                        });
                    }
                    else {
                        // form validation
                        logger("zip or distance not entered");
                        if ($("#tbxNATPEventsNearMeZip").val() == "") {
                            $("#tbxNATPEventsNearMeZip").focus();
                        }
                        else if ($("#tbxNATPEventsNearMeDistance").val() == "") {
                            $("#tbxNATPEventsNearMeDistance").focus();
                        }
                    }
                }

                return false;
            });
        });

        logger(webpart + ":: finished");
    }
    catch (err) {
        if (err != "[object Error]") { logger(webpart + " :: " + err); }
        $("#btnNATPEventsNearMeGo").attr("src", searchimage);
    }
    $("#btnNATPEventsNearMeGo").attr("src", searchimage);
});
//
// calculates distance in km 'as the crow flies' using the Haversine formula
//
function ComputeDistance(eventLatitude,eventLongitude,zipLatitude,zipLongitude)
{
	var R = 6371; // radius of earth measured km
	var dLat = (zipLatitude-eventLatitude)* Math.PI / 180; // to radians
	var dLon = (zipLongitude-eventLongitude)* Math.PI / 180; // to radians
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(eventLatitude * Math.PI / 180) * Math.cos(zipLatitude * Math.PI / 180) * 
	        Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var dKm = R * c;
	var dMi = dKm * 0.621371192; // convert to miles
	return dMi.toFixed(1);
}
//
// Get ZipCode Location from List
//
function GetZipCodeLocation(zipcode)
{
	var soapEnv =
		"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
			<soapenv:Body> \
				<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
					<listName>ZipCodeLookup</listName> \
					<query> \
						<Query> \
						<Where> \
						<Eq> \
						<FieldRef Name='NATPZipCode' /> \
						<Value Type='Text'>" + zipcode + "</Value> \
						</Eq> \
						</Where> \
						</Query> \
					</query> \
					<viewFields> \
						<ViewFields> \
							<FieldRef Name='NATPZipCode' /> \
							<FieldRef Name='NATPCity' /> \
							<FieldRef Name='NATPState' /> \
							<FieldRef Name='NATPLatitude' /> \
							<FieldRef Name='NATPLongitude' /> \
						</ViewFields> \
					</viewFields> \
				</GetListItems> \
			</soapenv:Body> \
		</soapenv:Envelope>";
			
	$.ajax(
	{
		url: "http://www.natptax.com/_vti_bin/lists.asmx",
		type: "POST",
		dataType: "xml",
		async: false,
		data: soapEnv,
		complete: processResult,
		contentType: "text/xml; charset=\"utf-8\""
	});
}
//
// process the list query response
//
function processResult(xData, status)
{
	$(xData.responseXML).find("z\\:row").each(function() 
	{
		var owsId = $(this).attr("ows_ID");
		var owsZipCode = $(this).attr("ows_NATPZipCode");
		var owsCity = $(this).attr("ows_NATPCity");
		var owsState = $(this).attr("ows_NATPState");
		var owsLatitude = $(this).attr("ows_NATPLatitude");
		var owsLongitude = $(this).attr("ows_NATPLongitude");
		var divLatitude = "<div id='ziplatitude'>" + owsLatitude + "</div>";
		var divLongitude = "<div id='ziplongitude'>" + owsLongitude + "</div>";
		var divCoordinate = divLatitude + divLongitude;
		$("#NATPZipCodeLookup").html(divCoordinate);
	});
}
//
// function to prevent firebug logger from breaking in ie
//
function logger(err)
{
	try { if(debug == true) { console.log(err); } }
	catch(error) { alert(error); }
}
