/**
 * Wyndham HF Brand Map
 * 
 * Displays a google map with clustered markers for one brand.
 * Clicking a marker displays a custom info window
 * 
 * Dependencies:
 * 	MapIconMaker (GMap Utility)
 * 	MarkerCluster (GMap Utility)
 * 	EXtInfoWindow (GMap Utility)
 * 	jQuery
 */

var map;
//Global brand colours (for icons)
var brandColour = [];
brandColour["BU"] = "#004cac";
brandColour["BH"] = "#b2031e";
brandColour["DI"] = "#45a0db";
brandColour["HJ"] = "#ff6c00";
brandColour["MT"] = "#002480";
brandColour["KG"] = "#0a35a4";
brandColour["RA"] = "#d30540";
brandColour["SE"] = "#f5ea02";
brandColour["TL"] = "#002480";
brandColour["WG"] = "#7aba42";
//Global brand names (for file paths)
var brandNames = [];
brandNames["BU"] = "baymont";
brandNames["BH"] = "hawthorn";
brandNames["DI"] = "daysInn";
brandNames["HJ"] = "howardJohnson";
brandNames["KG"] = "knightsInn";
brandNames["MT"] = "microtel";
brandNames["RA"] = "ramada";
brandNames["SE"] = "super8";
brandNames["TL"] = "travelodge";
brandNames["WG"] = "wingate";

$(document).ready(function(){
	$('.show-brandmap').click(function(){
		//Brand abbreviation is the class of the map div
		loadmap($('#map').attr('class'));
	});	
});

$(window).unload(function(){
	//prevent memory leaks 
	GUnload(); 
});

/**
 * Initialize the Google Map
 * Displays one brand at a time
 * @param String brand - 2 character brand abbreviation
 */
function loadmap(brand){
	var styles = getClusterStyles(brand);
	
    if (GBrowserIsCompatible()) {        		
		
		var data = eval(" (" + getData(brand) + ") ");
		
        var markers = [];
        var markerClusterer = null;
		
		map = new GMap2(document.getElementById("map"));
		//Center set for middle of USA
		map.setCenter(new GLatLng(38.0000, -97.0000), 4);
		map.addControl(new GLargeMapControl());
		for (var i = 0; i < data.entries.length; i++) {
			var id = data.entries[i].id;
			var title = data.entries[i].title;
			var address = data.entries[i].address;
			var address2 = data.entries[i].address2;
			var latlng = new GLatLng(parseFloat(data.entries[i].lat), parseFloat(data.entries[i].lng));
			var entry = {
                latlng: latlng,
				id: id,
                title: ucWords(title),
                address: ucWords(address),
                address2: ucWords(address2)
            };
			markers.push(createMarker(entry, brand));
		}
		markerCluster = new MarkerClusterer(
			map, 
			markers, 
			{
				styles: styles
			}
		);
    }
}
/**
 * Create marker for an entry
 * Initializes click event
 * @param Object entry - entry{latlng, id, title, address, address2, brand}
 */
function createMarker(entry, brand){	
    var newIcon = MapIconMaker.createMarkerIcon({
        width: 32,
        height: 32,
        primaryColor: brandColour[brand]
    });
	newIcon.infoWindowAnchor = new GPoint(+132,+15);
    var marker = new GMarker(entry.latlng, {
        icon: newIcon
    });
	var html = [];
		html.push(	"<div class='content'>"); 
		html.push(		"<table cellpadding='0' cellspacing='0' border='0'>");
		html.push(			"<tr>");
		html.push(				"<td><img src='/images/brandmaps/" + brandNames[brand] + "/infoWindow/logo.gif' width='77' height='60' alt='" + brandNames[brand] + "'/></td>");
		html.push(				"<td class='padding' valign='middle'>");
		html.push(					"<strong>" + entry.title + "</strong><br/>");
		html.push(					entry.address + "<br/>");
		html.push(					entry.address2 + "<br/>");
		html.push(				"</td>"); 
		html.push(			"</tr>"); 
		html.push(		"</table>");
		html.push(	"</div>");
    GEvent.addListener(marker, 'click', function(){
		marker.openExtInfoWindow(
			map,
			"custom_info_window",
			html.join(''),
			{beakOffset: 0}
		);
    });
    return marker;
}

/**
 * Return a JS array for the cluster styles
 * @param String brand - 2 character brand abbrv
 * @return Array - Cluster styles
 */
function getClusterStyles(brand){
	var styles = [{
		url: '/images/brandmaps/' + brandNames[brand] + '/clusterSm.gif',
		height: 38,
		width: 46,
		opt_anchor: [10, 0],
		opt_textColor: '#FFFFFF'
	},
	{
		url: '/images/brandmaps/' + brandNames[brand] + '/clusterMd.gif',
		height: 38,
		width: 46,
		opt_anchor: [10, 0],
		opt_textColor: '#FFFFFF'
	},
	{
		url: '/images/brandmaps/' + brandNames[brand] + '/clusterLg.gif',
		height: 38,
		width: 46,
		opt_anchor: [10, 0],
		opt_textColor: '#FFFFFF'
	}];
	return styles;
}

/**
 * Get all entries of a particular brand via AJAX
 * Async is false so this call blocks
 * @param String brand - 2 character brand abbrv
 * @return String - JSON formatted string of entries
 */
function getData(brand){
    var result;
    $.ajax({
        type: 'POST',
        async: false,
        url: '/lib/brandmaps.cfc?method=getEntries&brand=' + brand,
        success: function(data){
            result = trim(data);
        }
    });
    return result;
}

/**
 * Trim whitespace from a string
 * @param String str
 * @return String - str with whitespace removed
 */
function trim(str){
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

/**
 * Capitalizes the first letter of each word in a string
 */
function ucWords(str){
    if (typeof(str) == "string") {
		return str.replace(/\w+/g, function(a){
			return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
		});
	}
}


