﻿/*
@class ViaMapController
*/

$(window).unload( GUnload );

// Cluster Pin Image
var clusterPin;

function correctCluster() {
	if ($('#costco').is(':checked')) {
		Clusterer.defaultIcon.image = 'images/coffees/via_map/cluster_costco.png';
		clusterPin = 'images/coffees/via_map/cluster_costco.png';
	}

	if ($('#events').is(':checked')) {
		Clusterer.defaultIcon.image = 'images/coffees/via_map/cluster_event.png';
		clusterPin = 'images/coffees/via_map/cluster_event.png';
	}

	if ($('#target').is(':checked')) {
		Clusterer.defaultIcon.image = 'images/coffees/via_map/cluster_target.png';
		clusterPin = 'images/coffees/via_map/cluster_target.png';
	}

	if ($('input#stores').is(':checked')) {
		Clusterer.defaultIcon.image = 'images/coffees/via_map/cluster.png';
		clusterPin = 'images/coffees/via_map/cluster.png';
	}
}

// VIA Map Controller
var ViaMapController = {
	_dataCache: null,
	_mapInstance: null,
	_clusterer: null,
	_allStoresMarkers: [],
	_allEventsMarkers: [],
	_allTargetMarkers: [],
	_allCostcoMarkers: [],
	_cities: new Array(),
	init: function() {

		var controller = ViaMapController;

		$('#seattle, #chicago').click(function(evt) {
			controller._mapInstance.panTo(controller._cities[this.value].gLatLng);
			controller._mapInstance.setZoom(14);
		});

		$('#seattle').click(function(evt) {
			controller._clusterer.SetMaxVisibleMarkers(60);
		});

		$('#unitedkingdom').click(function(evt) {
			controller._mapInstance.panTo(controller._cities[this.value].gLatLng);
			controller._mapInstance.setZoom(11);
			controller._clusterer.SetMaxVisibleMarkers(20);
		});

		$('input[name="via-content"]').click(function(evt) {
			controller.filter({
				id: this.id,
				value: this.checked
			}); // Throw click value into getLocationData method

			correctCluster();
		});

		controller._cities = {
			'chicago': {
				state: 'IL',
				gLatLng: new GLatLng(41.881128, -87.636394)
			},
			'seattle': {
				state: 'WA',
				gLatLng: new GLatLng(47.614053, -122.340853)
			},
			'unitedkingdom': {
				state: '',
				gLatLng: new GLatLng(51.470088, -0.206108)
			}
		};

		if (GBrowserIsCompatible()) {
			this._mapInstance = new GMap2(document.getElementById("map"));
			this._mapInstance.addControl(new GLargeMapControl());

			this._mapInstance.setCenter(controller._cities[controller.getSelectedLocation()].gLatLng, 14);
			this._mapInstance.enableDoubleClickZoom();

			this._clusterer = new Clusterer(this._mapInstance);

			correctCluster();
			this._clusterer.SetIcon( clusterPin );

			window.setTimeout(function() {
				controller.getData();
			}, 0);
		}
	},
	getData: function() {
		var controller = this;
		var filters = controller.getOptions();
		var params = {};
		var icon;
		var posn;
		var marker;

		// Stores
		if (filters.stores) {
			//Consume the stores service, passing the location=chicago|seatle|unitedkingdom
			var storesJson = 'api/viaStores.ashx?long1=-87.636394&lat1=41.881128&long2=-122.347853&lat2=47.615653&long3=-0.206108&lat3=51.511988&radius=50&feature=VIA';
			$.getJSON(storesJson, params, function(data) {
				$.each(data.GetStoresByGeocodeAndFeaturesResult, function(i, item) {
					var type = 'store';
					icon = controller.getIcon([type, 'shadow']);
					posn = new GLatLng(+item.WalkInAddress.Coordinates.Latitude, +item.WalkInAddress.Coordinates.Longitude);
					marker = controller.createMarker(posn, icon, item, type);
					controller._clusterer.AddMarker(marker, item.Name);
					controller._allStoresMarkers.push(marker);
				});
			});
		}

		// Events
		if (filters.events) {
			//Consume the events web service.
			var eventsJson = 'api/viaEvents.ashx';
			$.getJSON(eventsJson, params, function(data) {
				$.each(data.d, function(i, item) {
					var type = 'event';
					icon = controller.getIcon([type, 'shadow']);
					posn = new GLatLng(+item.Latitude, +item.Longitude);
					marker = controller.createMarker(posn, icon, item, type);
					controller._clusterer.AddMarker(marker, item.Name);
					controller._allEventsMarkers.push(marker);
				});
			});
		}

		// Target
		if (filters.target) {
			var targetJson = 'api/data/target.json';
			$.getJSON(targetJson, params, function(data) {
				$.each(data.GetStoresByGeocodeAndFeaturesResult, function(i, item) {
					var type = 'target';
					icon = controller.getIcon([type, 'shadow']);
					posn = new GLatLng(+item.WalkInAddress.Coordinates.Latitude, +item.WalkInAddress.Coordinates.Longitude);
					marker = controller.createMarker(posn, icon, item, type);
					controller._clusterer.AddMarker(marker, item.Name);
					controller._allTargetMarkers.push(marker);
				});
			});
		}

		// Costco
		if (filters.costco) {
			var costcoJson = 'api/data/costco.json';
			$.getJSON(costcoJson, params, function(data) {
				$.each(data.GetStoresByGeocodeAndFeaturesResult, function(i, item) {
					var type = 'costco';
					icon = controller.getIcon([type, 'shadow']);
					posn = new GLatLng(+item.WalkInAddress.Coordinates.Latitude, +item.WalkInAddress.Coordinates.Longitude);
					marker = controller.createMarker(posn, icon, item, type);
					controller._clusterer.AddMarker(marker, item.Name);
					controller._allCostcoMarkers.push(marker);
				});
			});
		}
	},
	createMarker: function(posn, icon, place, type) {
		var title = '';
		var id = -1;
		var controller = this;

		if (type === 'store' || type === 'target' || type === 'costco') {
			title = place.Name;
			id = +place.StoreNumber;
		} else if (type === 'event') {
			title = place.Name;
			id = +place.EventID;
		}

		var marker = new GMarker(posn, {
			title: title,
			icon: icon,
			draggable: false
		});

		GEvent.addListener(marker, 'click', function() {
			var images = controller.getImages(id, type);
			var bubbleHtml = controller.getBubbleHtml(title, images, place, type, id);
			marker.openInfoWindowHtml(bubbleHtml, { maxWidth: 400 });
		});
		return marker;
	},
	filter: function(obj) {
		// Add and remove markers
		var controller = this;

		// Stores
		if (obj.id === 'stores') {
			if (!obj.value) {
				controller.removeMarkers($(controller._allStoresMarkers));
			} else {
				controller.addMarkers($(controller._allStoresMarkers));
			}
		}

		// Events
		if (obj.id === 'events') {
			if (!obj.value) {
				controller.removeMarkers($(controller._allEventsMarkers));
			} else {
				controller.addMarkers($(controller._allEventsMarkers));
			}
		}

		// Target
		if (obj.id === 'target') {
			if (!obj.value) {
				controller.removeMarkers($(controller._allTargetMarkers));
			} else {
				controller.addMarkers($(controller._allTargetMarkers));
			}
		}

		// Costco
		if (obj.id === 'costco') {
			if (!obj.value) {
				controller.removeMarkers($(controller._allCostcoMarkers));
			} else {
				controller.addMarkers($(controller._allCostcoMarkers));
			}
		}
	},
	addMarkers: function(markerAry) {
		var controller = this;
		markerAry.each(function() {
			controller._clusterer.AddMarker(this, this.title);
		});
	},
	removeMarkers: function(markerAry) {
		var controller = this;
		markerAry.each(function() {
			controller._clusterer.RemoveMarker(this);
		});
	},
	getImages: function(id, type) {
		var myImages = [];
		var myUrl = 'api/viaGalleryImages.ashx';
		// get images xml from cs
		$.ajax({
			type: "GET",
			url: myUrl,
			dataType: "xml",
			data: "tags=" + type + '_' + id,
			async: false,
			success: function(xml) {
				$(xml).find('photo').each(function() {
					myImages.push($(this).find('imageURL').text());
				});
			}
		});
		return myImages;
	},
	getIcon: function(images) {
		var icon = null;
		// create custom icons
		if (images) {
			icon = new GIcon(G_DEFAULT_ICON);
			icon.image = "images/coffees/via_map/" + images[0] + ".png";
			icon.iconSize = new GSize(18, 28);
			//icon.transparent = "images/viamap/" + images[0] + "_trans.png";
			icon.shadow = "images/coffees/via_map/" + images[1] + ".png";
			icon.shadowSize = new GSize(28, 28);
		}
		return icon;
	},
	// Function: returns value of selected radio location
	getSelectedLocation: function() {
		var locs = $('input[name="location"]');
		for (var i = 0, len = locs.length; i < len; i++) {
			if (locs[i].checked) { return locs[i].value; }
		}
	},
	getOptions: function() {
		// Fetch the checkboxes
		var chks = $('input[name="via-content"]');
		var hash = {};
		for (var i = 0, len = chks.length; i < len; i++) {
			if (chks[i].checked) { hash[chks[i].id] = true; }
		}
		return hash;
	},
	getBubbleHtml: function(title, images, place, type, id) {
		var retVal = '';
		var desc = '';
		var cssClass = 'viaMapBubble ';
		var controller = this;

		if (images.length === 0) {
			cssClass += ' noImages';
		}
		retVal += '<div class="' + cssClass + '">';
		retVal += '<h3 title="' + id + '">' + title + '</h3>';

		// if we have images
		if (images.length > 0) {
			retVal += '<div class="viaMapBubbleImgs">';
			retVal += '<div>';
			for (var i = 0; i < images.length; i++) {
				if (i === 0) {
					retVal += '<img class="activeimg" src="' + images[i] + '">';
				} else {
					retVal += '<img src="' + images[i] + '">';
				}
			}
			retVal += '</div>';
			retVal += '<a href="#prev" onclick="getBubbleImg(\'prev\', this);return false;" class="inactive btnprev">Prev</a>';
			retVal += '<a href="#next" onclick="getBubbleImg(\'next\', this);return false;" class="isactive btnnext">Next</a>';
			retVal += '</div>';
		}
		retVal += '<div class="viaMapBubbleContent">';

		// show date and time for events
		if (place.StartDate && place.EndDate) {
			var startTime = controller.getEventDate(place.StartDate);
			var endTime = controller.getEventDate(place.EndDate);

			var startSplit = startTime.split(' ');
			var endSplit = endTime.split(' ');

			if (startSplit[1] === endSplit[1]) {
				retVal += '<p class="date">' + startSplit[0] + ' ' + startSplit[1] + ' ' + startSplit[2] + ' ' + startSplit[3] + ' &ndash; ' + endSplit[3] + '</p>';
			} else {
				retVal += '<p class="date">' + startTime + ' &ndash;<br />' + endTime + '</p>';
			}
		}

		var tmpAddr;
		if (type === 'store' || type === 'target' || type === 'costco') {
			desc = place.WalkInAddress.Line1 + '<br />';
			desc += place.WalkInAddress.City + ', ' + place.WalkInAddress.State + ' ' + place.WalkInAddress.PostalCode + '<br />';
			desc += place.PhoneNumber + '<br /><br />';

			if (place.FacilityID) {
				desc += '<a href="http://www.starbucks.com/Retail/Find/storedetails.aspx?sid=' + place.FacilityID + '">Details</a> | ';
			}

			tmpAddr = place.WalkInAddress.Line1.replace(/ /, "+");
			desc += '<a href="http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=&amp;daddr=' + tmpAddr + '+' + place.WalkInAddress.City + '+' + place.WalkInAddress.PostalCode + '" target="_blank">Get Directions</a>';
		} else if (type === 'event') {
			desc = place.Description + '<br /><br />';

			// Address
			var descAddress;
			if (place.AddressLine2) {
				descAddress = place.AddressLine1 + '<br />' + place.AddressLine2 + '<br />';
			} else {
				descAddress = place.AddressLine1 + '<br />';
			}

			// City
			var descCity;
			if (place.City) {
				descCity = place.City + ', ';
			} else {
				descCity = '';
			}

			// CountrySubdivision
			var descCountrySubdivision;
			if (place.CountrySubdivision === 'Illinois') {
				descCountrySubdivision = 'IL';
			} else if (place.CountrySubdivision === 'Washington') {
				descCountrySubdivision = 'WA';
			} else {
				descCountrySubdivision = '';
			}

			// PostalCode
			var descPostalCode;
			if (place.PostalCode) {
				descPostalCode = ' ' + place.PostalCode;
			} else {
				descPostalCode = '';
			}

			var fullAddress = descAddress + descCity + descCountrySubdivision + descPostalCode + '<br /><br />';
			desc += fullAddress;

			tmpAddr = fullAddress.replace(/<br \/>/g, " ").replace(/ /g, "+").replace(/\+\+/g, "");
			desc += '<a href="http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=&amp;daddr=' + tmpAddr + '" target="_blank">Get Directions</a>';
		}
		retVal += '<p>' + desc + '</p>';
		retVal += '</div>';
		retVal += '</div>';

		return retVal;
	},
	getEventDate: function(dateJson) {
		var d = eval('new' + dateJson.replace(/\//g, ' '));
		var curr_date = d.getDate();

		var weekday = ['Sun.','Mon.','Tue.','Wed.','Thu.','Fri.','Sat.'];
		var dayofweek = weekday[d.getDay()];

		var month = ['1','2','3','4','5','6','7','8','9','10','11','12'];
		var curr_month = month[d.getMonth()];

		var curr_year = d.getFullYear();
		var year = curr_year.toString().substring(2);

		var curr_hours = d.getHours();
		var timePeriod;
		if (curr_hours > 11) {
			curr_hours = curr_hours - '12';
			timePeriod = 'pm';
		} else {
			timePeriod = 'am';
		}
		var curr_mins = d.getMinutes() + 1;
		if (curr_mins === 60) {
			curr_mins = '00';
			curr_hours = curr_hours + 1;
		}

		return (dayofweek + ' ' + curr_month + '/' + curr_date + '/' + year + ' <abbr>@</abbr> ' + curr_hours + ':' + curr_mins + timePeriod);
	},
	clearMarkers: function() {
		this._mapManagerInstance.clearMarkers();
	},
	showLoadingScreen: function() {

	},
	hideLoadingScreen: function() {

	}
};

function showNav(curIndex, btnPrev, btnNext, imgLength) {
	if (curIndex > 0) {
		if ($(btnPrev).hasClass('inactive')) { $(btnPrev).removeClass('inactive'); }
		$(btnPrev).addClass('isactive');
	} else {
		if ($(btnPrev).hasClass('isactive')) { $(btnPrev).removeClass('isactive'); }
		$(btnPrev).addClass('inactive');
	}

	if (curIndex < imgLength) {
		if ($(btnNext).hasClass('inactive')) { $(btnNext).removeClass('inactive'); }
		$(btnNext).addClass('isactive');
	} else {
		if ($(btnNext).hasClass('isactive')) { $(btnNext).removeClass('isactive'); }
		$(btnNext).addClass('inactive');
	}
}

function getBubbleImg(dir, anch) {
	var container = $(anch).parent();
	var myImgs = $(container).find('img');
	var btnPrev = $(container).find('a.btnprev').get(0);
	var btnNext = $(container).find('a.btnnext').get(0);
	var curIndex = 0;

    myImgs.each(function(i) {
		if ($(this).hasClass('activeimg')) {
			curIndex = i;
			$(this).removeClass('activeimg');
		}
	});

	if (dir === 'next') {
		if (curIndex < (myImgs.length - 1)) {
			curIndex++;
		}
	} else if (dir === 'prev') {
		if (curIndex > 0) {
			curIndex--;
		}
	}
	showNav(curIndex, btnPrev, btnNext, myImgs.length - 1);
	$(myImgs[curIndex]).addClass('activeimg');
}