var running = true; //prevent interruption of animation, and form control
var saveStopsG = true;
var webserviceCall = 0;
var tripPoints = new Array();
var tripId = 0;
var savedTrips = "";
var selectedTrip = -1;
var startAddress ="";
var endAddress = "";
var theInterval;
var firstRun = true;
var newRouteArray = new Array();
var mosClientId;
var userId;
var locationID;
var resportalURLClientId;
var resportalURL;
var cookieVisit = false;

$(document).ready(function() {
    $('.line').keydown(function(e) {
        if (e.keyCode == 13)
            $(this).change();
    });
    selectedTrip = gup('tripIndex');
    if (selectedTrip == "")
        selectedTrip = -1;

    mosClientId = $("#mosClientId").val();
    userId = $("#" + mosClientId).val();
    //    alert(mosClientId);
    //    alert(userId);

    resportalURLClientId = $("#resportalURLClientId").val();
    resportalURL = $("#" + resportalURLClientId).val();

    var tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    var dayAfterTomorrow = new Date();    
    dayAfterTomorrow.setDate(dayAfterTomorrow.getDate() + 2);    
    resportalURL = resportalURL + "&numberOfRooms=1&numberOfChildren=0&numberOfAdults=1&checkInDate=" + (tomorrow.getMonth()+1) + "/" + tomorrow.getDate() + "/" + tomorrow.getFullYear() + "&checkOutDate=" + (dayAfterTomorrow.getMonth()+1) + "/" + dayAfterTomorrow.getDate() + "/" + dayAfterTomorrow.getFullYear();
    //  alert(resportalURLClientId);
    //  alert(resportalURL);

    if (userId != undefined && userId != "") {
        getSavedTrips(userId);
        $('.step3 .rename').css('visibility', 'visible');
    } else
        $('.step3 .rename').css('visibility', 'hidden');

    initialize();
    if ($.cookie('trip') != null && selectedTrip == -1) populateTripFromCookie();

    if (selectedTrip >= 0) {
		
	}
	else {
		$(this).find('.step1').css('display', 'block');
		showAddress("map-start", mapStart); // INITIALIZE START FORM IF COMPLETED
		showAddress("map-end", mapEnd); // INITIALIZE END FORM IF COMPLETED  
		mapStart.checkResize();
		mapEnd.checkResize();
		mapStart.setCenter(new GLatLng(45.0, -97.0), 2);
		mapEnd.setCenter(new GLatLng(45.0, -97.0), 2);
	}
    var currentText = $('.step3 .rename').siblings('span').text();
    $('.step3 .rename').click(function() {
        currentText = $(this).siblings('span').text();
        $(this).siblings('span').empty();
        $(this).siblings('span').html('<input class="trip-title-entry" type="text" value="' + currentText + '" maxlength="48" />');

        $('.step3 .trip-title-entry').focus();

        $('.step3 .trip-title-entry').keydown(function(e) {
            if (e.which == 13) {
                $('.saved-trips ul .current').text($(this).val());
                $(this).parent().text($(this).val());
                updateTripName("/webservices/TripPlannerService.asmx/updateName", $(this).val());
            }
            if (e.which == 27) {
                $('.saved-trips ul .current').text(currentText);
                $(this).parent().text(currentText);
            }
        });
        return false;
    });

    $('.tp .step3 fieldset .button').children().click(function() {
        saveStopsG = true;
        //nextPage(true);        
        if (userId == "undefined" || userId == "") {
            alert("Please log in to save your trip.");
            return;
        }
        else {
            if (directions != null) callWebService('/webservices/TripPlannerService.asmx/createTrip');
        }
        //        if (showAddress(
        //			    $('.step2 li.clear:first .mapperwrapper').children().eq(0).attr("id"),
        //			    eval(
        //				    "mapStops[" +
        //				    (parseFloat($('.step2 li.clear:first .stop-num').text()) - 1) +
        //				    "]"
        //			    )
        //		    )
        //	    ) {        
        //            $('.step2 li.clear:first .add').trigger('click'); // IF STOP INFO IS PROPER, ADD TO VISUAL QUEUE
        //        }
        return false;
    });
    /*$('.no-stops').children().click(function() {
    saveStopsG = false;
    if (!routeData())
    nextPage(true);
    return false;
    });*/

    $('.next').children().click(function() {
        nextPage(true);
        return false;
    });
    $('.prev').children().click(function() {
        nextPage(false);
        return false;
    });

    //Stop Management
    $('.add').click(function() {
        var liClear = $(this).parents('li.clear');
        var stopIndex = parseFloat(liClear.find('.stop-num').text());
        if (showAddress('map-stop' + stopIndex, mapStops[stopIndex - 1])) {
            $(this).css("opacity", "1");
            var displayAddress;
            if (showAddress('map-stop' + stopIndex, mapStops[stopIndex - 1])) {
                displayAddress =
					$('.step2 li.clear:first .street1-s input').val() + ' ' +
					$('.step2 li.clear:first .street2-s input').val() +
					$('.step2 li.clear:first .city-s input').val() + ', ' +
					$('.step2 li.clear:first .state select').val();
            } else if ($('.step2 li.clear:first .street1-s input').val() != "" && $('.step2 li.clear:first .city-s input').val() != "" && $('.step2 li.clear:first .state select').val() != "") {
                displayAddress =
					$('.step2 li.clear:first .street1-s input').val() + ' ' +
					$('.step2 li.clear:first .city-s input').val() + ', ' +
					$('.step2 li.clear:first .state select').val();
            }

            liClear.find('.stop-address').text(displayAddress);

            var newMenu = liClear.clone(true);
            newMenu = $(newMenu);
            $('.step2 li.clear:first fieldset').children().css("display", "none");
            $('.step2 li.clear:first fieldset legend').css("display", "block");

            /*** Increment and Reload Forms ***/
            for (var x = 0; x < newMenu.find('label').length; x++) {
                var refLabel = newMenu.find('label:eq(' + x + ')');
                refLabel.attr("for", refLabel.attr("for").replace(/[0-9]$/, "") + (parseFloat(newMenu.find('.stop-num').text()) + 1));
                if (refLabel.siblings('input').length != 0)
                    refLabel.parent().children('input').attr("name", refLabel.parent().children('input').attr("name").replace(/[0-9]$/, "") + (parseFloat(newMenu.find('.stop-num').text()) + 1));
            }
            newMenu.find('input').val("");
            //newMenu.find('ol').children('li').children('span').text("Choose...");
            newMenu.find('ol').children('.state').children('cs-select').children('li.current').text("Choose...");

            /*** Transition ***/
            newMenu.height(0);
            newMenu.css("display", "none");
            liClear.before(newMenu);

            /*** Increment and Create Gmap ***/
            newMenu.find('.mapperwrapper').children().eq(0).attr("id", liClear.find('.mapperwrapper').children().eq(0).attr("id").replace(/[0-9]$/, "") + (parseFloat(newMenu.find('.stop-num').text()) + 1));
            mapStops[parseFloat(newMenu.find('.stop-num').text())] = new GMap2(document.getElementById(newMenu.find('.mapperwrapper').children().eq(0).attr("id")));
            mapStops[parseFloat(newMenu.find('.stop-num').text())].setCenter(new GLatLng(68.0, -155.0), 2);
            mapStops[parseFloat(newMenu.find('.stop-num').text())].addControl(new GSmallMapControl());

            /*** Increment Stop Number ***/
            newMenu.find('.stop-num').text(parseFloat(newMenu.find('.stop-num').text()) + 1);

            liClear.find('.stopfunc, .stop-address').fadeIn('medium');
            liClear.animate({
                marginBottom: '316px',
                height: '45px',
                opacity: '0.5'
            }, 'slow');

            liClear.children('.trip-display-highlight').css({ backgroundPosition: '0 0' }).animate({
                height: '30px',
                backgroundPosition: "(0 -250px)"
            }, 'slow',
				function() {
				    newMenu.css('display', 'block');
				    newMenu.animate({
				        height: '316px'
				    }, 'normal');
				    mapStops[parseFloat(newMenu.find('.stop-num').text() - 1)].checkResize();
				    liClear.animate({
				        marginTop: '10px',
				        marginBottom: '0',
				        opacity: '1'
				    }, 'normal');
				}
			);
            return false;
        } else {
            $(this).css("opacity", "0.5");
            return false;
        }
    });

    $('.change').click(function() {
        var xthis = $(this);
        var thisForm = xthis.siblings('ol');
        xthis.parents('li.clear').find('input').removeAttr("disabled");
        if (!xthis.hasClass('save')) {
            xthis.parents('fieldset').children().css("display", "block");
        } else {
            xthis.parent().children().css("display", "none");
            xthis.parent().children('.stopfunc').css("display", "block");
            xthis.parents('fieldset').children('legend').css("display", "block");
        }
        var stopIndex = parseFloat(xthis.siblings('legend').find('.stop-num').text()) - 1;
        //added for updating stop address and map
        if (xthis.text() == "Save Changes") {
            var street1 = thisForm.find('.street1').val();
            var street2 = thisForm.find('.street2').val();
            var city = thisForm.find('.city').val();
            var state = thisForm.find('.state').children('select').val();
            var address = ""
            if (street1 != "" && city != "" && state != "" && street2 != "") {
                address = street1 + ' ' + street2 + ', ' + city + ', ' + state
            } else if (street1 != "" && city != "" && state != "") {
                address =
				street1 + ' ' +
				city + ', ' +
				state;
            } else if (city != "" && state != "") {
                address =
					city + ', ' +
					state;
            }
            xthis.siblings('legend').find('.stop-address').text(address);
            geocoder.getLatLng(address, function(point) {
                if (!point) {
                    alert("Sorry, we couldn't find " + address + ".  Please double check the address.");
                } else {
                    mapStops[stopIndex].setCenter(point, 13);
                    mapStops[stopIndex].checkResize();
                }
            });
        } else {
            var mapCenter = mapStops[stopIndex].getCenter();
            //mapStops[stopIndex].checkResize();
            mapStops[stopIndex].setCenter(mapCenter, 13);
            var icon = new GIcon();
            icon.image = "/images/map-marker_stop.png";
            icon.iconSize = new GSize(37, 28);
            icon.iconAnchor = new GPoint(13, 25);
            var marker = new GMarker(mapCenter, icon);
            mapStops[stopIndex].checkResize();
            mapStops[stopIndex].addOverlay(marker);
        }

        $(this).toggleClass("save");

        if (xthis.parents('.trip-display-outline').height() < 316) {
            xthis.text("Save Changes");
            xthis.parents('.trip-display-outline').animate({
                height: '316px'
            }, 'medium');
            xthis.parents('.trip-display-highlight').css({ backgroundPosition: '0 -250px' }).animate({
                height: '300px',
                backgroundPosition: "(0 0)"
            }, 'medium');
        } else {
            xthis.text("Click To Change");
            xthis.parents('.trip-display-outline').animate({
                height: '45px'
            }, 'medium');
            xthis.parents('.trip-display-highlight').animate({
                height: '30px',
                backgroundPosition: "(0 -250px)"
            }, 'medium');
        }
        return false;
    });

    $('.remove').click(function() {
        var xthis = $(this);
        var liClear = xthis.parents('li.clear');
        var thisForm = xthis.siblings('ol');
        liClear.animate({
            height: "0",
            opacity: "0"
        }, 'fast', function() {
            liClear.remove();
        });
        var allStops = $('.stop-num');
        var stop = 0;
        for (var x = 0; x < allStops.length; x++) {
            var stopNum = $(allStops[x]);
            if (parseFloat(stopNum.text()) > parseFloat(liClear.find('.stop-num').text())) {
                $('.stop-list fieldset:eq(' + x + ') .mapperwrapper > div').attr('id', 'map-stop' + (parseFloat(stopNum.text()) - 1));
                stopNum.text(parseFloat(stopNum.text()) - 1);
            }
        }
        //blank all the stop fields before routing
        thisForm.find('.street1').val("");
        thisForm.find('.street2').val("");
        thisForm.find('.city').val("");
        thisForm.find('.state').children('input').val("");
        thisForm.find('.zip').val("");
        //re-route data
        routeData();
        return false;
    });

});


/*** CONSTRUCT LIST OF ADDRESSES ALONG ROUTE IN PROPER ORDER ***/
function routeData() {    
    var saveStops = saveStopsG;
    var fieldNames = new Array();
    fieldNames[0] = ["#street1", "#street2", "#city", "select[name='state']", "select[name='country']", "#zip"];
    fieldNames[1] = "";
    fieldNames[2] = ["#street1-e", "#street2-e", "#city-e", "select[name='state-e']", "select[name='country-e']", "#zip-e"];
    if (saveStops) {
        fieldNames[1] = [".street1-s input", ".street2-s input", ".city-s input", ".step2 .state select", ".step2 .country select", ".zip-s input"];
    }
    var routeArray = new Array();    
    var routeNode = 0;    
    for (var x = 0; x < fieldNames.length; x++) {
        var addy = "";
        if ($(fieldNames[x][0]).length == 1) {		    
            if (/*$(fieldNames[x][0]).val() != "" &&*/ $(fieldNames[x][2]).val() != "" && $(fieldNames[x][3]).val() != "") {                
                for (var y = 0; y < fieldNames[x].length; y++) {
                    if ($(fieldNames[x][y]).val() != "" && $(fieldNames[x][y]).val() != undefined) {
                        if (y == (fieldNames[x].length - 1)) {
                            addy = addy + $(fieldNames[x][y]).val() + '';
                        } else {
                            addy = addy + $(fieldNames[x][y]).val() + '| ';
                        }                       
                        
                    } else { 
                        if (y == (fieldNames[x].length - 1)) {
                            addy = addy + '';
                        } else {
                            addy = addy + '|';
                        }
                    }
                }
                if (addy != "") {                    
                    routeArray[routeNode] = addy;
                    routeNode++;
                }
            }
				
        } else {
            for (var z = ($(fieldNames[x][0]).length - 1); z >= 0; z--) {
                addy = "";
                if (/*$(fieldNames[x][0] + ':eq(' + [z] + ')').val() != "" &&*/ $(fieldNames[x][2] + ':eq(' + [z] + ')').val() != "" && $(fieldNames[x][3] + ':eq(' + [z] + ')').val() != "") {
                    for (var y = 0; y < fieldNames[x].length; y++) {
                        if ($(fieldNames[x][y] + ':eq(' + [z] + ')').val() != "" && $(fieldNames[x][y] + ':eq(' + [z] + ')').val() != undefined) {
                            if (y == (fieldNames[x].length - 1)) {
                                addy = addy + $(fieldNames[x][y] + ':eq(' + [z] + ')').val() + '';
                            } else {
                                addy = addy + $(fieldNames[x][y] + ':eq(' + [z] + ')').val() + '|';
                            }                            
                        } else {
                            if (y == (fieldNames[x].length - 1)) {
                                addy = addy + '';
                            } else {
                                addy = addy + '|';
                            }
                        }                                             
                    }
                    if (addy != "") {                        
                        routeArray[routeNode] = addy;
                        routeNode++;
                    }
                }
            }
        }
    }    
    /*var outie = "";
    for(var x=0;x<routeArray.length;x++) {
        outie = outie + x + ": " + routeArray[x] + "\n";        
    }
	alert("routeData:outie:"+outie);*/
    tripPoints = routeArray;	
    if (directions == null && routeArray.length >= 2)
        directions = new GDirections(mapRoute, document.getElementById("directions"));
    if (directions != null) {
        directions.loadFromWaypoints(routeArray);        
         
        if (wizardIndex == 1 && !cookieVisit && userId != undefined && userId != "" && $.cookie("trip")!= null) {
			nextPage(true, 2);
		}
    }
    if (selectedTrip >= 0 && firstRun) {
		firstRun = false;
		theInterval = setInterval("checkForDirections()",5);
    }
    return false;
}

function checkForDirections() {
	if($('#directions table').length != 0) {
		clearInterval(theInterval);
		$('.step:eq(1)').addClass('visited');
		nextPage(true, 3);
	}
}

var wizardIndex = 1;
function nextPage(next, skipTo) {    
    if (!running) {
        running = true;
        if (!skipTo) {
            $('html, body').animate({
                scrollTop: 0
            }, 'slow');
        }
        var currPage = ".step" + wizardIndex;
        var destPage;
        var wizardIndexNav = wizardIndex - 1;        
        var currNav = ".steps li:eq(" + wizardIndexNav + ")";
        var destNav;
        if (next && wizardIndex < 3) {
            $('.steps .step:eq(' + (wizardIndex - 1) + ')').removeClass('current');
            $('.steps .step:eq(' + (wizardIndex - 1) + ')').addClass('visited');
            wizardIndex++;
            wizardIndexNav++;

        } else if (!next && wizardIndex > 1) {
            wizardIndex--;
            wizardIndexNav--;
            //reset webservice call to 0
            webserviceCall = 0;
        }		
        destPage = ".step" + wizardIndex;
        destNav = ".steps li:eq(" + wizardIndexNav + ")";
        if (skipTo) {
            destPage = ".step" + skipTo;
            destNav = ".steps li:eq(" + (skipTo - 1) + ")";
            wizardIndex = skipTo;
        }

        $(currPage).fadeOut('slow', function() {
            $(destPage).fadeIn('medium');
        });

        $(currNav).css({ backgroundPosition: '0 0' }).animate({
            backgroundPosition: "(0 -69px)"
        }, 'slow',
			function() {
			    $(destNav).css({ backgroundPosition: '0 -69px' });
			    if (!$(destNav).hasClass('visited')) {
			        $(destNav).addClass('current');
			    }
			    $(destNav).addClass('visited');
			    $(destNav).animate({
			        backgroundPosition: "(0 0)"
			    }, 'medium',
					function() {
					    running = false;
					    if (wizardIndex == 1) {
					        mapStart.checkResize();
					        showAddress("map-start", mapStart);
					        mapEnd.checkResize();
					        showAddress("map-end", mapEnd);
					    }
					    if (wizardIndex == 2) {
					        var index = mapStops.length - 1;
					        mapStops[index].checkResize();
					        //mapStops[index].setCenter(new GLatLng(45.0, -97.0), 2);
					    }
					    /*** ACTIONS FOLLOWING STEP LOADS ***/
					    if (mapRoute && mapStops) {
					        mapStops[0].checkResize(); //// REFRESH MAPS, FIX DISPLAY ERRORS
					        mapRoute.checkResize();
							
							if (wizardIndex == 2 && !cookieVisit && userId != undefined && userId != "" && $.cookie("trip")!= null) {
								GEvent.addListener(directions,"load", function() {
									if (selectedTrip >= 0) {
								
								    } else {
								        $('.step3 .rename').siblings('span').text("My Trip #" + ($('#Saved\\ Trips ul li').length + 1));
								    }
									nextPage(true, 3);
								});
							}
							
					        if (directions != null && wizardIndex == 3) {
					            if (webserviceCall == 0 && selectedTrip == -1) {
					                if (userId == "undefined" || userId == "") $.cookie('trip', tripPoints);
					            }
					            selectedTrip = -1;
					            /*** RE-CENTER ROUTE MAP ***/
					            var routeBound = directions.getBounds();
					            if (routeBound == null) {
					                //alert("Error creating route for the trip. Please check all your addresses and try again");
					            }
					            if (routeBound != null) {
					                mapRoute.setCenter(routeBound.getCenter(), mapRoute.getBoundsZoomLevel(routeBound));
					                /*** ENTER TRIP INTO CACHE ***/
					                if ($('.saved-trips ul .current').length == 0)
					                    $('.saved-trips ul').append('<li class="current">' + $('.step3 fieldset legend span').text() + '</li>');

					                /*** STYLE STEP-BY-STEP DIRECTIONS ***/
					                if ($('#directions h1').length == 0) {
					                    $('#directions').prepend('<h1>Driving Directions</h1>');
					                }
					                $('#directions').css("padding", "0");
					                $('#directions table, #directions tr, #directions td').attr("style", "");
					                $('#directions div[jsselect="Placemark"] > div > div')
										.css("text-align", "left")
										.css("font-weight", "bold");
					                $('#directions div[jsselect="Placemark"] > div > table tr td')
										.css("padding-bottom", "10px");
					                $('#directions div[jsselect="Placemark"] > div > table > tbody > tr > td[jseval="this.innerHTML = descriptionHtml"]')
										.addClass('description');
					                $('#directions div[jsselect="Placemark"] > div > table > tbody > tr > td[jseval="this.innerHTML = Distance.html"]')
										.addClass('walker');
					                if ($('.walker').text().search(/Go/) == -1)
					                    $('.walker').prepend("Go ");
					                $('#directions div[jsselect="Placemark"] > table').css("display", "none");
					                $('#directions div[jsselect="Placemark"]:not(:first, :last) > table')
										.css("display", "block")
										.addClass('stop');
					                if ($('.stop .msg').length == 0)
					                    $('.stop tr').prepend('<td class="msg">You have arrived at <strong>Stop</strong></td>');
					                $('#directions tr').click(function() {
					                    $('html, body').animate({
					                        scrollTop: 215 + "px"
					                    }, 'slow');
					                });
					                /*** POPULATE ROUTE OVERVIEW LIST ***/
					                $('.route ol').empty();
					                var addies = new Array(), cities = new Array(), states = new Array(), locIDs = new Array(), city, state,
									    pointLength = $('#directions div[jsselect="Placemark"]').length,
										stopList = $('.step2 ol.stop-list > li').length;
									
					                for (var x = 0; x < pointLength; x++) {
										if(x == 0) {
											city = $('.start .city').val();
											state = $('.start .state select').val();
										} else if(x == pointLength - 1) {
											city = $('.end .city').val();
											state = $('.end .state select').val();
										} else {
											city = $('.step2 ol.stop-list > li:eq('+(stopList - x)+') .city-s input').val();
											state = $('.step2 ol.stop-list > li:eq('+(stopList - x)+') .state select').val();
										}

					                    addies[x] = city + ', ' + state;
					                   
					                    cities[x] = city;
					                    states[x] = state;
					                }
					                for (var y = 0; y < addies.length; y++) {
					                    if(y != addies.length-1) {
											getLocationID(y, addies[y], cities[y], states[y]);
										} else {
											getLocationID('last', addies[y], cities[y], states[y]);
										}
					                }

					                /*
					                if (locIDs[0] == "-1" || locIDs[0] == undefined)
					                    $('.route .start').html('<span class="loc-info">'+addies[0]+'</span>');
					                else
					                    $('.route .start').html('<span class="loc-info">'+addies[0]+'</span>' + " <a class='rri' href='" + resportalURL + "&locationID=" + locationID + "'>Click to Find Nearby Red Roof Inns</a>");

					                if (locIDs[locIDs.length - 1] == "-1" || locIDs[locIDs.length - 1]  == undefined)
					                    $('.route .end').html('<span class="loc-info">'+addies[addies.length - 1]+'</span>');
					                else
					                    $('.route .end').html('<span class="loc-info">'+addies[addies.length - 1]+'</span>' + " <a class='rri' href='" + resportalURL + "&locationID=" + locationID + "'>Click to Find Nearby Red Roof Inns</a>");
					                */
									
					                /*
									if (addies.length > 2) {
					                    var distSoFar = 0;
					                    var ttlDist = directions.getDistance().meters;
					                    var addDist = 0;
					                    for (var x = 1; x < (addies.length - 1); x++) {
					                        if (locIDs[x] == "-1" || locIDs[x] == undefined)
					                            $('.route ol').append('<li class="stop"><span class="loc-info">' + addies[x] + '</span></li>');
					                        else
					                            $('.route ol').append("<li class='stop'><span class='loc-info'>" + addies[x] + "</span> <a class='rri' href='" + resportalURL + "&locationID=" + locationID + "'>Click to Find Nearby Red Roof Inns</a></li>");
					                    }
					                    for (var x = 0; x < $('.route ol li.stop').length; x++) {
					                        addDist = directions.getRoute(x).getDistance().meters;

					                        if ((((distSoFar + addDist) / ttlDist) * 278) < ((distSoFar / ttlDist) * 278) + 30 && x > 0)
					                            $('.route ol li.stop:eq(' + x + ')').css("top",
													((distSoFar / ttlDist) * 278) + 30 + "px");
					                        else
					                            $('.route ol li.stop:eq(' + x + ')').css("top",
													(((distSoFar + addDist) / ttlDist) * 278) + "px");

					                        distSoFar = distSoFar + addDist;
					                    }
					                }
									*/
					            }
					        }
					    }
					}
				);
			}
		);

    }
    $('.visited').click(function() {
		cookieVisit = true;
        if ($('.step').length - $(this).nextAll('.step').length != wizardIndex) {
            if ($('.step').length - $(this).nextAll('.step').length > wizardIndex) {
                nextPage(true, $('.step').length - $(this).nextAll('.step').length);
            } else {
                nextPage(false, $('.step').length - $(this).nextAll('.step').length);
            }
        }
    });    
}

if (GBrowserIsCompatible()) {    
    var geocoder = new GClientGeocoder();    
    var mapStart = null;
    var mapEnd = null;
    var mapStops = new Array();
    var mapRoute = null;
    var directions = null;
    var formControl1 = 0;
    var formControl2 = 0;
}

function initialize() {    
    if (GBrowserIsCompatible()) {        
        mapStart = new GMap2(document.getElementById("map-start"));
        mapEnd = new GMap2(document.getElementById("map-end"));
        mapStops[0] = new GMap2(document.getElementById("map-stop1"));
        mapRoute = new GMap2(document.getElementById("map-route"));
        mapStart.setCenter(new GLatLng(45.0, -97.0), 2);
        mapEnd.setCenter(new GLatLng(45.0, -97.0), 2);
        mapStops[0].setCenter(new GLatLng(68.0, -155.0), 2);
        mapRoute.setCenter(new GLatLng(72.0, -175.0), 2);
        mapStart.addControl(new GSmallMapControl());
        mapEnd.addControl(new GSmallMapControl());
        mapStops[0].addControl(new GSmallMapControl());
        mapRoute.addControl(new GSmallMapControl());

        $('.start input, .start select').change(function() {		    
            showAddress("map-start", mapStart);
        });
        $('.end input, .end select').change(function() {
            showAddress("map-end", mapEnd);
        });
        $('.step2 input, .step2 select').change(function() {
            showAddress(
				$(this).parents('li.clear').find('.mapperwrapper').children().eq(0).attr("id"),
				eval(
					"mapStops[" +
					(parseFloat($(this).parents('li.clear').find('.stop-num').text()) - 1) +
					"]"
				)
			);
        });
    }
    
}

function showAddress(id, map) {    
    var addressList = $('#' + id).parent().siblings('ol');
    if (geocoder && addressList.find(".city").val() != '') {
        var address =
			addressList.find(".street1").val() + ' ' +
			addressList.find(".street2").val() + ', ' +
			addressList.find(".city").val() + ', ' +
            addressList.find(".state").children('select').val() + ' ' +
			addressList.find(".country").children('select').val() + ' ' +
			addressList.find(".zip").val();
            geocoder.getLocations(address, function(result) {
                if (result && result.Status.code == 200) {
                    if (result.Placemark[0].AddressDetails.Accuracy <= 4) {
                        var startAddr = result.Placemark[0].address.split(", ");
                        //just replace the fields for now
                        addressList.find(".city").val(jQuery.trim(startAddr[0]));                        
                        addressList.find(".state").children('select').val(jQuery.trim(startAddr[1]));
                    } else if(result.Placemark[0].AddressDetails.Accuracy > 4 && addressList.find(".state").children('select').val() == "") {
						formValidate(map, false);
				        return false;
					} else if (result.Placemark[0].AddressDetails.Accuracy > 4) {
                        //parse the address and re-populate the form fields
                        var startAddr = result.Placemark[0].address.split(", ");
                        addressList.find(".street1").val(jQuery.trim(startAddr[0]));
                        addressList.find(".city").val(jQuery.trim(startAddr[1]));
                        var stateAndZip = startAddr[2].split(" ");
                        var zip = jQuery.trim(stateAndZip[2]);                        
                        addressList.find(".state").children('select').val(jQuery.trim(stateAndZip[0]));
                    }
			        map.clearOverlays();
			        var lat = result.Placemark[0].Point.coordinates[1];
			        var lng = result.Placemark[0].Point.coordinates[0];
			        var point = new GLatLng(lat, lng);
			        map.setCenter(point, 13);
			        var icon = new GIcon();
			        switch (addressList.find(".street1").siblings('label').attr("for")) {
			            case "street1":
			                icon.image = "/images/map-marker_start.png";
			                icon.iconSize = new GSize(85, 38);
			                icon.iconAnchor = new GPoint(43, 35);
			                break;
			            case "street1-e":
			                icon.image = "/images/map-marker_end.png";
			                icon.iconSize = new GSize(74, 37);
			                icon.iconAnchor = new GPoint(38, 33);
			                break;
			            default:
			                icon.image = "/images/map-marker_stop.png";
			                icon.iconSize = new GSize(37, 28);
			                icon.iconAnchor = new GPoint(13, 25);
			        }
			        var marker = new GMarker(point, icon);
			        map.addOverlay(marker);
			        map.checkResize();
			        routeData();
			    } else {
			        alert("Sorry, we couldn't find " + address + ".  Please double check the address.");
			    }
			});			
        formValidate(map, true);
		addressList.find('.add').css('opacity','1');
        return true;
    } else {
        formValidate(map, false);
        return false;
    }
}


function formValidate(map, complete) {
    if (map == mapStart)
        formControl1 = complete;
    else if (map == mapEnd)
        formControl2 = complete;
    if (formControl1 && formControl2) {
        running = false;
        $('.step1 .next').css("opacity", "1");
    } else {
        running = true;
        $('.step1 .next').css("opacity", "0.5");
    }
}

//method to call a webservice with the trip string
function callWebService(serviceURL) { //SAVE TRIP EVENT

    //alert("callWebService");
    if (userId == "undefined" || userId == "") return;
    //create json string from javascript objects
    var jsonStr = getJSONString(userId);
    //var jsonStr = JSON.stringify(trip);
    //alert('callWebService> jsonStr>'+jsonStr);
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: serviceURL,
        dataType: "json",
        data: jsonStr,
        success:
           function(msg) {
               //alert("Callwebservice Success response:" + msg + ": trip created");
               //$('#testDiv').html(eval(msg));
               //$('#testDiv').html(msg.d);
               tripId = msg;
               //append the newly added trip to the list of trips
               /*var savedTripsNode = $('.content .tasks ul #Saved\\ Trips ul');
               var numTrips = $('.content .tasks ul #Saved\\ Trips ul').children('li').length;
               var index = gup("tripIndex");
               if (index == "") {			       
               //alert(numTrips);
               var trip = "<li><a href=\"/trip-planner/plan-a-trip.aspx?tripIndex="+numTrips+"\">"+$('.step3 legend span').text()+"</a></li>"; 
               savedTripsNode.append(trip);			       			       
               } else {
               //don't do anything
               } */
               $('.content .tasks ul #Saved\\ Trips ul').html("");
               getSavedTrips(userId);
               $('.step3 .rename').css('visibility', 'visible');
               if ($.cookie('trip') != null) $.cookie('trip', null);
               window.location = "saved-trips.aspx"; 
           },
        error:
           function(XMLHttpRequest, textStatus, errorThrown) {
               console.log(":" + XMLHttpRequest.responseText);
               var response = JSON.parse(XMLHttpRequest.responseText);
               if (response.Message) {
                   console.log(response.Message);
               }
           }
    });
}

function updateTripName(serviceURL, newName) {
   //escape double quotes in the name
   var re=/"/g;
   var check = newName.replace(re, '\\"');    
   var updateStr = { "updateStr": "{'userId':" + "'" + userId + "'" + ",'id':" + tripId + ", 'title':\"" + check + "\"}" };   
   var jsonStr = JSON.stringify(updateStr);   
   $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: serviceURL,
        dataType: "json",
        data: jsonStr,
        success:
           function(msg) {
               //alert("webservice response:" + msg + ": trip created");
               //$('#testDiv').html(eval(msg));
               //$('#testDiv').html(msg.d);
               //tripId = msg;			   
			   //update the list item 
			   var index = gup("tripIndex");			   
			   if (index == "") {			     
				 var tripIndex = $('#Saved\\ Trips ul').children().length - 1;
				 $('#Saved\\ Trips ul li:eq('+tripIndex+')').html("<a href=\"/trip-planner/plan-a-trip.aspx?tripIndex="+tripIndex+"\">"+newName+"</a>");
                              } else {		   
			     $('#Saved\\ Trips ul li:eq('+index+')').html("<a href=\"/trip-planner/plan-a-trip.aspx?tripIndex="+index+"\">"+newName+"</a>");
			   }
           },
        error:
           function(XMLHttpRequest, textStatus, errorThrown) {
               console.log(":" + XMLHttpRequest.responseText);
               var response = JSON.parse(XMLHttpRequest.responseText);
               if (response.Message) {
                   console.log(response.Message);
               }
           }
    });
}

function getJSONString(userId) {         
    var trip = { "tripStr": "{trip :{'id': "+tripId+",'title': " + "\"" + $('.step3 legend span').text() + "\"" +
    ",userId:"+"'"+userId+"'"+",tripPoint:[" + getTripEndPoint(true) + getStopsJSON() + getTripEndPoint(false)+ "]}}"
    };
    var jsonStr = JSON.stringify(trip);    
    return jsonStr;
}

function getStopsJSON() {
    //check if there are stops    
    if (!saveStopsG) {
        return "";
    } else {
        var outie = "";	
        var stopNum = 1;	
        for (var x = 0; x < tripPoints.length; x++) {		    
            if (x > 0 && x < (tripPoints.length - 1)) {                                
                var address = new String(tripPoints[x]);				
                var addressArr = address.split('|');
				var stopPoint = "{isStart: false, isEnd: false";
                for (var y = 0; y < addressArr.length; y++) {
                    if (y == 0) {
                        stopPoint += ", streetAddress1: '";
                        stopPoint += addressArr[y];
                        stopPoint += "'";
                    } else if (y == 1) {
                        stopPoint += ", streetAddress2: '";
                        stopPoint += addressArr[y];
                        stopPoint += "'";
                    } else if (y == 2) {
                        stopPoint += ", city: '";
                        stopPoint += addressArr[y];
                        stopPoint += "'";
                    } else if (y == 3) {
                        stopPoint += ", state: '";
                        stopPoint += addressArr[y];
                        stopPoint += "'";
                    } else if (y == 4) {
                        stopPoint += ", country: '";
                        stopPoint += addressArr[y];
                        stopPoint += "'";
                    } else if (y == 5) {
                        stopPoint += ", zip: '";
                        stopPoint += addressArr[y];
                        stopPoint += "'";
                    }                                        					
                }
                stopPoint += ", stopNumber: "+stopNum;				
                stopPoint += "}, ";
				outie += stopPoint;
				stopNum++;
            }
        }        
        return outie;
    }    
}

function getTripEndPoint(isStart) {
    if (isStart) {
        var startPoint = "{isStart: true, isEnd: false";        
        startPoint += ", streetAddress1: '";
        startPoint += $('#map-start').parent().siblings('ol').find(".street1").val();
        startPoint += "'";
        startPoint += ", streetAddress2:";
        if ($('#map-start').parent().siblings('ol').find(".street2").val() == '') {
              startPoint += ""
        } else {
              startPoint += " '"
              startPoint += $('#map-start').parent().siblings('ol').find(".street2").val();
              startPoint += "'";
        }    
        startPoint += ", city: '";
        startPoint += $('#map-start').parent().siblings('ol').find(".city").val();
        startPoint += "'";
        startPoint += ", state: '";
        startPoint += $('#map-start').parent().siblings('ol').find(".state").children('select').val();
        startPoint += "'";
        startPoint += ", country: '";
        startPoint += $('#map-start').parent().siblings('ol').find(".country").children('select').val();
        startPoint += "'";
        startPoint += ", zip: '";
        startPoint += $('#map-start').parent().siblings('ol').find(".zip").val();
        startPoint += "'";
		startPoint += ", stopNumber: 0"
		startPoint += "}, ";		
        return startPoint;
    } else {
            var endPoint = "{isStart: false, isEnd: true";
            endPoint += ", streetAddress1: '";
            endPoint += $('#map-end').parent().siblings('ol').find(".street1").val();
            endPoint += "'";
            endPoint += ", streetAddress2:";
            if ($('#map-end').parent().siblings('ol').find(".street2").val() == '') {
                endPoint += ""
            } else {
                endPoint += " '"
                endPoint += $('#map-end').parent().siblings('ol').find(".street2").val();
                endPoint += "'";
            }            
            endPoint += ", city: '";
            endPoint += $('#map-end').parent().siblings('ol').find(".city").val();
            endPoint += "'";
            endPoint += ", state: '";
            endPoint += $('#map-end').parent().siblings('ol').find(".state").children('select').val();
            endPoint += "'";
            endPoint += ", country: '";
            endPoint += $('#map-end').parent().siblings('ol').find(".country").children('select').val();
            endPoint += "'";
            endPoint += ", zip: '";
            endPoint += $('#map-end').parent().siblings('ol').find(".zip").val();
            endPoint += "'";
			endPoint += ", stopNumber: 0"
            endPoint += "}";            
            return endPoint;
    }
}

function getSavedTrips(userId) {    
	var serviceURL = "/webservices/TripPlannerService.asmx/getTrips";
	$.ajax({
	    type: "POST",
	    contentType: "application/json; charset=utf-8",
	    url: serviceURL,
	    dataType: "json",
	    data: "{'userId':'" + userId + "'}",
	    success:
           function(msg) {
	            
               //$('#testDiv').html(eval(msg));
               //$('#testDiv').html(msg.d);
               savedTrips = JSON.parse(msg);
               var numTrips = savedTrips.trips.trip.length;
               //alert(numTrips);
               var savedTripsNode = $('.content .tasks ul #Saved\\ Trips');
               //savedTripsNode.append("<ul>");
               //savedTripsNode.replace("");
               var trip = "<ul>";
               for (var x = 0; x < numTrips; x++) {
                   trip += "<li><a href=\"/trip-planner/plan-a-trip.aspx?tripIndex=" + savedTrips.trips.trip[x].id + "\">" + savedTrips.trips.trip[x].title + "</a></li>";
                   //savedTripsNode.append(trip);
               }
               trip += "</ul>";
               savedTripsNode.append(trip);
               //savedTripsNode.html(trip);
			   
			   //get trip data
				var tripIndex = -1;
				var totalTripPoints = savedTrips.trips.trip.length;
				for (var x = 0; x < totalTripPoints; x++) {
					if (savedTrips.trips.trip[x].id == selectedTrip) 
						tripIndex = x;
				}
				parseTripData(tripIndex);
				showAddress("map-start", mapStart); // INITIALIZE START FORM IF COMPLETED
				showAddress("map-end", mapEnd); // 
				routeData();
				//running = false;
				//nextPage(true, 3);
           },
	    error:
           function(XMLHttpRequest, textStatus, errorThrown) {
               console.log(":" + XMLHttpRequest.responseText);
               var response = JSON.parse(XMLHttpRequest.responseText);
               if (response.Message) {
                   console.log(response.Message);
               }
           }
	});
}

function parseTripData(tripIndex) {        
    var tripTitle = savedTrips.trips.trip[tripIndex].title;	
    //set the trip name with the title
	$('.step3').find('.rename').siblings('span').text(tripTitle);
	tripId = savedTrips.trips.trip[tripIndex].id;
	var numTripPoints = savedTrips.trips.trip[tripIndex].tripPoint.length;
	if (numTripPoints > 0) {
	    //get all the address data		
		for(var x = 0; x < numTripPoints; x++) {
		    var isStart = savedTrips.trips.trip[tripIndex].tripPoint[x].isStart;
			var isEnd = savedTrips.trips.trip[tripIndex].tripPoint[x].isEnd;
			if (isStart) {
			    mapStart = populateTripEndPoints("map-start", savedTrips.trips.trip[tripIndex].tripPoint[x]);
			}
            else if (isEnd) {
                mapEnd = populateTripEndPoints("map-end", savedTrips.trips.trip[tripIndex].tripPoint[x]);
            } else {            
                var tripPoint = savedTrips.trips.trip[tripIndex].tripPoint[x];
                populateTripStops(tripPoint.streetAddress1,tripPoint.streetAddress2,tripPoint.city,tripPoint.state,tripPoint.country,tripPoint.zip);
            }						
		}
	}	
}

function populateTripEndPoints(id, tripPoint) {    
    var addressList = $('#' + id).parent().siblings('ol');
	var map = new GMap2(document.getElementById(id));
	map.addControl(new GSmallMapControl());
	addressList.find(".street1").val(tripPoint.streetAddress1);	
	addressList.find(".street2").val(tripPoint.streetAddress2);
	addressList.find(".city").val(tripPoint.city);
	addressList.find(".state select").val(jQuery.trim(tripPoint.state));
	addressList.find(".country select").val(jQuery.trim(tripPoint.country));
	addressList.find(".zip").val(tripPoint.zip); 	
    return map; 
}

function populateTripStops(streetAddress1, streetAddress2,city,state, country, zip) {    	
    $('.step2 li.clear:first .street1-s input').val(jQuery.trim(streetAddress1));
	$('.step2 li.clear:first .street2-s input').val(jQuery.trim(streetAddress2));
	$('.step2 li.clear:first .city-s input').val(jQuery.trim(city));	
	$('.step2 li.clear:first .state select').val(jQuery.trim(state));
	$('.step2 li.clear:first .country select').val(jQuery.trim(country));
	$('.step2 li.clear:first .zip-s input').val(jQuery.trim(zip)); 
	//routeData();	
	var stopAddr = streetAddress1 + ' '+ streetAddress2 + ' ' 
	               + city + ' '+ state + ' '+ country + ' '+ zip;	
	var displayAddress = "";

	if ($('.step2 li.clear:first .street1-s input').val() != "" && $('.step2 li.clear:first .city-s input').val() != "" && $('.step2 li.clear:first .state select').val() != "" && $('.step2 li.clear:first .street2-s input').val() != "") {
            displayAddress =
				$('.step2 li.clear:first .street1-s input').val() + ' ' +
				$('.step2 li.clear:first .street2-s input').val() + ', ' +
				$('.step2 li.clear:first .city-s input').val() + ', ' +
				$('.step2 li.clear:first .state select').val();
	} else if ($('.step2 li.clear:first .street1-s input').val() != "" && $('.step2 li.clear:first .city-s input').val() != "" && $('.step2 li.clear:first .state select').val() != "") {
		    displayAddress =
				$('.step2 li.clear:first .street1-s input').val() + ', ' +
				$('.step2 li.clear:first .city-s input').val() + ', ' +
				$('.step2 li.clear:first .state select').val();
	} else if ($('.step2 li.clear:first .city-s input').val() != "" && $('.step2 li.clear:first .state select').val() != "") {
            displayAddress =				
				$('.step2 li.clear:first .city-s input').val() + ', ' +
				$('.step2 li.clear:first .state select').val();
        }
	$('.step2 li.clear:first').find('.stop-address').text(displayAddress);	
	var newMenu = $('.step2 li.clear:first').clone(true);	
	/*** Increment and Reload Forms ***/
	for (var x = 0; x < $(newMenu).find('label').length; x++) {
		$(newMenu).find('label:eq(' + x + ')').attr("for", $(newMenu).find('label:eq(' + x + ')').attr("for").replace(/[0-9]$/, "") + (parseFloat($(newMenu).find('.stop-num').text()) + 1));
		if ($(newMenu).find('label:eq(' + x + ')').siblings('input').length != 0)
		    $(newMenu).find('label:eq(' + x + ')').parent().children('input').attr("name", $(newMenu).find('label:eq(' + x + ')').parent().children('input').attr("name").replace(/[0-9]$/, "") + (parseFloat($(newMenu).find('.stop-num').text()) + 1));
    }	
   
	/*** Transition ***/
	$(newMenu).height(0);	
	$('.step2 li.clear:first').before(newMenu);
	/*** Increment and Create Gmap ***/
	$(newMenu).find('.mapperwrapper').children().eq(0).attr("id", $('.step2 li.clear').find('.mapperwrapper').children().eq(0).attr("id").replace(/[0-9]$/, "") + (parseFloat($(newMenu).find('.stop-num').text()) + 1));
	mapStops[parseFloat($(newMenu).find('.stop-num').text())] = new GMap2(document.getElementById($(newMenu).find('.mapperwrapper').children().eq(0).attr("id")));
	mapStops[parseFloat($(newMenu).find('.stop-num').text())].setCenter(new GLatLng(68.0, -155.0), 2);	
	mapStops[parseFloat($(newMenu).find('.stop-num').text())].addControl(new GSmallMapControl());	
	
	var mapStop = parseFloat($(newMenu).find('.stop-num').text()) - 1;
	/*** Increment Stop Number ***/
    $(newMenu).find('.stop-num').text(parseFloat($(newMenu).find('.stop-num').text()) + 1);	
	$(newMenu).css('height', '316px');
	$(newMenu).css('display', 'block');    	
    mapStops[mapStop].checkResize();	
	var stopIndex = 1;	
	$('.change').click(function() {        
        geocoder.getLocations(displayAddress, function(result) {			    
                if (result && result.Status.code == 200) {					
                    mapStops[mapStop].clearOverlays();
					var lat = result.Placemark[0].Point.coordinates[1];
					var lng = result.Placemark[0].Point.coordinates[0];
					var point=new GLatLng(lat,lng);
					mapStops[mapStop].setCenter(point, 13);
					var icon = new GIcon();
					icon.image = "/images/map-marker_stop.png";							
			        icon.iconSize = new GSize(37, 28);
			        icon.iconAnchor = new GPoint(13, 25);      					
					var marker = new GMarker(point, icon);
					mapStops[mapStop].checkResize();
					mapStops[mapStop].addOverlay(marker);						
                    routeData();                    
                } else {
                    alert("Sorry, we couldn't find " + address + ".  Please double check the address.");
                }		
			});			      		
		//$(this).siblings('legend').children('.stop-address').text('');
	});
    	
	$('.step2 li.clear:eq('+stopIndex+')').css('height', '45px');
	$('.step2 li.clear:eq('+stopIndex+')').css('marginTop', '10px');
	$('.step2 li.clear:eq('+stopIndex+')').css('marginBottom', '0');	
	$('.step2 li.clear:eq('+stopIndex+')').css('opacity', '1');
	$('.step2 li.clear:eq('+stopIndex+')').children('.trip-display-highlight').css('height', '30px');	
	$('.step2 li.clear:eq('+stopIndex+')').children('.trip-display-highlight').css({ backgroundPosition: '0 -250px' });	
	$('.step2 li.clear:eq('+stopIndex+')').children('.trip-display-highlight').css('display', 'block');	
		
	$('.step2 li.clear:eq('+stopIndex+')').find('.stop-address').css('display', 'inline');
	$('.step2 li.clear:eq('+stopIndex+')').find('.remove').css('display', 'inline');
	$('.step2 li.clear:eq('+stopIndex+')').find('.change').css('display', 'inline');
	
    $('.step2 li.clear:first .street1-s input').val("");
	$('.step2 li.clear:first .street2-s input').val("");
	$('.step2 li.clear:first .city-s input').val("");
	//$('.step2 li.clear:first .state select').val("");
	$('.step2 li.clear:first .country select').val("USA");
	$('.step2 li.clear:first .zip-s input').val(""); 			    
}

//method to get query string parameters
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/* NOTE: IF ANY FIELD NAME or THE ORDER OF THE ELEMENTS IN THE HTML CHANGES, THESE 2 FUNCTIONS WOULDNT WORK PROPERLY */
function populateTripFromCookie() {    
    var tripCookie = $.cookie('trip');
    var tripelements = tripCookie.split(",");

    //populate map start
    var start = tripelements[0].split("|");
    mapStart = populateTripStartAndEnd("map-start", start);
    
    //populate map end
    var end = tripelements[tripelements.length - 1].split("|");
    mapEnd = populateTripStartAndEnd("map-end", end);

    //populate map stops
    var stopNum = 1;
    for (var x = 0; x < tripelements.length; x++) {
        if (x > 0 && x < (tripelements.length - 1)) {
            var address = new String(tripelements[x]);
            var streetAddress1;
            var streetAddress2;
            var city;
            var state;
            var zip;
            var addressArr = address.split('|');            
            for (var y = 0; y < addressArr.length; y++) {
                if (y == 0) {
                    streetAddress1 = addressArr[y];                    
                } else if (y == 1) {
                    streetAddress2 = addressArr[y];                    
                } else if (y == 2) {
                    city = addressArr[y];                    
                } else if (y == 3) {
                    state = addressArr[y];                    
                } else if (y == 4) {
                    country = addressArr[y];                    
                } else if (y == 5) {
                    zip = addressArr[y];                    
                }
            }                       
            populateTripStops(streetAddress1, streetAddress2, city, state,country, zip);
            stopNum++;
        }
    }
    showAddress("map-start", mapStart);
    showAddress("map-end", mapEnd);
    routeData();
    running = false;
    saveStopsG = true;        
    return false;         
}

function populateTripStartAndEnd(id, tripPoint) {
    var addressList = $('#' + id).parent().siblings('ol');
    var map = new GMap2(document.getElementById(id));
    map.addControl(new GSmallMapControl());
    addressList.find(".street1").val(tripPoint[0]);
    addressList.find(".street2").val(tripPoint[1]);
    addressList.find(".city").val(tripPoint[2]);
	addressList.find(".state").children('select').val(jQuery.trim(tripPoint[3]));
	addressList.find(".country").children('select').val(jQuery.trim(tripPoint[4]));
    addressList.find(".zip").val(tripPoint[5]);
    return map;
}
/* Gets the location ID for every stop, then populates the stop list on Step 3 */
var distSoFar;
function getLocationID(num, addy, city, state) {
    locationID = "-1";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/SearchSvc.asmx/GetLocationIDByCityAndState",
        dataType: "json",
        data: "{'city':'" + city + "','state':'" + state + "'}",
        success:
           function(msg) {
               locationID = JSON.parse(msg);
               //console.log(locationID);
			   
			   switch(num) {
					case 0:
						if (locationID == "-1" || locationID == undefined)
		                    $('.route .start').html('Start at ' + addy);
		                else
		                    $('.route .start').html('Start at ' + addy + " <a href='" + resportalURL + "&locationID=" + locationID + "'>Find Nearby Red Roof Inns</a>");
						break;
					case 'last':
		                if (locationID == "-1" || locationID  == undefined)
		                    $('.route .end').html('Arrive in ' + addy);
		                else
		                    $('.route .end').html('Arrive in ' + addy + " <a href='" + resportalURL + "&locationID=" + locationID + "'>Find Nearby Red Roof Inns</a>");
						break;
					default:
						if (num > 0) {
							if(num == 1) {
								distSoFar = 0;
							}
		                    var ttlDist = directions.getDistance().meters;
		                    var addDist = directions.getRoute((num-1)).getDistance().meters;
							
	                        if (locationID == "-1" || locationID == undefined)
	                            $('.route ol').append('<li>Stop in ' + addy + '</li>');
	                        else
	                            $('.route ol').append('<li>Stop in ' + addy + "<a href='" + resportalURL + "&locationID=" + locationID + "'>Find Nearby Red Roof Inns</a></li>");
							
							var currStop = $('.route ol li:last');
							var prevStop = $('.route ol li:last').prev();
							
	                        if ((((distSoFar + addDist) / ttlDist) * 278) < ((distSoFar / ttlDist) * 278) + 30 && num > 1)
	                            currStop.css("top",
									((distSoFar / ttlDist) * 278) + 30 + "px");
	                        else
	                            currStop.css("top",
									(((distSoFar + addDist) / ttlDist) * 278) + "px");

							if (prevStop.length != 0 && currStop.position().top < prevStop.position().top+30)
								currStop.css("top", prevStop.position().top+30 + "px");
							if (currStop.position().top > 251)
								currStop.css("top", "251px");

	                        distSoFar = distSoFar + addDist;
		                }
						break;

			   }
           },
        error:
            function(XMLHttpRequest, textStatus, errorThrown) {
                console.log(":" + XMLHttpRequest.responseText);
                var response = JSON.parse(XMLHttpRequest.responseText);
                if (response.Message) {
                    console.log(response.Message);
                }
            }
    });
}