// conduitvision.js
// (C) 2008 Roundhouse Technologies and Licensed to Conduit
// Permission is granted to use and modify as needed, but may not be redistributed

// Note: to test this in Firefox 3 with a local data source ,
// change the local file same origin policy per below
// http://dojotoolkit.org/pipermail/dojo-contributors/2008-January/008609.html


//resizeWindow(940,720,50,50);

function Conduit() { };
Conduit.events = [];
Conduit.loading = false;
Conduit.queryOptions = getOptionsFromQueryString();
Conduit.type_prefixes = { 1 : 'RSS', 2 : 'RDI', 3 : 'EMC', 4 : 'SPE', 5 : 'ALV', 6 : 'GCL', 7 : 'LCL', 8 : 'WEC', 9 : 'WEC', 10 : 'TBI' };
Conduit.last_timestamp = 0;

// ConduitEvent object definition; these are the objects we'll display on the map(s)
function ConduitEvent(event_hash) {
	this.event_type = event_hash['Type'];
	this.time = event_hash['Time'];
	this.latitude = event_hash['LatLong']['Latitude'];
	this.longitude = event_hash['LatLong']['Longitude'];
	this.type_prefix = Conduit.type_prefixes[this.event_type];
	this.title_graphic = "";//"<img class='titleGraphic' src='images/infowindows/" + this.type_prefix + "_title.png'>";
	this.minutes_ago = event_hash['MinutesAgo'];
	this.isExtended = (event_hash['Title'] != undefined);
	this.time_ago = this.minutes_ago < 1 ? '' : parseInt(this.minutes_ago) + '';
		
	if (this.isExtended) {
		this.whereWhen = 	"<span id='where'>" + 
												(event_hash['City']=='-' || event_hash['City']=="" ?
													titleCaps(event_hash['Country']) :
													titleCaps(event_hash['City']) + ', ' + titleCaps(event_hash['Country']) ) +
											"</span><br/>" ;

		switch(this.type_prefix) {
/*			case 'RSS':
				this.message = "<a href='" + event_hash['MessageLinkTargetUrl'] + "' target='new'>This RSS story</a> is being read by a commnity toolbar user.<br/>";
				break;
			case 'GCL':
				this.message = 'A user launched ' + "<a href='" + event_hash['MessageLinkTargetUrl'] + "' target='new'>this gadget</a> from the community toolbar.<br/>";
				break;*/
			default:
				this.message = event_hash['Message'].length>0 ? event_hash['Message'] + '<br/>' : '';
				break;
		}
		
		if (event_hash['LogoUrl']) {
			var logoImage = new Image();
			logoImage.src = event_hash['LogoUrl'];
			this.message += "";
		}
	}
}

// What should the infoWindowText be for this event?
ConduitEvent.prototype.infoWindowText = function() {
	if (this.message.length)
		return this.title_graphic + "<div class='infoWindowText'>"+ this.message + "<br/>" + this.whereWhen + "</div>";
	else
		return this.title_graphic + "<div class='infoWindowText'>"+ this.whereWhen + "</div>";
}

// Utility function to get browser window width and height
function getWindowWidthHeight () {
	var myWidth = -110, myHeight = -110;
	if(typeof(window.innerWidth) == 'number')
	{
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	}
	else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
	{
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	}
	else if(document.body && (document.body.clientWidth || document.body.clientHeight))
	{
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	
	return {'width' : myWidth, 'height' : myHeight};
}

function resizeWindow (w, h, x, y) {
	// make sure we have a final x/y value
	// pick one or the other windows value, not both
	if (x==undefined) x = window.screenLeft || window.screenX;
	if (y==undefined) y = window.screenTop || window.screenY;
	// for now, move the window to the top left
	// then resize to the maximum viewable dimension possible
	//window.moveTo(0,0);
	//window.resizeTo(screen.availWidth,screen.availHeight);
	// now that we have set the browser to it's biggest possible size
	// get the inner dimensions.  the offset is the difference.
	var inner = getWindowWidthHeight();
	var ox = screen.availWidth-inner.width;
	var oy = screen.availHeight-inner.height;
	// now that we have an offset value, size the browser
	// and position it
	window.resizeTo(w+ox, h+oy);
	//window.moveTo(x,y);
}

// Initiate the continuous display of events on the map
// Note that this works in 2D and 3D modes
function showEvents() {
	var evt;

	loadData();
	if (evt = Conduit.events.pop()) evt.show();
	
	setTimeout(showEvents, (evt && evt.isExtended) ? 4000 : 1800);
}

// Initiate the asynchronous loading of new events in the background
function loadData() {
	if ((Conduit.events.length < 3) && (!Conduit.loading)) {
		Conduit.loading = true;
		$.ajax( { url: "http://youcef.mobcom.fr/globe/test.json", type: "POST", processData: false,
							contentType: "application/json",
							timeout: 10000,
							dataType: 'text',
							success: function(transport) { addEvents(transport); },
							complete: function() { Conduit.loading = false; } });
	}
}

// Parse JSON data received via Ajax into new event objects locally
function addEvents(response) {
	var parsed_response = JSON2.parse(response);
	Conduit.last_timestamp = parsed_response['d']['TimeStamp'];
	var event_hashes = parsed_response['d']['Frame']['Activities'];
	$.each(event_hashes, function(i) { Conduit.events.push(new ConduitEvent(this)) });
	
	// update stats in both 2d/3d
	var stats = parsed_response['d']['Frame']['ActivityStatistics']['Statistics'];
	//console.info(stats);
	$('#newInstalls').html('New toolbar installations: ' + stats['New toolbar installations']);
	$('#toolbarInstalls').html('Other activities: ' + stats['Other activities']);
}

// Extract options from query string

function getOptionsFromQueryString() {

	var options = { event_type: 1,
									isLocal: window.location.toString().substr(0,4)=='file' };
	
	options.url = options.isLocal ?  'Activities.svc' : '/ActivitiesService.asmx/GetLatest';
	
	var str = location.search.substring(1, location.search.length);
	if (str.length < 1) return options;

	// plus => space per http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	str = str.replace(/\+/g, ' ');
	
	// extract name=value arguments
	var args = str.split('&'); // parse out name/value pairs separated via &
	var len = args.length;
	var i;
	
	for (i = 0; i < len; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		 if (pair.length==2)
			options[name] = decodeURIComponent(pair[1]);
		else
		 	options[name] = true;
	}

	if (options.ct) options.url += '&ct=' + options.ct;

	options.extended = (parseInt(options.event_type) > 0);

	return(options);
}

/*************************************/
/*
 * Title Caps
 * 
 * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
 * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
 * License: http://www.opensource.org/licenses/mit-license.php
 */
(function(){
	var small = "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)";
	var punct = "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)";
  
	this.titleCaps = function(title){
		var parts = [], split = /[:.;?!] |(?: |^)["Ò]/g, index = 0;
		
		while (true) {
			var m = split.exec(title);

			parts.push( title.substring(index, m ? m.index : title.length)
				.replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all){
					return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
				})
				.replace(RegExp("\\b" + small + "\\b", "ig"), lower)
				.replace(RegExp("^" + punct + small + "\\b", "ig"), function(all, punct, word){
					return punct + upper(word);
				})
				.replace(RegExp("\\b" + small + punct + "$", "ig"), upper));
			
			index = split.lastIndex;
			
			if ( m ) parts.push( m[0] );
			else break;
		}
		
		return parts.join("").replace(/ V(s?)\. /ig, " v$1. ")
			.replace(/(['Õ])S\b/ig, "$1s")
			.replace(/\b(AT&T|Q&A)\b/ig, function(all){
				return all.toUpperCase();
			});
	};
    
	function lower(word){
		return word.toLowerCase();
	}
    
	function upper(word){
	  return word.substr(0,1).toUpperCase() + word.substr(1);
	}
})();
/*************************************/

