// Mapping 0.1
var olympics = olympics || {};
olympics.feeds = olympics.feeds || {};
olympics.feeds.BlogParser = function() {
this._markers = [];
this._startedProcessing 	= false;
this._finishedProcessing 	= false;
}
olympics.feeds.BlogParser.prototype = {
process: function(data) {
var data = data.items;
data = this._prepareData(data);
if(data && typeof data.length == "number") {
this._startedProcessing = true;
var i = 0,
len = data.length;
for(; i < len; i++) {
this._markers.push( this._processItem(data[i]) );
}
this._finishedProcessing = true;
}
return this._markers;
},
getMarkers: function() {
return this._markers;
},
_processItem: function(item) {
var post = item;
var geo = post.geo.split(" ");
var ll = new olympics.mapping.LatLon(geo[0], geo[1]);
var m = new olympics.mapping.MapMarker(ll);
m.setTitle(post.title);
m.setIcon("http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/generic_markers/blog.png");
var data = {
postTitle: post.title,
postAuthor: post.author,
postSummary: post.description,
postTime: olympics.util.formatTime(new Date(post.pubDate), "{dd} {mmm} {yyyy}, {hh}:{mm} {AMPM}"),
urlForPost: post.link
}
var hoverBodyTemplate = [ '<div class="blog-body">',
'<h3>{postTitle}</h3>',
'<div class="meta">',
'<p class="name">{postAuthor}</p>',
'<p class="time">{postTime}</p>',
'</div>',
'<p class="blog-more">' + olympics.lang["HOVER_PANEL_CLICK_FOR_MORE"] + '</p>',
'</div>' ].join("\n");
var hoverBody = glow.lang.interpolate(hoverBodyTemplate, data);
var contentForHover = {
header	: olympics.lang["PANEL_TITLE_BLOG"],
body	: hoverBody,
footer	: ""
}
m.setContentObject("hover", contentForHover);
var clickBodyTemplate = [
'<div class="blog-body">',
'<h3>{postTitle}</h3>',
'<div class="meta">',
'<p class="name">{postAuthor}</p>',
'<p class="time">{postTime}</p>',
'</div>',
'<div class="blog-summary">',
'<p>{postSummary}</p>',
'</div>',
'<div>',
'<p><a href="{urlForPost}">' + olympics.lang["BLOG_POST_CONTINUE_READING"] + '</a></p>',
'<p class="new-page">' + olympics.lang["PANEL_CLICK_WARNING" ] + '</p>',
'</div>',
'</div>' ].join("\n");
var clickBody = glow.lang.interpolate(clickBodyTemplate, data);
var contentForClick = {
header	: olympics.lang["PANEL_TITLE_BLOG"],
body	: clickBody,
footer	: ""
}
m.setContentObject("click", contentForClick);
m.setContentObject("meta", {type:"blog"});
return m;
},
_prepareData: function(data) {
return data;
}
}
olympics.feeds = olympics.feeds || {};
olympics.feeds.Loader = {
getInstance: function() {
if(typeof olympics.feeds.Loader._instance == "undefined") {
olympics.feeds.Loader._instance = new olympics.feeds.LoaderInstance();
}
return olympics.feeds.Loader._instance;
},
DEFAULT_LOAD_TYPE: "jsonp",
_jsonCbs: {len:0},
loadScriptWithCharset: function(url, callback, charset) {
var noCacheUrl = function (url) {
return [url, (/\?/.test(url) ? "&" : "?"), "a", new Date().getTime(), parseInt(Math.random()*100000)].join("");
}
if (callback) {
var callbackName = "c" + olympics.feeds.Loader._jsonCbs.len++;
olympics.feeds.Loader._jsonCbs[callbackName] = callback;
url = glow.lang.interpolate(url, {callback: "olympics.feeds.Loader._jsonCbs." + callbackName});
}
var script = document.createElement("script");
script.src = url;
if(charset) {
script.setAttribute("charset", charset);
}
glow.ready(function() {
document.body.appendChild(script);
});
}
}
olympics.feeds.LoaderInstance = function() {
this._currentId = 1;
this._feedQueue = []
}
olympics.feeds.LoaderInstance.prototype = {
load: function(source, args) {
var source 	= source;
args = args || {};
var type 	= args["type"] || olympics.feeds.Loader.DEFAULT_LOAD_TYPE;
var charset = args["charset"] || null;
var feed = this._addFeedToQueue(source, type, charset);
return feed;
},
_generateId: function() {
return this._currentId++;
},
_addFeedToQueue: function(source, type, charset) {
var self = this;
var feed = new olympics.feeds.Feed( this._generateId(),
source,
type,
charset );
olympics.feeds.Loader.loadScriptWithCharset(
source,
function(data) {
var customEvent = new glow.events.Event();
customEvent.feed = feed;
feed.setData(data);
if(olympics.util.LOGGING) console.log("Feed loaded (%o): Feed: %o", source, feed);
glow.events.fire( 	olympics.feeds.Loader,
olympics.feeds.Loader.Events.FEED_LOADED,
customEvent );
},
charset);
return feed;
},
_feedLoaded: function() {
}
}
olympics.feeds.Loader.Events = {
FEED_LOADED: "feed_loader_feed_loaded",
FEED_TIME_OUT: "feed_loaded_feed_timeout"
}
olympics.feeds.Feed = function(id, source, type) {
this._id 		= id;
this._source 	= source;
this._type		=type;
this._loaded 	= false;
this._data 		= null;
}
olympics.feeds.Feed.prototype = {
getId: function() {
return this._id;
},
getSource: function() {
return this._source;
},
getType: function() {
return this._type;
},
isLoaded: function() {
return this._loaded;
},
getData: function() {
return this._data;
},
setData: function(data) {
this._data = data;
this._loaded = true;
}
}
olympics.feeds = olympics.feeds || {};
olympics.feeds.TwitterParser = function() {
this._markers = [];
this._startedProcessing 	= false;
this._finishedProcessing 	= false;
}
olympics.feeds.TwitterParser.prototype = {
process: function(data) {
var data = this._prepareData(data);
if(data && typeof data.length == "number") {
this._startedProcessing = true;
var i = 0,
len = data.length;
for(; i < len; i++) {
var marker =  this._processItem(data[i]);
if(marker) this._markers.push( marker );
}
this._finishedProcessing = true;
}
return this._markers;
},
getMarkers: function() {
return this._markers;
},
_processItem: function(item) {
var post = item;
if(!post.geometry) return false;
var ll = new olympics.mapping.LatLon(post.geometry.coordinates[0], post.geometry.coordinates[1]);
var m = new olympics.mapping.MapMarker(ll);
m.setTitle(post.text);
m.setIcon("http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/generic_markers/twitter.png");
m.setId("twitter_" + post.id);
var splitDate = post.created_at.split(" ");
var ieDateString = splitDate[0] + ", " + splitDate[2] + " " + splitDate[1] + " " + splitDate[5] + " " + splitDate[3] + " " + splitDate[4];
var data = {
twitterMessage 	: post.text,
authorFullName 	: post.user.name,
authorFirstName : post.user.name.split(" ")[0],
urlForTwitter	: "http://twitter.com/" + post.user.screen_name,
timestamp		: olympics.util.formatTime(new Date(ieDateString), "{dd} {mmm} {yyyy}, {hh}:{mm} {AMPM}")
}
var hoverBodyTemplate = [ '<div class="twitter-body">',
'<h3>{twitterMessage}</h3>',
'<div class="meta">',
'<p class="name">{authorFullName}</p>',
'<p class="time">{timestamp}</p>',
'</div>',
'<p class="twitter-more">' + olympics.lang["HOVER_PANEL_CLICK_FOR_MORE"] + '</p>',
'</div>' ].join("\n");
var hoverBody = glow.lang.interpolate(hoverBodyTemplate, data);
var contentForHover = {
header: olympics.lang["PANEL_TITLE_TWITTER"],
body:	hoverBody,
footer: ""
};
m.setContentObject("hover", contentForHover);
var clickBodyTemplate = [
'<div class="twitter-body">',
'<div class="meta">',
'<p class="name">{authorFullName}</p>',
'<p class="time">{timestamp}</p>',
'</div>',
'<div class="message">',
'<p>{twitterMessage}</p>',
'</div>',
'<div>',
'<p><a href="{urlForTwitter}">' + olympics.lang["TWITTER_CONTINUE_READING"] + '</a></p>',
'<p class="new-page">' + olympics.lang["PANEL_CLICK_WARNING"] + '</p>',
'</div>',
'</div>' ].join("\n");
var clickBody = glow.lang.interpolate(clickBodyTemplate, data);
var contentForClick = {
header: olympics.lang["PANEL_TITLE_TWITTER"],
body:	clickBody,
footer: ""
};
m.setContentObject("click", contentForClick);
m.setContentObject("meta", {type:"twitter"});
return m;
},
_prepareData: function(data) {
return data;
}
}
olympics.feeds = olympics.feeds || {};
olympics.feeds.VenueParser = function() {
this._startedProcessing 	= false;
this._finishedProcessing 	= false;
this._markers 		= [];
}
olympics.feeds.VenueParser.prototype = {
idCounter: 0,
process: function(data) {
var data = this._prepareData(data);
if(data && typeof data.length == "number") {
this._startedProcessing = true;
var i = 0,
len = data.length;
for(; i < len; i++) {
this._markers.push( this._processItem(data[i]) );
}
this._finishedProcessing = true;
}
return this._markers;
},
_processItem: function(item) {
var venue = item;
var id = "venues_" + venue.id;
var ll = new olympics.mapping.LatLon(venue.geo.lat, venue.geo.lon);
var m = new olympics.mapping.MapMarker(ll);
m.setId( id );
m.setTitle(venue.name);
var contentForHover;
var contentForClick;
if (venue.type == "venue") {
var data = {
venueName: venue.name,
imageHTML: "",
description: venue.info,
linksHTML: this._createLinksHTML(venue.links),
sportListText: this._createSportListText(venue.sports),
sportListIconHTML: this._createSportListIconHTML(venue.sports_icons)
}
data["linksDisclaimerText"] = venue.links.length > 0 ? ['<div>',
'<p class="new-page">' + olympics.lang["PANEL_CLICK_WARNING"] + '</p>',
'<p class="map-disclaimer">' + olympics.lang["PANEL_SITE_DISCLAIMER"] + '</p>',
'</div>'].join("\n") : "";
if(venue.images.type == "static") {
data["imagePath"] = "http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/pics/" + venue.images.source;
data["imageRel"]  = "";
} else if(venue.images.type == "flickr" ){
data["imagePath"] = "http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/ui/loading.gif";
data["imageRel"]  = venue.images.source;
} else {
data["imagePath"] = "http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/ui/no_image.gif";
data["imageRel"]  = "";
}
var hoverBodyTemplate = [
'<div class="venue-body">',
'<div class="venue-sports">',
'{sportListText}',
'</div>',
'<p class="venues-more">' + olympics.lang["HOVER_PANEL_CLICK_FOR_MORE"] + '</p>',
'</div>' ].join("\n");
var hoverBody = glow.lang.interpolate(hoverBodyTemplate, data);
contentForHover = {
header	: data.venueName,
body	: hoverBody,
footer	: ""
}
m.setContentObject("hover", contentForHover);
var clickBodyTemplate = [
'<div class="venue-body">',
'<div class="images">',
'<img class="image-main" src="{imagePath}" alt="{venueName}" rel="{imageRel}" />',
'{sportListIconHTML}',
'</div>',
'<div class="venue-desc">',
'<p>{description}</p>',
'</div>',
'<div class="venue-links">',
'{linksHTML}',
'</div>',
'{linksDisclaimerText}',
'</div>' ].join("\n");
var clickBody = glow.lang.interpolate(clickBodyTemplate, data);
contentForClick = {
header	: data.venueName,
body	: clickBody,
footer	: ""
}
m.setContentObject("click", contentForClick);
var iconHTML = this._createMarkerGroupForSports(venue.sports_icons);
m.setIcon(iconHTML);
m.setContentObject("meta", {type:"venue"});
} else if(venue.type == "landmark"){
var data = {
venueName: venue.name,
description: venue.info,
linksHTML: this._createLinksHTML(venue.links),
imageHTML: ""
}
data["linksDisclaimerText"] = venue.links.length > 0 ? ['<div>',
'<p class="new-page">' + olympics.lang["PANEL_CLICK_WARNING"] + '</p>',
'<p class="map-disclaimer">' + olympics.lang["PANEL_SITE_DISCLAIMER"] + '</p>',
'</div>'].join("\n") : "";
if(venue.images.type == "static") {
data["imagePath"] = "http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/pics/" + venue.images.source;
data["imageRel"]  = "";
} else if(venue.images.type == "flickr"){
data["imagePath"] = "http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/ui/loading.gif";
data["imageRel"]  = venue.images.source;
} else {
data["imagePath"] = "http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/ui/no_photo.gif";
}
var hoverBodyTemplate = [
'<div class="landmark-body">',
'<p class="venues-more">' + olympics.lang["HOVER_PANEL_CLICK_FOR_MORE"] + '</p>',
'</div>' ].join("\n");
var hoverBody = glow.lang.interpolate(hoverBodyTemplate, data);
contentForHover = {
header	: data.venueName,
body	: hoverBody,
footer	: ""
}
m.setContentObject("hover", contentForHover);
var clickBodyTemplate = [
'<div class="landmark-body">',
'<div class="images">',
'<img class="image-main" rel="{imageRel}" src="{imagePath}" alt="{venueName}" />',
'{imageHTML}',
'</div>',
'<div class="landmark-desc">',
'<p>{description}</p>',
'</div>',
'<div class="landmark-links">',
'{linksHTML}',
'</div>',
'{linksDisclaimerText}',
'</div>' ].join("\n");
var clickBody = glow.lang.interpolate(clickBodyTemplate, data);
contentForClick = {
header	: data.venueName,
body	: clickBody,
footer	: ""
}
m.setContentObject("click", contentForClick);
m.setIcon("http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/generic_markers/landmark.png");
m.setContentObject("meta", {type:"landmark"});
}
return m;
},
_prepareData: function(data) {
return data;
},
_createMarkerGroupForSports: function(sports) {
var iconHTML = ["<div class=\"marker-group\">"];
var len = sports.length;
for(var i=0; i < len; i++) {
iconHTML.push("<img class=\"offset-" + i + "\" src=\"http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/sport_markers/" + sports[i].toLowerCase() + ".png\" />");
}
iconHTML.push("</div>");
return iconHTML.join("\n");
},
_createLinksHTML: function(links){
var html = ["<ul class=\"link-group\">"];
var len = links.length;
for (var i = 0; i < len; i++) {
var link = links[i];
var url = link.url;
var text = link.text;
html.push("<li class=\"link-" + i + "\"><a href=\"" + url + "\">" + text + "</a></li>");
}
html.push("</ul>");
return html.join("\n");
},
_createSportListIconHTML: function(sports) {
var html = ["<ul class=\"icon-group\">"];
var len = sports.length;
for(var i=0; i<len; i++) {
html.push("<li class=\"icon-offset-" + i + "\"><img src=\"http://newsimg.bbc.co.uk/sol/shared/bsp/hi/olympics2008/map/img/sport_icons/" + sports[i].toLowerCase() + "_large.png\" alt=\"" + sports[i] + "\"/></li>");
}
html.push("</ul>");
return html.join("\n");
},
_createSportListText: function(sports) {
var me = this;
var list = ['<ul>'];
var len = sports.length;
for(var i = 0; i<len; i++) {
list.push('<li>' + me._capitalise(sports[i]) + '</li>');
}
list.push('</ul>');
return list.join("\n");
},
_capitalise: function(str) {
var first = str.slice(0,1);
var rest  = str.slice(1, str.length);
return first.toUpperCase() + rest;
}
}
olympics.mapping = olympics.mapping || {};
olympics.mapping.LatLon = function(lat, lon) {
this.lat = lat;
this.lon = lon;
this.nativeObj = null;
}
olympics.mapping.LatLon.prototype = {
setLat: function(lat) {
this.lat = lat;
this._invalidate();
},
setLon: function(lon) {
this.lon = lon;
this._invalidate();
},
getLat: function() {
return this.lat;
},
getLon: function() {
return this.lon;
},
toNative: function() {
if(!this.nativeObj) {
this.nativeObj = this._createNativeImplementation();
}
return this.nativeObj;
},
toString: function() {
return this.getLat() + "," + this.getLon();
},
equals: function(ll, precision) {
var equal = true;
if( Number(this.getLat()).toFixed(precision) !== Number(ll.getLat()).toFixed(precision) ) equal = false;
if( Number(this.getLon()).toFixed(precision) !== Number(ll.getLon()).toFixed(precision) ) equal = false;
return equal;
},
serialise: function() {
return {lat: this.getLat(), lon: this.getLon()}
},
_createNativeImplementation: function() {
var ll = new VELatLong(this.lat, this.lon);
return ll;
},
_invalidate: function() {
this.nativeObj = null;
}
}
olympics.mapping = olympics.mapping || {};
olympics.mapping.MapLayer = function() {
this.parentMap = null;
this.markers = [];
this.visible = true;
this.nativeLayer = new VEShapeLayer();
}
olympics.mapping.MapLayer.prototype = {
addMarker: function(marker) {
this.markers.push(marker);
this._fireMarkerAddedEvent(marker);
this.nativeLayer.AddShape(marker.toNative());
},
addMarkers: function(markers) {
var self = this;
var nativeMarkers = [];
var i = 0,
len = markers.length;
try {
nativeMarkers = glow.lang.map( markers, function(marker) {
self.markers.push(marker);
self._fireMarkerAddedEvent(marker);
return marker.toNative();
})
} catch(e) {
if(olympics.util.LOGGING) console.warn(e);
}
this.nativeLayer.AddShape(nativeMarkers);
},
getMarkers: function() {
return this.markers;
},
toNative: function() {
return this.nativeLayer;
},
show: function() {
this.nativeLayer.Show();
this.visible = true;
},
hide: function() {
this.nativeLayer.Hide();
this.visible = false;
},
isVisible: function() {
return this.visible;
},
_fireMarkerAddedEvent: function(m) {
var evt = new glow.events.Event();
evt.data = m;
glow.events.fire(this, olympics.mapping.MapLayer.Events.MARKER_ADDED, evt);
}
}
olympics.mapping.MapLayer.Events = {
MARKER_ADDED	: "marker_added_to_layer",
MARKER_REMOVED	: "marker_removed_from_layer",
LAYER_SHOW		: "map_layer_visible",
LAYER_HIDE		: "map_layer_hidden"
}
olympics.mapping = olympics.mapping || {};
olympics.mapping.MapLocator = function(domElementId, bindToMap, opts) {
this.domElementId = domElementId;
this.parentMap	  = bindToMap;
var opts = opts || {};
var lineColourArray = opts["lineColour"] || [255,0,0,1];
this.boxLineColour = new VEColor(lineColourArray[0],lineColourArray[1],lineColourArray[2],lineColourArray[3]);
var fillColourArray = opts["fillColour"] || [255,0,0,0.5];
this.boxFillColour = new VEColor(fillColourArray[0],fillColourArray[1],fillColourArray[2],fillColourArray[3]);
this.width = opts["width"] || 100;
this.height = opts["height"] || 100;
this.minBoxHeight = opts["minBoxHeight"] || 9;
this.minBoxWidth  = opts["minBoxWidth"]  || 12;
this.isMapMoving = false;
this.locatorBox;
this.mapMovingLatOffset;
this.mapMovingLongOffset;
this.map = new olympics.mapping.MapView(this.domElementId, {width:this.width, height:this.height, bridgeNativeEvents:false, fixedMap: true});
this.map.display();
this.map.getNative().SetMapStyle(VEMapStyle.Aerial);
this.map.getNative().HideDashboard();
this._createNativeParentHandlers();
this._createNativeEventHandlers();
this._updateLocator();
}
olympics.mapping.MapLocator.prototype = {
_createNativeEventHandlers: function() {
this.map.getNative().AttachEvent("onmousedown",this._bindFunction(this._mouseDownEvent, this));
this.map.getNative().AttachEvent("onmousemove",this._bindFunction(this._mouseMoveEvent, this));
this.map.getNative().AttachEvent("onmouseup",this._bindFunction(this._mouseUpEvent, this));
this.map.getNative().AttachEvent("onmousewheel", function(e) {return true;});
},
_createNativeParentHandlers: function() {
this.parentMap.getNative().AttachEvent("onchangeview",this._bindFunction(this._updateLocator, this));
},
_bindFunction: function(fn, env) {
return function(evt) {
fn.call(env, evt);
}
},
_mouseDownEvent: function(evt) {
if (evt.leftMouseButton && evt.elementID) {
this.isMapMoving = true;
this.locatorBox = this.map.getNative().GetShapeByID(evt.elementID);
var miniMapPoints = this.locatorBox.GetPoints();
var mouseLatLong = this.map.getNative().PixelToLatLong(new VEPixel(evt.mapX, evt.mapY));
this.mapMovingLatOffset = mouseLatLong.Latitude - miniMapPoints[0].Latitude;
this.mapMovingLongOffset = mouseLatLong.Longitude - miniMapPoints[0].Longitude;
this.map.getNative().vemapcontrol.EnableGeoCommunity(true);
}
return true;
},
_mouseMoveEvent: function(evt) {
if (this.isMapMoving) {
var mousePoint = this.map.getNative().PixelToLatLong(new VEPixel(evt.mapX, evt.mapY));
var oldPoints = this.locatorBox.GetPoints();
var shapeWidth = oldPoints[1].Longitude - oldPoints[0].Longitude;
var shapeHeight = oldPoints[3].Latitude - oldPoints[0].Latitude;
var newPoints = new Array();
newPoints[0]=new VELatLong(mousePoint.Latitude - this.mapMovingLatOffset, mousePoint.Longitude - this.mapMovingLongOffset);
newPoints[1]=new VELatLong(mousePoint.Latitude - this.mapMovingLatOffset, mousePoint.Longitude - this.mapMovingLongOffset + shapeWidth);
newPoints[2]=new VELatLong(mousePoint.Latitude - this.mapMovingLatOffset + shapeHeight, mousePoint.Longitude - this.mapMovingLongOffset + shapeWidth);
newPoints[3]=new VELatLong(mousePoint.Latitude - this.mapMovingLatOffset + shapeHeight, mousePoint.Longitude - this.mapMovingLongOffset);
this.locatorBox.SetPoints(newPoints);
var centrePoint = new VELatLong(newPoints[3].Latitude+((newPoints[0].Latitude-newPoints[3].Latitude)/2),newPoints[1].Longitude+((newPoints[0].Longitude-newPoints[1].Longitude)/2));
this.parentMap.getNative().SetCenter(centrePoint);
}
return true;
},
_mouseUpEvent: function(evt) {
if (this.isMapMoving && evt.leftMouseButton)
{
this.isMapMoving = false;
this.map.getNative().vemapcontrol.EnableGeoCommunity(false);
}
},
_updateLocator: function() {
if (this.isMapMoving) return;
this.map.getNative().DeleteAllShapes();
var currentView = this.parentMap.getNative().GetMapView();
var box = {
tl: new VELatLong(currentView.TopLeftLatLong.Latitude, currentView.TopLeftLatLong.Longitude),
tr: new VELatLong(currentView.TopLeftLatLong.Latitude, currentView.BottomRightLatLong.Longitude),
bl: new VELatLong(currentView.BottomRightLatLong.Latitude, currentView.TopLeftLatLong.Longitude),
br: new VELatLong(currentView.BottomRightLatLong.Latitude, currentView.BottomRightLatLong.Longitude)
}
var pixels = {
tl: this.map.getNative().LatLongToPixel(box.tl),
tr: this.map.getNative().LatLongToPixel(box.tr),
bl: this.map.getNative().LatLongToPixel(box.bl),
br: this.map.getNative().LatLongToPixel(box.br)
}
if( (pixels.tr.x - pixels.tl.x) < this.minBoxWidth) {
pixels.tr.x = pixels.tl.x + this.minBoxWidth;
pixels.br.x = pixels.tl.x + this.minBoxWidth;
pixels.br.y = pixels.tr.y + this.minBoxHeight;
pixels.bl.y = pixels.tr.y + this.minBoxHeight;
}
box.tr = this.map.getNative().PixelToLatLong(pixels.tr);
box.br = this.map.getNative().PixelToLatLong(pixels.br);
box.bl = this.map.getNative().PixelToLatLong(pixels.bl);
var miniMapShape = new VEShape(VEShapeType.Polygon,
[box.tl, box.tr, box.br, box.bl]);
miniMapShape.SetLineColor(this.boxLineColour);
miniMapShape.SetLineWidth(1);
miniMapShape.SetFillColor(this.boxFillColour);
miniMapShape.HideIcon();
this.map.getNative().AddShape(miniMapShape);
}
}
olympics.mapping = olympics.mapping || {};
olympics.mapping.MapMarker = function(ll) {
this.id			= null;
this.title 		= "";
this.content 	= { "_default_": null };
this.icon		= null;
this.latLon		= ll;
this._domElement = null;
this.id = olympics.mapping.MapMarker._nextId++;
this.nativeObj 	= new VEShape(VEShapeType.Pushpin, this.getLatLon().toNative());
this.nativeObj._bbcMarkerId = this.id;
this.valid		= true;
}
olympics.mapping.MapMarker._nextId = 0;
olympics.mapping.MapMarker.prototype = {
setTitle: function(title) {
this.title = title;
this._invalidate();
},
setContent: function(content) {
this.content['_default_'] = content;
this._invalidate();
},
setContentObject: function(label, content) {
this.content[label] = content;
},
setLatLon: function(ll) {
this.latLon = ll;
this._invalidate();
},
setIcon: function(path) {
this.icon = path;
this._invalidate();
},
setId: function(id) {
this.id = id;
},
getTitle: function() {
return this.title;
},
getContent: function() {
return this.content['_default_'];
},
getContentObject: function(label) {
return this.content[label] || null;
},
getLatLon: function() {
return this.latLon;
},
getIcon: function() {
return this.icon;
},
getId: function() {
return this.id;
},
setDOMElement: function(element) {
this._domElement = element;
},
getDOMElement: function() {
if(!this._domElement) {
this._domElement = this.toNative().GetIconElement();
if(!this._domElement) {
this._domElement = this.nativeObj.Primitives[0]._iconElement;
}
}
return this._domElement;
},
isInView: function() {
var el = glow.dom.get(this.getDOMElement());
if(!el) return false;
var offset = el.offset;
if( offset.x == 0 && offset.y == 0 ) {
return false;
} else {
return true;
}
},
validate: function() {
this.nativeObj.SetTitle(this.getTitle());
this.nativeObj.SetDescription(this.getContent());
this.nativeObj._bbcMarkerId = this.id;
if (this.icon) {
this.nativeObj.SetCustomIcon(this.icon);
}
this.valid = true;
},
toNative: function() {
if(!this.valid) {
this.validate();
}
return this.nativeObj;
},
_invalidate: function() {
this.valid = false;
}
}
olympics.mapping = olympics.mapping || {};
olympics.mapping.MapTileLayer = function(parentMap, tileSourceURL, label, args) {
this.parentMap = parentMap;
this.markers = [];
this.visible = true;
this._addedToMap = false;
this.layerID = label;
var args = args || {};
this.bounds = args["bounds"] ? args["bounds"] : null;
var nativeBoundsRect = null;
if(this.bounds) {
nativeBoundsRect = new VELatLongRectangle( this.bounds[0].toNative(), this.bounds[1].toNative() );
}
if(olympics.util.LOGGING) console.log("MapTileLayer: Setting bounds rectangle to: ", nativeBoundsRect);
this.nativeLayer = new VETileSourceSpecification(label, tileSourceURL, null, [nativeBoundsRect]);
}
olympics.mapping.MapTileLayer.prototype = {
toNative: function() {
return this.nativeLayer;
},
show: function() {
if(!this._addedToMap) {
this.parentMap.getNative().AddTileLayer(this.nativeLayer, false);
this._addedToMap = true;
}
this.parentMap.getNative().ShowTileLayer(this.layerID);
this.visible = true;
},
hide: function() {
this.parentMap.getNative().HideTileLayer(this.layerID);
this.visible = false;
},
isVisible: function() {
return this.visible;
}
}
olympics.mapping = olympics.mapping || {};
olympics.mapping.MapView = function( domElementId,  args) {
this.domElement 	= glow.dom.get("#" + domElementId);
this.domElementId 	= domElementId;
args = args || {}
this.containerWidth = args["width"] || null;
this.containerHeight = args["height"] || null;
this._mapMoving;
this._mapZooming;
this._mapCookieName = "olympics-map";
this._mapCookiePath = "/sol/shared/bsp/hi/olympics2008/map";
this.fixedMap = args["fixedMap"] || false;
this.bridgeNativeEvents = typeof args["bridgeNativeEvents"] == "boolean" ? args["bridgeNativeEvents"] : true;
if(olympics.util.LOGGING) console.log("bridge native events for: %o set to: %o", this.domElementId, this.bridgeNativeEvents);
if (this.containerWidth) {
this.domElement.css('width', this.containerWidth + "px");
}
if (this.containerHeight) {
this.domElement.css('height', this.containerHeight + "px");
}
this.domElement.css('position', 'relative');
this.markerCache = {};
this.layers = [];
this.nativeMap		= new VEMap(this.domElementId);
this.nativeBaseLayer = new VEShapeLayer();
}
olympics.mapping.MapView.prototype = {
display: function(useCookie) {
var useCookie = useCookie || false;
var cookieWasUsed = false;
var mapLoaded = false;
if(useCookie) {
var prevState = olympics.util.Cookie.fetch(this._mapCookieName);
if(prevState && prevState.lat && prevState.lon && prevState.zoom) {
this.nativeMap.LoadMap(new olympics.mapping.LatLon(prevState.lat, prevState.lon).toNative(), prevState.zoom, null, this.fixedMap);
mapLoaded = true;
cookieWasUsed = true;
}
}
if(!mapLoaded) this.nativeMap.LoadMap(null, null, null, this.fixedMap);
if(this.bridgeNativeEvents) this._createNativeHandlers();
this.nativeMap.AddShapeLayer( this.nativeBaseLayer );
return cookieWasUsed;
},
setCenter: function( point) {
this.setCentre(point);
},
setCentre: function(point) {
this.nativeMap.SetCenter(point.toNative());
},
getCentre: function() {
var ll = this.nativeMap.GetCenter();
return new olympics.mapping.LatLon(ll.Latitude, ll.Longitude);
},
setZoom: function(level) {
this.nativeMap.SetZoomLevel(level);
},
getZoom: function() {
return this.nativeMap.GetZoomLevel();
},
setCentreAndZoom: function(point, zoom) {
this.nativeMap.SetCenterAndZoom(point.toNative(), zoom);
},
addMarker: function( marker,  point) {
},
addMarkers: function( markers) {
var nativeMarkers = [];
var i = 0,
len = markers.length;
try {
nativeMarkers = glow.lang.map( markers, function(marker) {
return marker.toNative();
})
} catch(e) {
if(olympics.util.LOGGING) console.warn(e);
}
this.nativeBaseLayer.AddShape(nativeMarkers);
},
openMarkerById: function(id, opts) {
var opts = opts || {};
var marker = this.markerCache[id];
if(olympics.util.LOGGING) console.info("Open marker by id", id);
if(marker === null || typeof marker == "undefined") {
return null;
} else {
var customEvent = new glow.events.Event();
customEvent.source = marker;
if(opts["zoom"]) {
customEvent.zoom = opts.zoom;
}
if(opts["client"]) {
customEvent.client = opts.client;
} else {
customEvent.client = null;
}
glow.events.fire( this, olympics.mapping.MapView.Events.MARKER_CLICK, customEvent );
return marker;
}
},
createLayer: function() {
var layer = new MapLayer();
this.layers.push( layer );
this.nativeMap.AddShapeLayer(layer.toNative());
var self = this;
glow.events.addListener( 	layer,
olympics.mapping.MapLayer.Events.MARKER_ADDED,
function(evt){
self._markerAddedToLayer(evt.data);
});
glow.events.addListener( 	layer,
olympics.mapping.MapLayer.Events.MARKER_REMOVED,
function(evt){
self._markerRemovedFromLayer(evt.data);
});
return layer;
},
getNative: function() {
return this.nativeMap;
},
isMoving: function() {
return this._mapMoving;
},
isZooming: function() {
return this._mapZooming;
},
isOutOfBounds: function(marker) {
var ll = this.getNative().LatLongToPixel( marker.getLatLon().toNative() );
var mLat = ll.y;
var mLon = ll.x;
var currentView = this.getNative().GetMapView();
var br = this.getNative().LatLongToPixel(currentView.BottomRightLatLong);
var tl = this.getNative().LatLongToPixel(currentView.TopLeftLatLong);
var minLat = tl.y;
var maxLat = br.y;
var minLon = tl.x;
var maxLon = br.x;
if(olympics.util.LOGGING) console.log("currentView:: lat: max: %o min: %o, lon: max: %o min: %o", maxLat, minLat, maxLon, minLon);
if(olympics.util.LOGGING) console.log("marker (num):: lat: %o lon: %o", mLat, mLon);
var latOutOfBounds = (mLat < minLat) || (mLat > maxLat) ? true : false;
var lonOutOfBounds = (mLon < minLon) || (mLon > maxLon) ? true : false;
return latOutOfBounds || lonOutOfBounds;
},
_createNativeHandlers: function() {
var self = this;
var extractMarkerFromEvent = function(evt) {
var decision = false;
if(evt.elementID) {
var nativeMarker = self.nativeMap.GetShapeByID(evt.elementID);
if (nativeMarker) {
var marker = self._findMarkerByNativeId(nativeMarker._bbcMarkerId);
marker.setDOMElement(glow.dom.get("#" + evt.elementID)[0]);
if(marker) decision = {source: marker};
}
}
return decision;
}
var storeInCookie = function(markerId) {
var objToStore = self.getCentre().serialise();
objToStore["zoom"] = self.getZoom();
if(markerId) {
objToStore["marker"] = markerId;
}
olympics.util.Cookie.store(self._mapCookieName, objToStore, new olympics.util.Time(30).minutes().fromNow(), self._mapCookiePath);
}
this.nativeMap.AttachEvent(
"onmouseover",
this._createNativeEventToGlowBridge(
olympics.mapping.MapView.Events.MARKER_OVER,
extractMarkerFromEvent,
true
));
this.nativeMap.AttachEvent(
"onmouseout",
this._createNativeEventToGlowBridge(
olympics.mapping.MapView.Events.MARKER_OUT,
extractMarkerFromEvent
));
this.nativeMap.AttachEvent(
"onclick",
this._createNativeEventToGlowBridge(
olympics.mapping.MapView.Events.MARKER_CLICK,
extractMarkerFromEvent
));
this.nativeMap.AttachEvent(
"onclick",
function(evt) {
var marker = extractMarkerFromEvent(evt).source;
if(marker) {
storeInCookie(marker.id);
}
});
this.nativeMap.AttachEvent(
"onstartpan",
function(){
self._mapMoving = true;
});
this.nativeMap.AttachEvent(
"onendpan",
function(){
self._mapMoving = false;
storeInCookie();
});
this.nativeMap.AttachEvent(
"onstartzoomn",
function(){
self._mapZooming = true;
});
this.nativeMap.AttachEvent(
"onendzoom",
function(){
self._mapZooming = false;
storeInCookie();
});
},
_createNativeEventToGlowBridge: function(externalEventName, firingCondition, stopPropagation, internalEvent) {
var self = this;
var stopPropagation = stopPropagation || false;
return function(evt) {
var customEvent = new glow.events.Event();
var shouldFire = firingCondition(evt);
if (shouldFire) {
customEvent = self._mergeObjects(shouldFire, customEvent);
if(olympics.util.LOGGING) console.log("Bridging event (%o) Internal event obj: %o - External event obj: %o [stopProp? %o]", externalEventName, evt, customEvent, stopPropagation);
glow.events.fire(self, externalEventName, customEvent);
}
return stopPropagation;
}
},
_mergeObjects: function(source, target) {
var mergedObject = {};
var source = source || {};
var target = target || {};
for(prop in target) {
mergedObject[prop] = target[prop];
}
for(prop in source) {
mergedObject[prop] = source[prop];
}
return mergedObject;
},
_markerAddedToLayer: function(marker) {
if(marker) this.markerCache[marker.id] = marker;
},
_markerRemovedFromLayer: function(marker) {
if(marker) delete this.markerCache[marker.id];
},
_findMarkerByNativeId: function(id) {
var marker = this.markerCache[id];
return typeof marker == "undefined" ? null : marker;
}
}
olympics.mapping.MapView.Events = {
MARKER_OVER	: "map_view_marker_over",
MARKER_OUT	: "map_view_marker_out",
MARKER_CLICK: "map_view_marker_click"
}
olympics.ui = olympics.ui || {};
olympics.ui.LinkPanel = function(links, context, args) {
this.nativePanel = null;
var args = args || {};
this.linksPerColumn = args["linksPerColumn"] || 6;
this.action			= args["action"] || function() {};
this.name			= args["name"]   || "";
this.width			= args["width"]  || null;
this.height			= args["height"] || null;
this.content 		= this._processLinks(links);
this.context 		= context;
}
olympics.ui.LinkPanel.prototype = {
show: function() {
if(!this.nativePanel) {
this._createNativePanel();
}
this.nativePanel.show();
},
hide: function() {
if(!this.nativePanel) {
this._createNativePanel();
}
this.nativePanel.hide();
},
_createNativePanel: function() {
var panelClassName = "";
if(this.name != "") {
panelClassName = " " + this.name;
}
var linkPanelTemplate =
'<div class="link-panel custom-panel' + panelClassName + '">' +
'<div class="map-panel-pointer glow-infoPanel-pointerT"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerR"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerB"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerL"></div>' +
'<div class="custom-panel-content">' +
'<div class="glow-panel-hd"></div>' +
'<a class="glow-panel-close" href="#" title="' + olympics.lang["PANEL_CLOSE_BUTTON_LABEL"] + '"><span>X</span></a>' +
'<div class="glow-panel-bd"></div>' +
'<div class="glow-panel-ft"></div>' +
'</div>' +
'</div>';
this.nativePanel	= new glow.widgets.InfoPanel(this.content, { pointerPosition:"t",
context: this.context,
template: linkPanelTemplate,
pointerRegisters: {
t: {x: "40", y: 0},
r: {x: "100%", y: "50%"},
b: {x: "50%", y: "100%"},
l: {x: 0, y: "50%"}
} ,
anim: "fade",
width: this.width,
height: this.height
});
var self = this;
glow.events.addListener( this.nativePanel.container, "click", function(evt){
self.action(evt.source);
});
},
_processLinks: function(links) {
var links 		= glow.dom.get(links);
var numLinks 	= links.length;
var content		= glow.dom.create("<div id=\"panel-container\"></div>");
var i = 0;
var numCols = Math.floor(numLinks/this.linksPerColumn);
var group = 0;
for(; i < numLinks; i += this.linksPerColumn) {
var column = glow.dom.create('<ol class="group-' + group + '"></ol>');
var linkItemsForColumn = links.slice( i, i + this.linksPerColumn);
column.append( linkItemsForColumn );
content.append( column );
group++;
}
content.append(glow.dom.create("<div> </div>").css("clear", "both"));
return content;
}
}
olympics.ui = olympics.ui || {};
olympics.ui.LocationShortcuts = function(mapView, domElement, args){
this._mapView 		= mapView;
this._domElement	= domElement;
this._shortcuts 	= new glow.dom.NodeList();
}
olympics.ui.LocationShortcuts.prototype = {
_shortcuts: null,
addShortcut: function(args) {
var args 	= args || {};
var label 	= args["label"] 	|| "";
var latLon = args["latLon"] 	|| null;
var zoom	= args["zoom"]		|| 0;
var shortcut = this._createShortcutAndAddEvent(
"shortcut-"+this._shortcuts.length, label, label, "shortcut jumpToArea",
{ point:latLon, zoom:zoom } );
this._shortcuts.push(shortcut);
this._domElement.append(shortcut);
return shortcut;
},
removeShortcut: function(shortcutId) {
},
_createShortcutAndAddEvent: function(domId, contentHTML, title, classNames, jumpSpec) {
var self = this;
var element = glow.dom.create("<div id=\"" + domId + "\" class=\"" + classNames + "\" title=\"" + title + "\">" + contentHTML + "</div>");
glow.events.addListener(element, "click", function(evt) {
self._jumpToMapViewLocation(jumpSpec)
});
return element;
},
_jumpToMapViewLocation: function(jumpSpec) {
if(olympics.util.LOGGING) console.log("Jump to method: %o", jumpSpec);
var point 	= jumpSpec["point"] || this._mapView.getCenter();
var zoom 	= jumpSpec["zoom"] 	|| this._mapView.getZoom();
this._mapView.getNative().SetCenterAndZoom(point.toNative(), zoom);
}
}
olympics.ui = olympics.ui || {};
olympics.ui.Panel = function( element,  args,  nativeArgs){
this.nativePanel = null;
var args = args || {};
var nativeArgs = nativeArgs || {};
this.type 			= args["type"] || olympics.ui.Panel.Types.DIRECTED_PANEL;
this.closeButton 	= args["closeButton"] ? true : false;
this.context		= args["context"] || null;
this.panelWidth		= args["width"] || 400;
this.panelHeight	= args["height"] || 400;
this._currentMarkerId = null;
this.position		= null;
var hoverPanelTemplate =
'<div class="hover-panel custom-panel">' +
'<div class="map-panel-pointer glow-infoPanel-pointerT"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerR"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerB"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerL"></div>' +
'<div class="custom-panel-content">' +
'<div class="glow-panel-hd"></div>' +
'<a class="glow-panel-close" href="#" title="' + olympics.lang["PANEL_CLOSE_BUTTON_LABEL"] + '">X</a>' +
'<div class="glow-panel-bd"></div>' +
'<div class="glow-panel-ft"></div>' +
'</div>' +
'</div>';
var clickPanelTemplate =
'<div class="click-panel custom-panel">' +
'<div class="map-panel-pointer glow-infoPanel-pointerT"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerR"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerB"></div>' +
'<div class="map-panel-pointer glow-infoPanel-pointerL"></div>' +
'<div class="custom-panel-content">' +
'<div class="glow-panel-hd"></div>' +
'<a class="glow-panel-close" href="#" title="' + olympics.lang["PANEL_CLOSE_BUTTON_LABEL"] + '"><span>X</span></a>' +
'<div class="glow-panel-bd"></div>' +
'<div class="glow-panel-ft"></div>' +
'</div>' +
'</div>';
switch(this.type) {
case olympics.ui.Panel.Types.DIRECTED_PANEL:
nativeArgs['template'] = hoverPanelTemplate;
nativeArgs['width'] = this.panelWidth;
this.nativePanel = new glow.widgets.InfoPanel(element, nativeArgs);
break;
case olympics.ui.PANEL:
default:
this.nativePanel = new glow.widgets.InfoPanel( element,
{ modal	: false,
anim	: "fade",
template: clickPanelTemplate,
pointerPosition: 'l',
width: this.panelWidth });
this.invalidateContext();
break;
}
if(!this.closeButton) {
this.nativePanel.container.get(".glow-panel-close").css("display", "none");
}
var panel = this;
glow.events.addListener( this.nativePanel.container.get(".glow-panel-close"),
"click",
function() {
panel.hide();
return true;
});
}
olympics.ui.Panel.prototype = {
getNativePanel: function() {
return this.nativePanel;
},
pointToAndShow: function(context) {
this.pointTo(context);
this.show();
},
show: function(){
if(this.context) {
var elOffset = glow.dom.get(this.context).offset();
if(olympics.util.LOGGING) console.log("Panel.show(): elOffset: ", elOffset);
if( elOffset.x == 0 && elOffset.y == 0 ) {
if(olympics.util.LOGGING) console.log("Panel.show(): elOffset is 0,0 so exiting.", elOffset);
return;
} else {
this.nativePanel.show();
}
}
},
hide: function() {
this.invalidateContext();
this.nativePanel.hide();
},
reposition: function() {
this.nativePanel.setPosition();
},
isVisible: function() {
return this.nativePanel.isShown;
},
pointTo: function(context) {
this.context = context;
this.nativePanel.setContext(context);
},
invalidateContext: function() {
this.context = null;
this._currentMarkerId = null;
},
setContent: function(contentObj) {
var contentObj = contentObj || {};
if(contentObj["title"] && contentObj["title"].length > 0) {
this.nativePanel.header.html( contentObj["title"] );
} else {
this.nativePanel.header.html( "  " );
}
if(olympics.util.LOGGING) console.log("set native panel with header: ", contentObj["title"]);
if(contentObj["body"] && contentObj["body"].length > 0) {
this.nativePanel.body.html( contentObj["body"] );
} else {
this.nativePanel.body.html( "  " );
}
if(contentObj["footer"] && contentObj["footer"].length > 0) {
this.nativePanel.footer.html( contentObj["footer"] );
} else {
this.nativePanel.footer.html( "  " );
}
},
setCurrentMarkerId: function(id) {
this._currentMarkerId = id;
},
getCurrentMarkerId: function() {
return this._currentMarkerId;
},
_calculatePositionWithinContext: function(context, panelWidth, panelHeight, alignment) {
var contextOffset = context.offset();
var x = contextOffset.x + context.width() - panelWidth;
var y = contextOffset.y + ((context.height() - panelHeight) / 2);
x = x ? x : 0;
y = y ? y : 0;
return {x:x, y:y}
}
}
olympics.ui.Panel.Types = {
DIRECTED_PANEL	: "InfoPanel",
PANEL			: "Panel"
}
olympics.ui = olympics.ui || {};
olympics.ui.ToolbarPanel = function(mapView) {
this._container;
this._toolbarWidth = "55em";
this._toolbarButtons = {};
this._nativeToolbar = glow.dom.create("<div id=\"toolbarContainer\"></div>");
glow.dom.get("#map_view_container").prepend(this._nativeToolbar);
glow.dom.get("#MSVE_navAction_toggleGlyphWrapper").remove();
glow.dom.get("#MSVE_navAction_topBar").remove();
}
olympics.ui.ToolbarPanel.prototype = {
addButton: function(args) {
var args 		= args || {};
var type		= args["type"];
var label		= args["label"];
var action		= args["action"];
var context 	= args["context"];
var isSelected 	= args["isSelected"] || false;
var iconPath	= args["icon"] || null;
var id			= args["id"];
var domElement = null;
var icon = iconPath ? "<img src=\"" + iconPath + "\" alt=\"\" />" : "";
var idHTML = id ? " id=\"" + id + "\" " : "";
var classes = "class=\"" + "toolbarElement" +   "\"";
switch(type) {
case "panel":
domElement = this._createNativeMapControl(id, icon + "<span>" + label + "</span>", classes, label);
this._nativeToolbar.append(domElement);
break;
case "toggle":
default:
domElement = glow.dom.create("<div " + classes + idHTML + "><label>" + icon + "<span>" + label + "</span><input type=\"checkbox\"></label></div>");
this._nativeToolbar.append(domElement);
domElement.get("input")[0].checked = isSelected;
break;
}
this._toolbarButtons[id] = domElement;
return domElement;
},
updateButtonPlaceholderById: function(buttonId, replaceTarget, replaceWith) {
var button = this._toolbarButtons[buttonId];
var buttonLabel;
if(button) {
button = glow.dom.get(button);
buttonLabel = button.get("span");
var newLabel = buttonLabel.html().replace(replaceTarget, replaceWith);
if(olympics.util.LOGGING) console.log("Called update placeholder ",buttonLabel.text(), buttonId, replaceTarget, replaceWith, newLabel);
buttonLabel.html(newLabel);
}
},
_createNativeMapControl: function(domId, contentHTML, classNames, title) {
var classNames = classNames || "";
var title = title || "";
var element = glow.dom.create("<div id=\"" + domId + "\" " + classNames + " " + classNames + "\" title=\"" + title + "\">" + "<a>" + contentHTML + "</a>" + "</div>");
return element;
}
}
olympics.util = olympics.util || {};
olympics.util = {
LOGGING: false,
formatTime: function(date, format) {
var months = function() {
return [ olympics.lang["JAN"],olympics.lang["FEB"],olympics.lang["MAR"],olympics.lang["APR"],olympics.lang["MAY"],olympics.lang["JUN"],olympics.lang["JUL"],olympics.lang["AUG"],olympics.lang["SEP"],olympics.lang["OCT"],olympics.lang["NOV"],olympics.lang["DEC"]];
}();
var data = {
dd:	date.getDate(),
mmm: months[date.getMonth()],
yyyy: date.getFullYear(),
hh: date.getHours(),
mm: date.getMinutes()
}
if(format.match("{AMPM}")) {
if( data.hh <= 12 ) {
data["AMPM"] = olympics.lang["TIME_AM"];
} else {
data["AMPM"] = olympics.lang["TIME_PM"];
data["hh"] = data["hh"] - 12;
}
}
return glow.lang.interpolate(format, data);
},
randomiseArray: function (arr) {
var random = [];
for (var i = 0; i < arr.length; i++) {
random[i] = arr[i];
}
var shuffler = function (a, b) {var num = Math.round(Math.random() * 2) - 1;return num;};
random.sort(shuffler);
return random;
},
getQueryStringValueForKey: function(key, url) {
var keys = olympics.util.splitQueryStringToKeys(url);
if(keys[key]) {
return keys[key];
}
},
splitQueryStringToKeys: function(query) {
var keyValues = {};
var regexp = /([-+]?[\w.]+)/ig;
var matches = query.match(regexp);
if(matches) {
for(var i=0; i<matches.length; i+=2) {
keyValues[matches[i]] = matches[i+1];
}
}
return keyValues;
},
Cookie: {
store: function(name, object, when, path){
var cookieBaseTemplate = "{name}={data};";
var expiryTemplate = " expires={when};";
var pathTemplate = " path={path};";
var encodedObj = object && typeof object != "string" ? glow.data.encodeJson(object) : "";
var when = when && when.constructor === Date ? when : (1).days().ago();
var path = path ? glow.lang.interpolate(pathTemplate, { path: path }) : "";
var expiry = glow.lang.interpolate(expiryTemplate, {
when: when.toGMTString()
});
var base = glow.lang.interpolate(cookieBaseTemplate, {
name: name,
data: encodedObj
});
document.cookie = base + expiry + path;
},
fetch: function(name){
var data = "";
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) data = c.substring(nameEQ.length,c.length);
}
if (data) {
return glow.data.decodeJson(data);
} else {
return null;
}
}
},
applyPNGFix: function(elements, blankImgPath) {
if(glow.env.ie != 6 && glow.env.ie != 5.5) {
if(olympics.util.LOGGING) console.log("This browser doesn't support applyPNGFix. Exiting.");
return;
}
var f = 'DXImageTransform.Microsoft.AlphaImageLoader';
var applyFilter = function(el, src, method) {
if(el[0].filters[f]) {
if(src) {
el[0].filters[f].enabled = true;
el[0].filters[f].src = src;
el[0].filters[f].sizingMethod = method
} else {
el[0].filters[f].enabled = false;
}
} else if(src) {
var filterCode = 'progid:' + f + '(src="' + src + '",sizingMethod="' + method + '")';
el[0].style.filter += filterCode;
el[0].filters[f].enabled = true;
}
}
var blankImgSrc = blankImgPath || "/sol/shared/bsp/hi/olympics2008/map/css/pngfix/blank.gif";
elements.each(function(i) {
var el = elements.slice(i, i+1);
if(el[0].tagName == "IMG") {
if(el[0].src.match(".png$")) {
if(el[0].currentStyle.width == "auto" || el[0].currentStyle.height == "auto") {
el[0].style.width = el.css("width");
}
applyFilter(el, el[0].src, "scale");
el[0].src = blankImgSrc;
}
}
});
}
}
olympics.util.Time = function(time) {
this.time = time;
}
olympics.util.Time.prototype = {
fromNow: function() { return new Date(new Date().getTime() + this.time) },
ago: function() { return new Date(new Date().getTime() - this.time) },
days: function() { return new olympics.util.Time(this.time * 24 * 60 * 60 * 1000) },
hours: function() { return new olympics.util.Time(this.time * 60 * 60 * 1000) },
minutes: function() { return new olympics.util.Time(this.time * 60 * 1000)}
}
