var bumaps_init = function() {
	new BUEmbeddedMap();
}

function BUEmbeddedMap() {
	if (!GBrowserIsCompatible()) return false;
	BUEmbeddedMap.instance = this;
	this.markers = {};
	this.addReferencedData(eval( '(' + item_cache_str + ')' ));
	
	this.mapDiv = jQuery('#map');
	var id = null;
	this.mapDiv.find('input').each(function() {
		id = jQuery(this).val();
	});

	this.userMapId = id;
	if ( !id ) {
		return false;
	}

	this.map = new GMap2(this.mapDiv[0]);
	this.map.addControl(new GLargeMapControl());
	
	GEvent.addListener(this.map, "click", function(overlay, point) {
		if (overlay && overlay.bumaps_info) {
			BUEmbeddedMap.instance.openMarker(overlay.id);
		}
	});
	this.popupXslTemplate = string2xml(popupXslString);
	this.loadMarkers();
}

BUEmbeddedMap.bootstrap = function() {
	var addLinkTag = function(url) {
		var scr = document.createElement('link');
		scr.type = 'text/css';
		scr.rel = 'stylesheet';
		scr.href = url;
		document.getElementsByTagName('head')[0].appendChild(scr);
	}

	var addScriptTag = function(url) {
		var scr = document.createElement('script');
		scr.type = 'text/javascript';
		scr.src = url;
		document.getElementsByTagName('head')[0].appendChild(scr);
	}
	
	var script_url = document.getElementById( 'bu-embedded-maps-script' ).src;
	var base_url = script_url.substring( 0, script_url.lastIndexOf( '/' ) );
	var base_url = base_url.substring( 0, base_url.lastIndexOf( '/' ) ) + '/';
	BUEmbeddedMap.baseURL = base_url;

	addLinkTag(BUEmbeddedMap.baseURL + 'common/popup.css');
	var d = new Date();
	var no_cache = d.getFullYear() + d.getMonth() + d.getDate() + d.getHours();
	addScriptTag(BUEmbeddedMap.baseURL + 'ajax/dept-maps-init.php?nc=' + no_cache );
}  

BUEmbeddedMap.prototype.loadMarkers = function() {
	var url = BUEmbeddedMap.baseURL + 'ajax/get-my-map-items-by-hash.php?hash='+this.userMapId;
	url += '&page_size=0&method=embedded';
	url += '&referrer='+escape(location.href);

	var me = this;
	
	jQuery.ajax({
		dataType: 'jsonp',
		url: url, 
		success: function(data) {
			me.addMarkers(data);
		}
	});
}

BUEmbeddedMap.prototype.addMarkers = function(data) {
	if (data.total_count < 1) {
		// No results found. Fail gracefully
		this.map.setCenter(new GLatLng(42.34312489659957, -71.10682547092439), 14);
		return;
	}

	// This code makes sure that all results are visible
	var bounds = new GLatLngBounds();
	if (data.markers.length > 1) {
		for (var i=0; i<data.markers.length; i++) 
			bounds.extend(new GLatLng(data.markers[i].lat, data.markers[i].lng)); 
	}
	else {
		if (data.markers.length == 1) {
			bounds.extend(new GLatLng(data.markers[0].lat, data.markers[0].lng));
		}
	}

	this.map.setCenter(bounds.getCenter(), this.map.getBoundsZoomLevel(bounds, this.map.getSize()) - 1);
	
	for (var i=0; i<data.markers.length; i++) {
		this.addMarker(data.markers[i]);
	}
	this.openMarker(data.markers[0].id);
}

BUEmbeddedMap.prototype.addMarker = function(data) {
	var marker_options = {
		icon: this.getMarkerIcon(data.type, data.icon)
	}

	var marker = new GMarker(new GLatLng(data.lat, data.lng), marker_options);
	marker.id = data.id;
	marker.type = data.type;
	marker.bumaps_info = data;

	this.map.addOverlay(marker);
	this.markers[data.id] = marker;
}

BUEmbeddedMap.prototype.openClosest = function(item_id, original_id) {
	if ( !this.markers.hasOwnProperty(item_id) && this.referencedData[item_id]) {
		this.addMarker( this.referencedData[item_id] );
		this.openMarker(item_id);
		var me = this;
		var handle = GEvent.addListener(this.map, 'infowindowclose', function() {
			var closestMarker = me.markers[item_id];
			me.map.removeOverlay(closestMarker);
			delete me.markers[item_id];
			GEvent.removeListener(handle);
		});
		return;
	}
	this.openMarker(item_id);
	this.restoreInfoWindow = true;
}

BUEmbeddedMap.prototype.openMarker = function(id) {
	if (this.markers.hasOwnProperty(id)) var marker = this.markers[id];
	else return false;

	if (!marker.bu_html) {
		try {
			var xml_string = object2xml(marker.bumaps_info, 'popup');
			var xml = string2xml(xml_string);
			marker.bu_html = xml2html(xml, this.popupXslTemplate);
		}
		catch(e) {
			alert('Error opening marker: ' + e);
			return false;
		}
	}
	
	var div = $('<div />').html(marker.bu_html);
    div.find('#icons').hide().remove();
    div.find('#view_full_map_link').show();

	this.addReferencedInfoToPopup(marker, div);
	div.find('.item-reference').click(function() {
		var params = parseUrl( $(this).attr('href') );
		BUEmbeddedMap.instance.openClosest( params['id'], this.current_open_marker_id);
		return false;
	});

	div.find('.directions-link').click(function() {
		var from = ( $(this).attr('rel') == 'from-here' );
		BUEmbeddedMap.instance.showDirectionsForm(from, id);
		return false;
	});

	div.find( '#popup_back_button a').click(function() {
		BUEmbeddedMap.instance.resetPopup();
		return false;
	});


	marker.openInfoWindow(div[0]);
	this.current_open_marker_id;
}

BUEmbeddedMap.prototype.resetPopup = function() {
	jQuery('#popup_closest').show();
	jQuery('#popup_get_directions').show();

	jQuery('#from_dir').hide();
	jQuery('#to_dir').hide();
	jQuery('#popup_back_button').hide();

	jQuery('#get_dirs').css('font-weight', '');

	this.resizeInfoWindow();
}

BUEmbeddedMap.prototype.showDirectionsForm = function(from, id) {
	if (from) {
		jQuery('#from_dir').show();
		jQuery('#to_dir').hide();
	}
	else {
		jQuery('#from_dir').hide();
		jQuery('#to_dir').show();
	}

	jQuery('#get_dirs').css('font-weight', 'bolder');

	jQuery('#popup_closest').hide();

	jQuery('#popup_back_button').show();
	this.resizeInfoWindow();
	return false;
}

BUEmbeddedMap.prototype.resizeInfoWindow = function() {
	try{
		this.map.updateInfoWindow(this.map.getInfoWindow().getTabs());
	}
	catch(e) {}
}

BUEmbeddedMap.prototype.addReferencedInfoToPopup = function(marker, div) {
	var item_cache = this.referencedData;

	div.find('.item-reference[rel="building"]').each(function() {
        var ref_id = jQuery.trim($(this).text());
		var ref_item = item_cache[ref_id];
		if ( typeof ref_item != 'undefined' )
			$(this).text(ref_item.title);
	});
	
	div.find('.item-reference[rel="train-stop"]').each(function() {
        var ref_id = jQuery.trim($(this).text());
		var ref_item = item_cache[ref_id];
		if ( typeof ref_item != 'undefined' )
			$(this).text(ref_item.title);
	});
	
	div.find('.item-reference[rel="parking-lot"]').each(function() {
        var ref_id = jQuery.trim($(this).text());
		var ref_item = item_cache[ref_id];
		if ( typeof ref_item != 'undefined' )
			$(this).text(ref_item.title.substring(ref_item.title.indexOf(':') + 2));
	});

	div.find('.item-reference[rel="bus"]').each(function() {
        var ref_id = jQuery.trim($(this).text());
		var ref_item = item_cache[ref_id];
		if ( typeof ref_item != 'undefined' )
			$(this).text(ref_item.title.substring(0, ref_item.title.indexOf(':')));
	});
}

BUEmbeddedMap.prototype.getMarkerIcon = function(type, icon_name) {
	var icon;
	var server_path = BUEmbeddedMap.baseURL;
	var m_path = server_path + 'icons/map-icons/markers/'; //marker icon path
	var p_path = server_path + 'icons/map-icons/markers/'; //print icon path
	var p_icon = p_path+icon_name+'.gif';
	var m_icon = m_path+icon_name+'.png';

	if (type == 'normal' || type == 'normal2') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = m_path + "shadow.png";
		icon.iconSize = new GSize(27, 26);
		icon.shadowSize = new GSize(41, 26);
		icon.iconAnchor = new GPoint(15, 27);
		icon.ifnoWindowAnchor = new GPoint(12, 2);
		icon.printShadow = p_path + "shadow.gif";
	}

	if (type == 'bus') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(18,18);
		icon.iconAnchor = new GPoint(10, 10);
		icon.printShadow = null;
	}

	if (type == 'parking') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(14,14);
		icon.iconAnchor = new GPoint(8, 8);
		icon.printShadow = null;
	}

	if (type == 'wireless') {
		icon= new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(18,18);
		icon.iconAnchor = new GPoint(9, 9);
		icon.printShadow = null;
	}

	if (type == 'train') {
		icon= new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(17,17);
		icon.iconAnchor = new GPoint(9, 9);
		icon.printShadow = null;
	}

	if (type == 'blue') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(14,14);
		icon.iconAnchor = new GPoint(7, 7);
		icon.printShadow = null;
	}

	if (type == 'tty') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(19,19);
		icon.iconAnchor = new GPoint(10, 10);
		icon.printShadow = null;
	}

	if (type == 'door') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(19,19);
		icon.iconAnchor = new GPoint(10, 10);
		icon.printShadow = null;
	}

	if (type == 'audible') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(19,19);
		icon.iconAnchor = new GPoint(10, 10);
		icon.printShadow = null;
	}

	if (type == 'curb') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(10,10);
		icon.iconAnchor = new GPoint(5, 5);
		icon.printShadow = null;
	}
	
	if (type == 'bicycle') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(16,16);
		icon.iconAnchor = new GPoint(8, 8);
		icon.printShadow = null;
	}

	if (type == 'mail') {
		icon = new GIcon(G_DEFAULT_ICON, m_path + icon_name + '.gif');
		icon.shadow = null;
		icon.iconSize = new GSize(19,19);
		icon.iconAnchor = new GPoint(10, 10);
		icon.printShadow = null;
	}

	if (type == 'bus_commencement') {
		icon = new GIcon(G_DEFAULT_ICON, m_icon);
		icon.shadow = null;
		icon.iconSize = new GSize(18,18);
		icon.iconAnchor = new GPoint(10, 10);
		icon.printShadow = null;
	}
	
	icon.printImage = p_icon;
	icon.mozPrintImage = p_icon;

	return icon;
}

BUEmbeddedMap.prototype.adjustZoom = function() {
	var bounds = new GLatLngBounds();
	for (var id in this.markers) {
		if (!this.markers.hasOwnProperty(id)) continue;
		bounds.extend(this.markers[id].getPoint());
	}

	this.map.setCenter(bounds.getCenter(), this.map.getBoundsZoomLevel(bounds, this.map.getSize()));
}

BUEmbeddedMap.prototype.createMarker = function(data) {
	if (typeof data == 'undefined') return false;
	var marker = new GMarker(new GLatLng(data.lat, data.lng), 
			this.getMarkerIcon(data.type, data.icon));
	this.map.addOverlay(marker);
	marker.bumaps_info = data;
	marker.id = data.id;
	this.markers[data.id] = marker;
	return marker;
}

BUEmbeddedMap.prototype.addReferencedData = function(data) {
	this.referencedData = data;
}

//Load the data:
if ( window.addEventListener ) {
	window.addEventListener('load', BUEmbeddedMap.bootstrap, false);
}
if ( window.attachEvent ) {
	window.attachEvent( 'onload', BUEmbeddedMap.bootstrap );
}
