// 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);
var activitiesConfig;
var TIMES_AGO_ARRAY = new Array(1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8);
function Conduit() { };
Conduit.events = [];
Conduit.loading = false;
Conduit.queryOptions = getOptionsFromQueryString();
Conduit.last_timestamp = 0;

//init activities config
jQuery(document).ready(function(){
    getActivityTypesConfig();
});


// ConduitEvent object definition; these are the objects we'll display on the map(s)
function ConduitEvent(event_hash) {
    var typeConfig = activitiesConfig[event_hash['Type']];
    this.event_type = event_hash['Type'];	
    this.time = event_hash['Time'];
	this.latitude = event_hash['LatLong']['Latitude'];
	this.longitude = event_hash['LatLong']['Longitude'];
	
    //search activity
    if (typeConfig.TypeId == 4) {
	    this.title_graphic = "<img class='titleGraphic' src='images/infowindows/search2.png'>";
	}
	else {
	    this.title_graphic = "<img class='titleGraphic' src='" + typeConfig.Icon + "'>";
	}

	this.minutes_ago = event_hash['MinutesAgo'];
	this.isExtended = (event_hash['Title'] != undefined);
	//this.time_ago = this.minutes_ago < 1 ? 'Less than a minute ago' : parseInt(this.minutes_ago) + ' minute ago';	
	    try {
	        var secondsAgo = TIMES_AGO_ARRAY[Math.floor(Math.random() * (TIMES_AGO_ARRAY.length - 1))];
	        if (secondsAgo == 1) {
	            this.timeAgo = "1 second ago";
	        }
	        else {
	            this.timeAgo = secondsAgo + " seconds ago";
	        }
	    }
	    catch (e) {
	        this.timeAgo = null;
	    }

	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/>";

	    if (event_hash['LogoUrl']) {
	        var logoImage = new Image();
	        logoImage.src = event_hash['LogoUrl'];

            // make it non klickable for wibiya
	        if (typeConfig.ProductId == 2) {
	            this.message = "<br/><img class='toolbarLogo' src='" + event_hash['LogoUrl'] + "' /><br/>";
	        } else {
	            this.message = "<br/><a href='" + event_hash['LogoUrlLinkTarget'] + "' target='new'><img class='toolbarLogo' src='" + event_hash['LogoUrl'] + "' /></a><br/>";
            }

	        
	    }

	    if (event_hash['Message'].indexOf('<br') > -1) {
	        this.message += event_hash['Message'].length > 0 ? event_hash['Message'] + '<br/>' : '';
	    }
	    else {
	        this.message += event_hash['Message'].length > 0 ? '<br/>' + event_hash['Message'] + '<br/>' : '';
	    }		
	}
}

// What should the infoWindowText be for this event?
ConduitEvent.prototype.infoWindowText = function() {
	if (this.message.length)
	    return "<div id=time-ago>" + this.timeAgo + "</div>" + this.title_graphic + "<div class='infoWindowText'>" + this.message + "<br/>" + this.whereWhen + "</div>";
	else
	    return "<div id=time-ago>" + this.timeAgo + "</div>" + this.title_graphic + "<div class='infoWindowText'>" + this.whereWhen + "</div>";
}

// Utility function to get browser window width and height
function getWindowWidthHeight () {
	var myWidth = 0, myHeight = 0;
	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: Conduit.queryOptions.url, type: "POST", processData: false,
		    contentType: "application/json",
		    timeout: 50000,
		    dataType: 'text',
		    data: JSON2.stringify({ type: Conduit.queryOptions.event_type, timestamp: Conduit.last_timestamp }),
		    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';
	//alert(options.url);
	
	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);
	}
})();
/*************************************/

// get the xml of events to be shown on the map when the application starts
// for each event call the show2 function with the longitude and latitude of the events and with an index represeting the nubmer of th event
function showFirstEvents(xml) {
    try {
        var balloonsInterval = 5500;
        $(xml).find("Activity").each(function(index) {
            var x = $(this).find("Longitude").text();
            var y = $(this).find("Latitude").text();
            Show2(x,y,index+1);

        });       
    }

    catch (e) {
        //GetData(true);
        alert("couldn't load the startup events");
    }
}


// this function gets the first events data from an outside source in xml
function GetData(cache) {
    $.ajax({
        url: '/ActivitiesService.asmx/GetClientStartupActivities',
        type: "GET",
        timeout: 50000,
        dataType: "xml",
        error: function(xhr) {
        alert("couldn't load the startup events")
        },
        success: showFirstEvents

    });
}

function getCacheData() {
    return "{\"d\":{\"__type\":\"BrandToolbar.WebServices.ConduitLive.Logic.Protocol.ActivityFrameResponse\",\"Frame\":{\"Duration\":18000,\"Activities\":[{\"LatLong\":{\"Latitude\":36.9870148,\"Longitude\":10.1291}},{\"LatLong\":{\"Latitude\":45.5540848,\"Longitude\":3.067585}},{\"LatLong\":{\"Latitude\":40.2404861,\"Longitude\":-86.48908}},{\"LatLong\":{\"Latitude\":48.60993,\"Longitude\":2.35662436}},{\"LatLong\":{\"Latitude\":38.47480,\"Longitude\":-94.5703125}},{\"LatLong\":{\"Latitude\":39.332031,\"Longitude\":-91.0546875}},{\"LatLong\":{\"Latitude\":37.820488,\"Longitude\":-84.0234375}},{\"LatLong\":{\"Latitude\":32.6554097,\"Longitude\":-90.878906}},{\"LatLong\":{\"Latitude\":21.8995603,\"Longitude\":-99.84375}},{\"LatLong\":{\"Latitude\":26.07388,\"Longitude\":-80.68359}},{\"LatLong\":{\"Latitude\":18.268304,\"Longitude\":-97.38281}},{\"LatLong\":{\"Latitude\":26.546602,\"Longitude\":-103.886718}},{\"LatLong\":{\"Latitude\":42.7771255,\"Longitude\":-71.71875}},{\"LatLong\":{\"Latitude\":44.18010,\"Longitude\":-95.27343}},{\"LatLong\":{\"Latitude\":7.315976,\"Longitude\":-72.94921}},{\"LatLong\":{\"Latitude\":3.1156515,\"Longitude\":-66.4453125}},{\"LatLong\":{\"Latitude\":34.123022,\"Longitude\":-81.5625}},{\"LatLong\":{\"Latitude\":52.02365,\"Longitude\":-104.0625}},{\"LatLong\":{\"Latitude\":51.039552,\"Longitude\":-102.4804}},{\"LatLong\":{\"Latitude\":36.135509,\"Longitude\":-95.44921875}},{\"LatLong\":{\"Latitude\":-0.398433,\"Longitude\":-56.25}},{\"LatLong\":{\"Latitude\":-3.3847,\"Longitude\":-50.4492187}},{\"LatLong\":{\"Latitude\":0.304686,\"Longitude\":-61.699218}},{\"LatLong\":{\"Latitude\":-1.98007,\"Longitude\":-58.359375}},{\"LatLong\":{\"Latitude\":2.9401157,\"Longitude\":-75.05859}},{\"LatLong\":{\"Latitude\":17.095992,\"Longitude\":-12.83203}},{\"LatLong\":{\"Latitude\":14.048489,\"Longitude\":-14.23828}},{\"LatLong\":{\"Latitude\":30.55973,\"Longitude\":-7.207031}},{\"LatLong\":{\"Latitude\":12.851793,\"Longitude\":-5.2734375}},{\"LatLong\":{\"Latitude\":7.4902925,\"Longitude\":-4.921875}},{\"LatLong\":{\"Latitude\":39.73873,\"Longitude\":-4.21875}},{\"LatLong\":{\"Latitude\":45.42724,\"Longitude\":0.87890}},{\"LatLong\":{\"Latitude\":44.68219,\"Longitude\":3.8671875}},{\"LatLong\":{\"Latitude\":51.14994,\"Longitude\":6.6796875}},{\"LatLong\":{\"Latitude\":45.5504741,\"Longitude\":8.96484375}},{\"LatLong\":{\"Latitude\":42.258881,\"Longitude\":12.48046875}},{\"LatLong\":{\"Latitude\":47.485533,\"Longitude\":13.359375}},{\"LatLong\":{\"Latitude\":37.12295,\"Longitude\":14.23828125}},{\"LatLong\":{\"Latitude\":34.703085,\"Longitude\":4.921875}},{\"LatLong\":{\"Latitude\":33.098291,\"Longitude\":1.58203125}},{\"LatLong\":{\"Latitude\":46.526619,\"Longitude\":19.511718}},{\"LatLong\":{\"Latitude\":55.750200,\"Longitude\":9.66796875}},{\"LatLong\":{\"Latitude\":44.18010,\"Longitude\":21.26953}},{\"LatLong\":{\"Latitude\":52.239462,\"Longitude\":-88.59375}},{\"LatLong\":{\"Latitude\":50.371628,\"Longitude\":-84.375}},{\"LatLong\":{\"Latitude\":52.45422,\"Longitude\":-71.3671875}},{\"LatLong\":{\"Latitude\":50.48360,\"Longitude\":-91.0546875}},{\"LatLong\":{\"Latitude\":48.31047,\"Longitude\":-76.640625}},{\"LatLong\":{\"Latitude\":59.33169,\"Longitude\":-72.94921}},{\"LatLong\":{\"Latitude\":55.65114,\"Longitude\":-96.8554}},{\"LatLong\":{\"Latitude\":-3.735631,\"Longitude\":-65.21484}},{\"LatLong\":{\"Latitude\":-8.105638,\"Longitude\":-55.72265}},{\"LatLong\":{\"Latitude\":-13.11443,\"Longitude\":-53.0859375}},{\"LatLong\":{\"Latitude\":-10.361032,\"Longitude\":-60.8203125}},{\"LatLong\":{\"Latitude\":27.0173747,\"Longitude\":-0.87890625}},{\"LatLong\":{\"Latitude\":42.9060147,\"Longitude\":26.015625}},{\"LatLong\":{\"Latitude\":23.359739,\"Longitude\":3.33984375}},{\"LatLong\":{\"Latitude\":52.45422,\"Longitude\":18.984375}},{\"LatLong\":{\"Latitude\":39.467864,\"Longitude\":29.1796875}},{\"LatLong\":{\"Latitude\":18.93469,\"Longitude\":5.625}},{\"LatLong\":{\"Latitude\":15.40849,\"Longitude\":5.09765625}},{\"LatLong\":{\"Latitude\":31.463655,\"Longitude\":9.84375}},{\"LatLong\":{\"Latitude\":49.92104,\"Longitude\":28.125}},{\"LatLong\":{\"Latitude\":21.736370,\"Longitude\":-2.109375}},{\"LatLong\":{\"Latitude\":9.229357,\"Longitude\":5.44921875}},{\"LatLong\":{\"Latitude\":44.682194,\"Longitude\":-102.3046}},{\"LatLong\":{\"Latitude\":40.6784167,\"Longitude\":-100.72265}},{\"LatLong\":{\"Latitude\":33.97737,\"Longitude\":-98.96484}},{\"LatLong\":{\"Latitude\":58.971157,\"Longitude\":-107.75390}},{\"LatLong\":{\"Latitude\":-7.40895,\"Longitude\":-37.265625}},{\"LatLong\":{\"Latitude\":-16.681098,\"Longitude\":-43.41796}},{\"LatLong\":{\"Latitude\":-18.35730,\"Longitude\":-53.613281}},{\"LatLong\":{\"Latitude\":-8.6273679,\"Longitude\":-47.46093}},{\"LatLong\":{\"Latitude\":-21.98651,\"Longitude\":-47.8125}},{\"LatLong\":{\"Latitude\":-33.6170,\"Longitude\":-55.72265}},{\"LatLong\":{\"Latitude\":-36.635512,\"Longitude\":-58.183593}},{\"LatLong\":{\"Latitude\":-25.842085,\"Longitude\":-49.21875}},{\"LatLong\":{\"Latitude\":-37.6165,\"Longitude\":-64.33593}},{\"LatLong\":{\"Latitude\":42.4478951,\"Longitude\":-73.4000549}}]}}}";
}


function getActivityTypesConfig() {
    $.get("/ActivitiesService.asmx/GetActivitiesConfig", function (result) {
        if (result.childNodes[0].textContent != "Error") {
            activitiesConfig = JSON2.parse(result.childNodes[0].textContent);
        } else {

            alert("couldn't load the activities config")
        }
    });
}

