/*
 *    BBC Travel News Javascript Library
 *    Version: 1.0
 *    Date: 2007-10-23
 *    Author: philip.mcallister@bbc.co.uk
 *
 */


// SETTINGS YOU CAN CHANGE HERE
var bbc_tn_refresh_enable = 1;	// Set to 1 to allow refreshing or 0 to disable
var bbc_tn_refresh = 30;		// Interval between automated refresh ajax requests in seconds
var bbc_tn_refresh_step = 15;	// Number of seconds to add to refresh interval to decrease request rate when there are errors
var bbc_tn_refresh_max = 0;		// Set to a positive, non-zero number and the page will only refresh this number of times
var bbc_tn_timeout = 40;		// Timeout interval for HTTP request in seconds
var bbc_tn_max_timeouts = 20;	// The maximum number of timeouts we care about. After this, we will not add refresh rate increments

// THINGS YOU DON'T WANT TO CHANGE BELOW HERE
var bbc_tn_refresh_ctr = 0;		// Number of times this page has refreshed
var bbc_tn_req_success = 0;		// Holds the request status. Set to 1 if request returned successfully, regardless of content (i.e. 200 or 404 sets this to 1)
var bbc_tn_num_timeouts = 0;	// Holds the total number of timeouts we have seen. If > 3, then slowly increases refresh time by 30 seconds a go until it refreshes only every 10 minutes.
var bbc_tn_region = '';			// Holds the name of the region id we are requesting
var bbc_tn_refresher;			// holds the refresh timer object
var bbc_tn_probable_timeout;	// holds the http timeout object

var bbc_tn_refresh_orig = bbc_tn_refresh;

/*  BBC_TN_getLiveTravel
 *
 *  AJAX-like http request for Travel News.
 *
 *  Usage: BBC_TN_getLiveTravel('cheshire');
 *
 *  region_id	string		Specifies the region to get data for, e.g. 'tyne' or 'virginwestcoast'
 */
function BBC_TN_getLiveTravel(region_id)
{
	// Store our region ID so we can use it in the interval timer
	bbc_tn_region = region_id;
	
	// Only bother doing anything if ajax is supported
	if (bbcjs.http.supported)
	{
		bbc_tn_req_success = 0;		// Reset success flag
		bbc_tn_refresh_ctr++;		// Increase refresh counter
		
		document.getElementById("liveTravelStatus").innerHTML = '<p><img src="/travelnews/images/ajax/loading_white_13x13.gif" alt="Progress indicator" align="absmiddle" width="13" height="13" /> Loading latest travel information ...</p>';
		
		// Make async request to travel api
		var url = '/cgi-perl/travelnews/travel-out.pl/o/html/r/' + region_id + '/';
		req = new bbcjs.http.Request({method:'get',onLoad:_BBC_TN_Handler, onError:_BBC_TN_Error, pass:{} });
		req.send(url);
		
		// Set a timeout to change the status if we don't get a response in a reasonable time
		bbc_tn_probable_timeout = setTimeout("_BBC_TN_weTimedOut()",bbc_tn_timeout * 1000);
		
		
		// If we've reached the max number of refreshes, disable the refresh timer
		if (bbc_tn_refresh_ctr == bbc_tn_refresh_max)
		{
			bbc_tn_refresh_enable = 0;
			clearInterval(bbc_tn_refresher);
		}
		
		
	}

	// If we haven't already, and refresh is enabled, set up the refresh timer
	if (!bbc_tn_refresher && bbc_tn_refresh_enable)
	{
		_BBC_TN_RefreshTimer();
	}
	
}


/*  _BBC_TN_Handler
 *
 *  Callback to handle the ajax response
 *
 *  request		object		Object containing the ajax response
 */
function _BBC_TN_Handler(request)
{
	bbc_tn_req_success = 1;					// Stop 'timeout' message from appearing
	clearTimeout(bbc_tn_probable_timeout);	// Stop 'timeout' message from appearing
	
	// reset the refresh timer to default
	if (bbc_tn_num_timeouts > 0)
	{
		_BBC_TN_RefreshTimer(0);
	}
	bbc_tn_num_timeouts = 0;	// Reset timeout counter
	
	document.getElementById("liveTravelStatus").innerHTML = '<p style="color:#666;">Refreshed: '+BBC_TN_PrintDate()+'</p>';
	new bbcjs.ui.Fader($('liveTravelStatus'), false, 'ddffdd', 'ffffff').fade();

	document.getElementById("liveTravelHolder").innerHTML = '';
	document.getElementById("liveTravelHolder").innerHTML = request.text();
}

/*  _BBC_TN_Error
 *
 *  Callback to handle errors from the ajax response
 *
 *  request		object		Object containing the ajax response
 */
function _BBC_TN_Error(request)
{
	bbc_tn_req_success = 1;
	bbc_tn_num_timeouts++;
	
	// If this is the third time we've timed out, increase refresh rate
	if (bbc_tn_num_timeouts > 2)
	{
		_BBC_TN_RefreshTimer(1);
	}
	
	document.getElementById("liveTravelStatus").innerHTML = '';
	document.getElementById("liveTravelStatus").innerHTML = '<p style="color:#666;">Sorry, we temporarily can\'t refresh the travel information. T: '+bbc_tn_num_timeouts+' R:'+bbc_tn_refresh+'</p>';
	new bbcjs.ui.Fader($('liveTravelStatus'), false, 'ffdddd', 'ffffff').fade();
}

/*  BBC_TN_PrintDate
 *
 *  Function that returns the current date/time in human readable format
 *
 */
function BBC_TN_PrintDate()
{
	var sfx = new Array('st','nd','rd','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','st','nd','rd','th','th','th','th','th','th','th','st');
	var mn = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	var dt = new Date();
	var out = ((dt.getHours() < 10) ? "0" : "") + dt.getHours()
		+ ':'
		+ ((dt.getMinutes() < 10) ? "0" : "") + dt.getMinutes()
		+ ' on '
		+ dt.getDate()
		+ sfx[dt.getDate()]
		+ ' '
		+ mn[dt.getMonth()]
		+ ' '
		+ dt.getFullYear();
	
	return out;
}

/*  _BBC_TN_weTimedOut
 *
 *  Callback function to alter refresh rate if we get too many timeouts or errors
 *
 */
function _BBC_TN_weTimedOut()
{
	if (bbc_tn_req_success == 0)
	{
		bbc_tn_num_timeouts++;
		
		// If this is the third time we've timed out, increase refresh rate
		if (bbc_tn_num_timeouts > 2)
		{
			_BBC_TN_RefreshTimer(1);
		}
		
		document.getElementById("liveTravelStatus").innerHTML = '<p style="color:#666;">Sorry, we temporarily can\'t refresh the travel information. T: '+bbc_tn_num_timeouts+' R:'+bbc_tn_refresh+'</p>';
		new bbcjs.ui.Fader($('liveTravelStatus'), false, 'ffffdd', 'ffffff').fade();

	}
}

/*  _BBC_TN_RefreshTimer
 *
 *  Creates an interval timer to refresh the travel information
 *
 *  action		bool		Boolean. 0 resets the refresh interval, 1 increments the refresh interval, null does nothing
 */
function _BBC_TN_RefreshTimer(action)
{
	// If action = 0, reset interval
	if (action == 0)
	{
		bbc_tn_refresh = bbc_tn_refresh_orig;
	}
	// If action == 1 and we're below max timeouts, add refresh step to the timeout
	else if (action == 1 && bbc_tn_num_timeouts <= bbc_tn_max_timeouts)
	{
		bbc_tn_refresh += bbc_tn_refresh_step;
	}

	// Clear and then reinstantiate the interval timer	
	if (bbc_tn_refresher)
	{
		clearInterval(bbc_tn_refresher);
	}
	if (bbc_tn_refresh_enable)
	{
		bbc_tn_refresher = setInterval('BBC_TN_getLiveTravel(bbc_tn_region)',bbc_tn_refresh * 1000);
	}
}

// RSS Functions
function getRssUrl() { 
	if (document.getElementsByTagName)
	{
		var url = "http://www.bbc.co.uk/travelnews/about/syndication/";
		var tc = "http://www.bbc.co.uk/travelnews/about/syndication/terms/";
		var linkTags = document.getElementsByTagName("link");
		var rssURI;
		for (var i = 0; i < linkTags.length; i++) {if (linkTags[i].getAttribute('title') == "rss") {rssURI = linkTags[i].getAttribute('href');}}
		if (rssURI){document.write('<a href="'+rssURI+'"><img height="15" hspace="0" vspace="0" border="0" width="32" alt="RSS Feed" src="/travelnews/images/furniture/rss_feed.gif" title="Really Simple Syndication" /></a>')}
	}
}

// Some odd old functions
function Over(image) { if(image && document.images && image.src.indexOf("_on.gif")==-1) {image.src = image.src.substring(0,(image.src.indexOf(".gif"))) + "_on.gif";}}

function Out(image) { if(image && document.images && image.src.indexOf("_on.gif")!=-1) {image.src = image.src.substring(0,(image.src.indexOf("_on.gif"))) + ".gif";}}
  
function goback() {
	history.back();
} 

function popup(URL,width,height){
   	var newURL = check_url(URL);           
	popup_window = window.open(newURL,'video','width='+width+',height='+height+',scrollbars=no,resizable=yes,toolbar=no,menubar=no,top=30,left=15');
	if (window.focus) {popup_window.focus();}
	return false;
}

function check_url(URL){
	if (URL.indexOf('?') != -1) {var newURL = URL+'&popup=yes';}
	else {var newURL = URL+'?popup=yes';}
	return newURL;
}


function mainSites(x)
  { if (x != "") { self.location=x; } 
}


function mapLink(x,y)
			{
				window.location.href = "http://www.streetmap.co.uk/streetmap.dll?LatLong2Map?grid=" + x + "," + y + "&arrow=Y&zoom=3Title=Location+of+incident";

			}
function Selector(x){
	if (x != "") { self.location=x; } 
}