/**
 *	hdtraffic.js	- HD Traffic javascript functions
 *
 *	Copyright (c) 2008 TomTom International BV
 *	All rights reserved. Alle rechten voorbehouden.
 */

var intReloadTime				= 60;
var roadNumbers					= null;
var strRoadActive				= false;
var arrRoadCategoriesObjects	= {};
var arrRoadTypes				= [ 'other-road' ];
var strRegion					= 'default';
var timeoutReloader				= null;
var objTotals					= {
										count:	0,
										meters:	0,
										delay:	0
								   };

var converter;
var hdt;

/******************************************************************************
 *	General purpose functions
 */
function hdtreloader()
{
	var boolTimeoutOnly = 0 < arguments.length && arguments[0];
	var objElem;

	// do not reload if only setting timeout is requested
	if ( !boolTimeoutOnly )
	{
		objElem = document.getElementById('tooltip');
		if ( objElem )
			objElem.style.display = 'none';

		hdt.reload();
	}

	if ( timeoutReloader )
	clearTimeout(timeoutReloader);

	timeoutReloader = setTimeout('hdtreloader()', intReloadTime * 1000);
}

function loaded() {
	if (hdt.traffic.incidents)
	{
		hdt.getCanvas('incidents').sort(function(lhs,rhs) { return roadNumbers.compare(lhs.roadNumber, rhs.roadNumber); });
		if ( hdt.traffic.roads && 'default' != hdt.regionName )
			addRoadNumbers(hdt.traffic.roads, roadNumbers);

		try
		{
			$('tt-text').style.display = null;
		}
		catch ( e )
		{
			var objElem = document.getElementById('tt-text');
			if ( objElem && objElem.style )
				objElem.style.display = 'inline';
		}

//		document.getElementById('hdt-count' ).innerHTML = hdt.incidentsCanvas.incidents.length;
	}
	else
		com.tomtom.setCSSProperty('.needsIncidents', 'display', 'none');
}

function openExplain()
{
	var w = window.open('explain.php', 'explain', 'width=650,height=480,resizable=1,toolbar=0,scrollable=0,location=0,top=50');
	w.focus();
	return false;
}

/******************************************************************************
 *	Overview page functions
 */
function createCountryOverview()
{
	var intAge				= hdt.countryOverview.ageMs / 1000;
	var intIncidents		= 0;
	var intTime				= 0;
	var intLength			= 0;
	var strUnitTime			= com.tomtom.Hdt.converter.units.time;
	var strUnitLength		= com.tomtom.Hdt.converter.units.length;
	var objElem				= null;
	var arrCategoryNames	= com.tomtom.RoadNumberOverview[hdt.country];
	var objCategoryIndex	= {};
	var intCount			= arrCategoryNames.length;
	var e;
	var i;
	var j;

	document.getElementById('hdt-time').innerHTML = getUpdatedStatus(intAge);

	// create restricted category index
	for ( i = 0; i < arrCategoryNames.length; ++i )
		objCategoryIndex[i] = { 'name': arrCategoryNames[i], 'count': 0, 'length': 0, 'delay': 0 };

	for ( i = 0; i < hdt.countryOverview.item.length; ++i )
	{
		var boolFound = false;
		var intT;
		var intL;

		for ( j in objCategoryIndex )
			if ( hdt.countryOverview.item[i].name == objCategoryIndex[j].name )
				break;

		if ( 0 < hdt.countryOverview.item[i].delaySeconds )
			intT = com.tomtom.Hdt.converter.time(hdt.countryOverview.item[i].delaySeconds, true, true);
		else
			intT = 0;

		if ( 0 < hdt.countryOverview.item[i].lengthMeters )
			intL = com.tomtom.Hdt.converter.length(hdt.countryOverview.item[i].lengthMeters, true);
		else
			intL = 0;

		objCategoryIndex[j].count	+= hdt.countryOverview.item[i].incidents;
		objCategoryIndex[j].length	+= intL;
		objCategoryIndex[j].delay	+= intT;
	}
		
	// setup overview table
	hdt.countryOverview.item.sort(function(a, b) { if ( a.name < b.name ) return -1; else if ( a.name > b.name ) return 1; else return 0; });
	for ( i in objCategoryIndex )
	{
		var strName = getLocaleRoadType(objCategoryIndex[i].name);

		document.getElementById('hdt-overview-cell-' + i + '-0').innerHTML = strName;
		document.getElementById('hdt-overview-cell-' + i + '-1').innerHTML = objCategoryIndex[i].count;
		document.getElementById('hdt-overview-cell-' + i + '-2').innerHTML = (1 == objCategoryIndex[i].count ? strLocaleReport : strLocaleReports);
		document.getElementById('hdt-overview-cell-' + i + '-3').innerHTML = objCategoryIndex[i].delay + ' ' + strUnitTime;
		document.getElementById('hdt-overview-cell-' + i + '-4').innerHTML = objCategoryIndex[i].length + ' ' + strUnitLength;

		objElem = document.getElementById('hdt-overview-row-' + i);
		try
		{
			objElem.style.display = 'table-row';
		}
		catch ( e )
		{
			objElem.style.display = 'inline';
			for ( j = 0; j <= 4; ++j )
			{
				objElem = document.getElementById('hdt-overview-cell-' + i + '-' + j);
				if ( objElem && objElem.style )
					objElem.style.display = 'inline';
			}
		}

		// update total counts
		intIncidents	+= objCategoryIndex[i].count;
		intTime			+= objCategoryIndex[i].delay;
		intLength		+= objCategoryIndex[i].length;
	}

	for ( i = 0; i < 3 - intCount; ++i )
		document.getElementById('hdt-overview-row-' + i).style.display = 'none';

	// display total counts
	document.getElementById('hdt-overview-cell-total-0').innerHTML = strLocaleTotal;
	document.getElementById('hdt-overview-cell-total-1').innerHTML = intIncidents;
	document.getElementById('hdt-overview-cell-total-2').innerHTML = (1 == intIncidents ? strLocaleReport : strLocaleReports)
	document.getElementById('hdt-overview-cell-total-3').innerHTML = intTime + ' ' + strUnitTime;
	document.getElementById('hdt-overview-cell-total-4').innerHTML = intLength.toFixed(0) + ' ' + strUnitLength;

	objElem = document.getElementById('hdt-overview-row-total');
	try
	{
		objElem.style.display = 'table-row';
	}
	catch ( e )
	{
		objElem.style.display = 'inline';
		for ( j = 0; j <= 4; ++j )
		{
			objElem = document.getElementById('hdt-overview-cell-total-' + '-' + j);
			if ( objElem && objElem.style )
				objElem.style.display = 'inline';
		}
	}
}

function createHdtOverview( strUrl, strApiKey, strCountry, strLanguage )
{
	// default configuration
	var objConfig = {
						numberTiles:
									{
										x: 1,
										y: 2
									},
						tiles:		{
										x:			1,
										y:			23,
										zoomLevel:	10
									},
						size:		{
										x: 150,
										y: 150
									},
						viewport:	{
										x: 105,
										y: 235
									}
					};

	if ( com.tomtom.Hdt.regions && com.tomtom.Hdt.regions[strCountry] )
		com.tomtom.Hdt.setRegions(com.tomtom.Hdt.regions[strCountry]);

	// create HDT object and set country, language
	hdt = new com.tomtom.Hdt(strUrl, strApiKey);
	hdt.setCountry(strCountry);
	hdt.setLanguage(strLanguage);
	hdt.setConfig(objConfig);
	hdt.setRegionOverview();

	hdt.setCanvases(com.tomtom.createTemplateCanvases({
		images: { root: 'hdt' },
		overview: createCountryOverview
	}));

	hdt.display();
	hdtreloader(true);
}


/******************************************************************************
 *	HD Traffic page functions
 */
function updateOverview()
{
	if ( hdt && hdt.traffic && hdt.traffic.overview )
	{
		var intAge = hdt.traffic.overview.ageMs / 1000;
		var intT;
		var intL;

		if ( 0 < hdt.traffic.overview.totalDelaySeconds )
			intT = com.tomtom.Hdt.converter.time(hdt.traffic.overview.totalDelaySeconds, true, true);
		else
			intT = 0;

		if ( 0 < hdt.traffic.overview.totalLengthMeters )
			intL = com.tomtom.Hdt.converter.length(hdt.traffic.overview.totalLengthMeters, true);
		else
			intL = 0;

		document.getElementById('hdt-time'  ).innerHTML = getLocaleDate(new Date());
		document.getElementById('hdt-age'   ).innerHTML = getUpdatedStatus(intAge);
		document.getElementById('hdt-length').innerHTML = intL;
		document.getElementById('hdt-delay' ).innerHTML = intT;
		if ( hdt.incidentsCanvas && hdt.incidentsCanvas.incidents )
			document.getElementById('hdt-count' ).innerHTML = hdt.incidentsCanvas.incidents.length;
		else
			document.getElementById('hdt-count' ).innerHTML = hdt.traffic.overview.count;
	}
}

function addRoadCategories( arrCategories )
{
    var ul					= document.getElementById('road-categories');
	var elemInsertBefore	= document.getElementById('road-categories-other');
	var boolCreateRoadTypes	= 1 >= arrRoadTypes.length;

	if ( !ul || !arrCategories || !elemInsertBefore )
		return;

	for ( var i = arrCategories.length; i > 0; --i )
	{
		var li		= document.createElement('li');
		var type	= arrCategories[i-1].toLowerCase();

		if ( boolCreateRoadTypes )
			arrRoadTypes[arrRoadTypes.length] = 'road-' + (i - 1);

		li.style.overflow	= 'auto';
		li.style.width		= '184px';
		li.innerHTML		= '<label for="limit-roads-' + (i - 1) + '">\n\t' +
									'<a id="limit-roads-' + (i - 1) + '" href="#tomtom-filelijst" onclick="return limitRoads(\'road-' + (i - 1) + '\', \'default\' == hdt.regionName);" />\n\t\t' +
										'<strong>' + (arrCategories[i - 1].length > 1 ? arrCategories[i - 1] : objLocaleRoadTypes[type + 'Roads']) + '</strong>' +
										'</a>\n\t' +
									'<div class="list' + arrCategories[i - 1] + 'Roads">\n\t\t' +
										'<div id="hdt-limit-road-' + type + '"></div>\n\t' +
									'</div>\n\t' +
								'</label>';

		ul.insertBefore(li, elemInsertBefore);
		elemInsertBefore = li;
	}
}

function addRoadNumbers( arrNumbers, objRoadNumbers )
{
    var objCategories	= document.getElementById('road-categories');
	var strCategory;
	var arrNumberList	= [];
	var number;
	var objCategory;
	var objRoadname;
	var i;

	if ( !objCategories )
		return;

	for ( i = 0; i < objRoadNumbers.categories.names.length; ++i )
	{
		arrRoadCategoriesObjects[objRoadNumbers.categories.names[i]] = {
																			listClass:	'list' + objRoadNumbers.categories.names[i] + 'Roads',
																			limit:		$('hdt-limit-road-' + objRoadNumbers.categories.names[i].toLowerCase()),
																			displayed:	false
																		};
	}
	arrRoadCategoriesObjects.Other = {
										listClass:	'listOtherRoads',
										limit:		$('hdt-limit-road-other'),
										displayed:	true
									  };

	for ( i in arrRoadCategoriesObjects )
		arrRoadCategoriesObjects[i].limit.innerHTML = '';

	for ( i in arrNumbers )
		if ( 'undefined' != i && 7 > i.length && -1 != i.search(/[0-9]/) )
			arrNumberList[arrNumberList.length] = i;

	arrNumberList.sort(function(lhs,rhs) { return -1 * roadNumbers.compare(lhs, rhs); });

	for ( i = arrNumberList.length; i-- > 0; )
	{
		objRoadName = arrNumbers[arrNumberList[i]];
		if ( null == objRoadName )
			continue;

		objCategory = objRoadNumbers.translate(arrNumberList[i]);
		if ( 'undefined' == objCategory || !objCategory || 'undefined' == typeof(arrRoadCategoriesObjects[objCategory.category]) )
			strCategory = 'Other';
		else
			strCategory = objCategory.category;

		objCategory = arrRoadCategoriesObjects[strCategory];
		if ( !objCategory.displayed )
		{
			com.tomtom.setCSSProperty('.' + objCategory.listClass, 'display', null);
			objCategory.displayed = true;
		}

		if ( 'string' == typeof(arrNumberList[i]) && -1 == arrNumberList[i].search(/^\s*$/) )
		{
			objCategory				 = objCategory.limit;
			objCategory.innerHTML	+= ('' == objCategory.innerHTML ? '\n\t\t\t' : '\t\t\t<div style="display: none; float: left; text-align: center; width: 9px;"> | </div>\n\t\t\t') +
										'<div style="float: left; width: 42px;">\n' +
										'\t\t\t<a id="' + objRoadName.className + '" href="#tomtom-filelijst" onclick="return onlyRoad(\'' + objRoadName.className + '\');">' +
											arrNumberList[i] + '</a></div>\n';
		}
	}
}

function deactivateRoads()
{
	var name = 0 < arguments.length ? arguments[0] : null;
	var elem;

	for ( var road in hdt.traffic.roads )
	{
		className = hdt.traffic.roads[road].className;
		if ( null == name || name != className )
		{
			elem = $(className);
			if ( elem )
				com.tomtom.removeClass(elem, 'active');
		}
	}
}

function limitRoads( name )
{
	hdt.limitRoadCategory(name);

	deactivateRoads();

	return false;
}

function onlyRoad( name )
{
	var className;

	hdt.limitRoadNumber(name);

	if ( null != name )
	{
		deactivateRoads(name);

		com.tomtom.addClass($(name), 'active');
	}

	return false;
}


function incidentInterceptor( incident, superF )
{
	var location;

	superF(incident);

	if ( incident.primaryLocation && incident.secondaryLocation )
	{
		if ( incident.primaryLocation == incident.secondaryLocation )
			location = strLocaleAt + incident.primaryLocation;
		else
			location = strLocaleBetween + ' ' + incident.secondaryLocation + ' ' + strLocaleAnd + ' ' + incident.primaryLocation;
	}

	if (incident.roadFrom && incident.roadTo)
	{
		incident.roadLocation	= incident.roadFrom + ' &rarr; ' + incident.roadTo;
		incident.location		= location;
	}
	else
		incident.roadLocation = location;

	incident.fullDescription = incident.description;
	if ( null != incident.cause && '' != incident.cause )
		incident.fullDescription += ' ' + strLocaleCausedBy + ' ' + incident.cause.charAt(0).toLowerCase() + incident.cause.substring(1);

	var impact = '';

	if ( incident.delay )
		impact += strLocaleDelay + ' ' + incident.delay + ' '

	if ( incident.length )
		impact += strLocaleLength + ' ' + incident.length + ' '

	if ( '' != impact )
		incident.impact = impact;

	/*
	incident.impact = 'IMPACT: ' + (incident.impact ? incident.impact : '&lt;none&gt;');
	incident.cause = 'CAUSE: ' + (incident.cause ? incident.cause : '&lt;none&gt;');
	incident.description = 'DESC: ' + (incident.description ? incident.description : '&lt;none&gt;');
	incident.fullDescription = 'FULL: ' + (incident.fullDescription ? incident.fullDescription : '&lt;none&gt;');
	incident.location = 'LOC: ' + (incident.location ? incident.location : '&lt;none&gt;');
	*/
}

function setRegion( strRegionParam )
{
	var intTmp		= null;
	var strName		= null;
	var strCountry	= '';
	var boolFound	= false;
	var arrRegions	= com.tomtom.Hdt.getRegions();
	var objWrapper	= document.getElementById('tomtom-map-form');
	var objElem		= null;

	for ( intTmp in arrRegions )
	{
		if ( !strCountry && 'default' == arrRegions[intTmp][0] )
		{
			strCountry = arrRegions[intTmp][1];

			if ( strName && strName.length )
				break;
		}
		if ( arrRegions[intTmp][0] == strRegionParam )
		{
			strName = arrRegions[intTmp][1];
			boolFound = true;

			if ( strCountry && strCountry.length )
				break;
		}
	}

	if ( !boolFound )
	{
		strRegionParam	= hdt.defaultRegion;
		strName			= strCountry;
	}

	strRegion = strRegionParam;
	hdt.setRegion(strRegion);

	strRegion										= hdt.region();
	document.getElementById('hdt-region').innerHTML	= strRegion;

	objElem = document.getElementById('hdt-region-2');
	if ( objElem )
		objElem.innerHTML = strRegion;
}

function changeRegion( strRegion )
{
	location = '?region=' + escape(strRegion);
	return false;
}

function createHdt( strUrl, strApiKey, strCountry, strLanguage, strRegion )
{
	var scheme;

	if ( com.tomtom.Hdt.regions && com.tomtom.Hdt.regions[strCountry] )
		com.tomtom.Hdt.setRegions(com.tomtom.Hdt.regions[strCountry]);

	com.tomtom.Hdt.fillRegionMenu(document.getElementById('region'), strRegion, {'cities': strLocaleMenuCities, 'regions': strLocaleMenuRegions, 'language': strLanguage });

	// create HDT object and set country, language
	hdt = new com.tomtom.Hdt(strUrl, strApiKey);
	hdt.setCountry(strCountry);
	hdt.setLanguage(strLanguage);
	setRegion(strRegion);
	hdt.setSize(731, 398);

	if (com.tomtom.Hdt[strCountry]) converter = com.tomtom.Hdt[strCountry].converter;

	scheme = com.tomtom.RoadNumberScheme[strCountry];
	if ( scheme )
	{
		roadNumbers	= new com.tomtom.RoadNumbers(scheme);
		addRoadCategories(roadNumbers.categories.names);
	}

	hdt.setCanvases(com.tomtom.createTemplateCanvases({
			images: {
				root:					'tomtom-kaart-layer',
				tooltip:				'tooltip',
				tooltipTemplate:		'tooltipText',
				maxIncidentsPerTooltip:	11,
				changeRegionHandle: {
					setter: changeRegion,
					title: function(name) { return strLocaleRegionTitleExtraStart + name + strLocaleRegionTitleExtraEnd; }
				}
			},
			incidents: { 
				root:			'tt-text',
				interceptor:	incidentInterceptor,
				overview:		updateOverview
			}
		},
		{
			roadNumbers:	roadNumbers,
			converter:		converter
		}
	));

	hdt.onLoaded = loaded;
	hdt.display();
	hdtreloader(true);
}
