var DRIVER_ID_ARRAY = new Array('A','B');
var DRIVER_ARRAY = new Array();
var MARKER_ARRAY = new Array();
var INFO_WINDOW_ARRAY = new Array();

var closeInfoWindows = function() {
    for (var i = 0; i < INFO_WINDOW_ARRAY.length; i++) {
        INFO_WINDOW_ARRAY[i].close();
    }
}

var initializeMap = function() {
	
	var myLatlng = new google.maps.LatLng(38.6110, -95.6845);
	var myOptions = {
		zoom: 4,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	var DriverMarker = function(DriverID) {
		var self = this;
                var questionMarkHour = 6;
                var disappearHour = 24;
		this.ID = DriverID;
		//this.request = 'shareathon.cfc?method=getCupcakeCar&_cf_nodebug=true&_cf_nocache=true&ID=' + self.ID;
		//this.request = '/pages/brite_kite?ID=' + self.ID;
		this.request = '/javascripts/data/brightkite.' + self.ID + '.json';
		//self.request = 'http://brightkite.com/people/' + self.ID + '/objects.json';
		this.status = null;
		this.image = null;
		this.shape = null;
		this.marker = null;
		this.infowindow = null;
		this.data = null;
		
		this.setData = function(rawData) {
                    //alert(rawData);
                    self.data = eval(eval('(' + rawData + ')'));
                    //alert(self.data);
                    self.checkIn();
		}
		
		this.loadData = function () {
                    $.ajax({
                        type: "POST",
                        url: self.request,
                        data: '',
                        datatype: "json",
                        async: false,
                        success: self.setData
                    });
		}
		
		this.checkIn = function() {
                    var checkin = null;
                    var note = null;
                    var photo = null;
                    var currenthour = Math.round(new Date().getTime()/1000/60/60);
                    var i = 0;

                    while (i < self.data.length) {

                            if (self.data[i].object_type == 'note' && note == null) {

                                    note = self.data[i];
                                    note.date = new Date(note.created_at);
                                    note.hour = Math.round(note.date.getTime()/1000/60/60);

                            } else if (self.data[i].object_type == 'photo' && photo == null) {

                                    photo = self.data[i];
                                    photo.date = new Date(photo.created_at);
                                    photo.hour = Math.round(photo.date.getTime()/1000/60/60);

                            } else if (self.data[i].object_type == 'checkin' && checkin == null) {

                                    checkin = self.data[i];
                                    checkin.date = new Date(checkin.created_at);
                                    checkin.hour = Math.round(checkin.date.getTime()/1000/60/60);
                                    checkin.note = null;
                                    checkin.photo = null;

                            }

                            if (checkin != null && note != null && photo != null) {
                                    i = self.data.length;
                            } else {
                                    i++;
                            }

                    }

                    if (checkin != null) {

                        if (Math.abs(checkin.hour - currenthour) < disappearHour) {
                                // set the icon for the car marker
                                checkin.icon = 'images/car_icon.png';
                                if (Math.abs(checkin.hour - currenthour) > questionMarkHour) {
                                        checkin.icon = 'images/car_shadow_icon.png';
                                }

                                if (note != null) {
                                        // if the note was recent enough, add it to the checkin object
                                        if (Math.abs(checkin.hour - note.hour) < 3 && note.place.name == checkin.place.name) {
                                                checkin.note = note;
                                                note = null;
                                        }
                                }

                                if (photo != null) {
                                        if (Math.abs(checkin.hour - photo.hour) < 3 && photo.place.name == checkin.place.name) {
                                                checkin.photo = photo;
                                                photo = null;
                                        }

                                }

                                self.status = checkin;
                                self.setMarker();
                        }
                    }
                }
									
		this.setMarker = function () {
				
                    var latlng = new google.maps.LatLng( self.status.place.latitude, self.status.place.longitude );
                    var contentString = 'Location: ' + self.status.place.name;
                    var arrayLen = MARKER_ARRAY.length;

                    if (self.status.note != null) {
                            contentString += '<br />' + self.status.note.body;
                    }

                    if (self.status.photo != null) {
                            contentString += '<br /><img src="'+ self.status.photo.photo + '" /><br />' + self.status.photo.body;
                    }

                    self.image = new google.maps.MarkerImage(self.status.icon,
                                                    // This marker is 44 pixels wide by 34 pixels tall.
                                                    new google.maps.Size(44, 34),
                                                    // The origin for this image is 0,0.
                                                    new google.maps.Point(0,0),
                                                    // The anchor for this image is the bottom left end of the car 0,32.
                                                    new google.maps.Point(0, 34)
                    );

                    self.shape = {
                            coord: [31,1,14,1,1,14,1,19,1,26,5,29,19,31,24,32,28,28,36,23,40,25,43,20,41,9,38,1,31,1],
                            type: 'poly'
                    };

                    if (self.marker == null) {

                            MARKER_ARRAY[arrayLen] = new google.maps.Marker({
                                    position: latlng,
                                    map: map,
                                    icon: self.image,
                                    shape: self.shape,
                                    title: self.status.place.name,
                                    zIndex: arrayLen + 1
                            });

                            self.marker = MARKER_ARRAY[arrayLen];

                    } else { // marker already exists

                            self.marker.setPosition(latlng);

                    }

                    self.infowindow = new google.maps.InfoWindow({
                                    content: contentString,
                                    //disableAutoPan: true,
                                    maxWidth: 220
                    });

                    INFO_WINDOW_ARRAY[INFO_WINDOW_ARRAY.length] = self.infowindow;

                    google.maps.event.addListener(self.marker, 'click', function() {
                            closeInfoWindows();
                            self.infowindow.open(map,self.marker);
                    })
            }
	}
	// end loadCarMarkers
	
	var loadCars = function() {
		for (var i = 0; i < DRIVER_ID_ARRAY.length; i++) {
			DRIVER_ARRAY[i] = new DriverMarker(DRIVER_ID_ARRAY[i]);
			DRIVER_ARRAY[i].loadData();
		}
	}
	
	var loadDestinationMarkers = function() {
		var request = "/destinations.xml";
                var tourListMax = 5;
                var tourListCount = 0;
		
		$.get(request, {}, function(data) {
			$(data).find("marker").each(function(i) {
				var icon;
                                var inTourList = false;
                                var isPastDate = false;
                                var arrayLen = MARKER_ARRAY.length;
				var marker = $(this);
				var latlng = new google.maps.LatLng(parseFloat(marker.attr("lat")), parseFloat(marker.attr("lng")));
				var endDate = new Date(marker.attr("enddate"));
                                var tempDate = new Date();
								var curDate = new Date(tempDate.getFullYear(),tempDate.getMonth(),tempDate.getDate());
								var dateSpanString = 'Coming soon!';


                                if (curDate - endDate > 0) {
                                    isPastDate = true;
                                }

                                if (isPastDate) {
                                    icon = new google.maps.MarkerImage('images/cupcakered.png',
                                                                    // This marker is 44 pixels wide by 34 pixels tall.
                                                                    new google.maps.Size(30, 30),
                                                                    // The origin for this image is 0,0.
                                                                    new google.maps.Point(0,0),
                                                                    // The anchor for this image is the bottom left end of the car 0,32.
                                                                    new google.maps.Point(5, 25)
                                    );
                                } else {
                                    icon = new google.maps.MarkerImage('images/cupcakeblue.png',
                                                                    // This marker is 44 pixels wide by 34 pixels tall.
                                                                    new google.maps.Size(30, 30),
                                                                    // The origin for this image is 0,0.
                                                                    new google.maps.Point(0,0),
                                                                    // The anchor for this image is the bottom left end of the car 0,32.
                                                                    new google.maps.Point(5, 25)
                                    );
                                }

                                if (tourListCount < tourListMax && !isPastDate) {
                                    dateSpanString = marker.attr("startdate") + ' – ' + marker.attr("enddate");
                                    inTourList = true;
                                } else if (isPastDate) {
                                    dateSpanString = "Sorry, we've already visited this location";
                                }

				var contentString = '<div style="text-align:center"><strong>';
                                    contentString += marker.attr("location") + '</strong><br />';
                                    contentString += dateSpanString;
                                    if (marker.attr("message") != '' && dateSpanString != 'Coming soon!') {
                                        contentString += '</div><hr /><div style="text-align:left">' + marker.attr("message");
                                    }
                                    contentString += '</div>';
				
				//var formattedStartDate = $.datepicker.formatDate('DD, MM d, yy',new Date(marker.attr("startdate")));
				
				if (inTourList) {
					$("#tourList").append('<li class="tourBox tourDateItem' + (i % 2 == 0 ? ' odd' : '') + '"><span class="tourLocation">' + marker.attr("location") +'</span><br />' + dateSpanString + '</li>');
                                        tourListCount++;
				}

                                if (isPastDate) {
                                    icon = 'images/cupcakered.png';
                                }
				
				//var marker = new google.maps.Marker({position: latlng, map: map});
				MARKER_ARRAY[arrayLen] = new google.maps.Marker({
					position: latlng,
					map: map,

                                        icon: icon,
					title: marker.attr('location'),
					zIndex: 1
				});

                                
                                var infowindow = new google.maps.InfoWindow({
                                                content: contentString,
                                                //disableAutoPan: true,
                                                maxWidth: 220
                                });

                                INFO_WINDOW_ARRAY[INFO_WINDOW_ARRAY.length] = infowindow;

                                google.maps.event.addListener(MARKER_ARRAY[arrayLen], 'click', function() {
                                        closeInfoWindows();
                                        infowindow.open(map,MARKER_ARRAY[arrayLen]);
                                });

                                if (inTourList) {
                                    $("#tourList > :last").bind('click',function() {
                                        closeInfoWindows();
                                        infowindow.open(map,MARKER_ARRAY[arrayLen]);
                                    });
                                }
			});
			loadCars();
		});
	}
	// end loadDestinationMarkers
	
	loadDestinationMarkers();
	
}