var ajaxPath = '/ajax/';
var cpLoaded = false;

var messageAt = 0;
var messageTimer = 0;
var messageRollTimer = 0;

var announcements = new Array();
var messageShowTime = 5;
var messagePauseTime = 10;

var stationMap;

var mouseMoveTick = 1;
var mouseHideTimer = 0;
var mouseVisible = true;

function initialize() {
	initFlyinfo();

	if (showCp)
		toggleConfigBar();

	/*if (scrollingBg) {
		jQuery('#background').fadeIn(1500);
		backgroundScrollTime = 300;
		bgWidth = parseInt(jQuery('#background').css('width'));

		jQuery('#background').animate({
			left: -1 * bgWidth
		}, backgroundScrollTime*1000, 'linear');
	}*/

	if (customerLogin)
		showMessage('Logged in', 'Successfully logged in!', 'information.png');
	//else if (!isCustomer)
	//	showMessage('Warning', 'Not logged in', 'alert.png');

	/*jQuery('#closemessage').click(function () {
		jQuery('#messagewindow').slideUp(200);
	});*/

	if (events) {
		jQuery('#station_btn').click(showStationWindow);

		stationMap = new StationMap();
	}

	//var pointerHideTime = 15000;
	var pointerHideTime = 180000;

	mouseHideTimer = setTimeout(hideMousePointer, pointerHideTime);

	jQuery(document).bind('mousemove', function() {
		if (mouseMoveTick % 30 == 0) {
			showMousePointer();

			if (mouseHideTimer != 0)
				clearTimeout(mouseHideTimer);

			mouseHideTimer = setTimeout(hideMousePointer, pointerHideTime);
		}

		mouseMoveTick++;
	});


	rollNextMessage();
}

function showMousePointer() {
	// IE7
	if (navigator.appVersion.indexOf('MSIE 7.') != -1) {
		jQuery('body').css('cursor', 'auto');
		jQuery('.clickable').css('cursor', 'pointer');
	}
	else
		jQuery('*').css('cursor', '');

	jQuery('.flight').addClass('hover');

	mouseVisible = true;
}
function hideMousePointer() {
	// IE7
	if (navigator.appVersion.indexOf('MSIE 7.') != -1) {
		var blankCursor = '/images/blank.cur';
		jQuery('body').css('cursor', blankCursor);
		jQuery('.clickable').css('cursor', blankCursor);
	}
	else if (navigator.appVersion.indexOf('MSIE 8.') != -1)
		jQuery('*').css('cursor', 'url(/images/blank.cur)');
	// Others
	else
		//jQuery('*').css('cursor', 'url(/images/blank.cur), none');
		jQuery('*').css('cursor', 'none');

	jQuery('.flight').removeClass('hover');
	mouseMoveTick = 1;

	mouseVisible = false;
}

function rollPeriodicMessages() {
	// This has to be here in case someone opened a message window
	if (!showPeriodicMessages)
		return;

	// No messages? Try again later
	if (announcements.length == 0) {
		messageRollTimer = setTimeout(rollPeriodicMessages, messagePauseTime*1000);
		return;
	}

	// Are we past the last message (announcement array may have changed!)
	if (messageAt >= announcements.length)
		messageAt = 0;

	var announcement = announcements[messageAt];

	messageShowTime = announcement.ontime;
	messagePauseTime = announcement.pause;

	showMessage('Announcement', announcement.message, announcement.icon);

	messageAt++;

	//messageRollTimer = setTimeout(rollPeriodicMessages, messagePauseTime*1000);
}


function showAlert(text) {
	showMessage('Alert', text, 'alert.png');
}

function showMessage(headerText, text, image) {
	clearTimeout(messageRollTimer);
	clearTimeout(messageTimer);

	if (image == '') {
		jQuery('#messageheader').hide();
		jQuery('#messagebody').css('text-align', 'center').css('padding', '0');
	}
	else {
		image = 'images/announcements/' + image;
		//jQuery('#messageheadertext').html('<img src="images/announcements/' + escape(image) + '" alt="" style="vertical-align: middle; width: 2.3em" /> ' + headerText);
		jQuery('#messageheadertext').html(
			'<!--[if gte IE 5.5]><![if lt IE 7]><img src="/images/blank.gif" alt="" id="messageicon" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + escape(image) + '\',sizingMethod=\'scale\');" /><![endif]><![endif]--><!--[if gte IE 7]><!--><img id="messageicon" src="' + escape(image) + '" alt="" /><!--<![endif]-->' + headerText);
		jQuery('#messageheader').show();
		jQuery('#messagebody').css('text-align', '').css('padding', '.7em');
	}

	jQuery('#messagebody').html(text);

	// When external objects are loaded, center window
	jQuery('#messagewindow').find('img, object').load(centerMessage);
	centerMessage();
	setTimeout(function () {
		centerMessage();
		jQuery('#messagewindow').fadeIn(1500);
	}, 500); // Flash and others

	messageTimer = setTimeout(hideMessage, messageShowTime * 1000);
}

function showStationWindow() {
	var station = jQuery(this).text();

	jQuery('#stationwindowheadertext').text(station);
	jQuery('#stationwindow').fadeIn(1000, function() {
		jQuery('#hotel_info').fadeOut(300); // IE bug
	});


	var data = new Object();
	data.station = station;
	if (fahrenheit)
		data.fahrenheit = 'y';

	jQuery('#stationweather').load(ajaxPath + 'weather.php', data); // POST


	if (GBrowserIsCompatible()) {
		jQuery.getJSON('/ajax/ft_data.php', {airport: station}, stationCoordArrived);
	}
}

function stationCoordArrived(jsonCoord) {
	var airportCoord = new GLatLng(jsonCoord.lat, jsonCoord.lon);

	// Initialize map
	stationMap.canvas = new GMap2(document.getElementById('station_map_canvas'));
	stationMap.canvas.setCenter(airportCoord, 0);

	stationMap.canvas.addControl(new GSmallMapControl());
	stationMap.canvas.enableDoubleClickZoom();

	// Marker
	var airportMarker = new GMarker(airportCoord, {icon: stationMap.airportIcon, title: 'Airport'});
	stationMap.canvas.addOverlay(airportMarker);

	// Hotels
	var hotels = new Hotelguide.HotelLayer(stationMap.canvas, {language: 'en', user: '116323', currency: 'EUR', max: 100, popupTitle: false, legend: true});

	jQuery(window).resize(resizeStationMap);
	resizeStationMap();

	stationMap.canvas.setCenter(airportCoord, 11);
}

function resizeStationMap() {
/*	jQuery('#station_map_canvas').css('width', parseInt(jQuery('#stationwindowbody').width()) + 'px')
		.height(parseInt(jQuery('#stationwindow').height()) - parseInt(jQuery('#stationwindowheader').height()) - 20);
*/

	stationMap.canvas.checkResize();
}

function StationMap() {
	this.canvas = null;
	this.airportIcon = new GIcon();

	this.airportIcon.iconSize = new GSize(16, 16);
	this.airportIcon.iconAnchor = new GPoint(8, 8);
	this.airportIcon.image = '/images/airport.png';
}

function hideStationWindow() {
	jQuery('#stationwindow').fadeOut(500);
}


function showNorwegianWindow(url) {
	jQuery('#nwgnwindowiframe').attr('src', url);
	jQuery('#nwgnwindow').fadeIn(1000);
}
function hideNorwegianWindow() {
	jQuery('#nwgnwindow').fadeOut(500);
}



function centerMessage() {
	centerElement('#messagewindow');
}

function hideMessage() {
	jQuery('#messagewindow').fadeOut(2000, function() {
		rollNextMessage();
	});
}

function rollNextMessage() {
	messageRollTimer = setTimeout(rollPeriodicMessages, messagePauseTime * 1000);
}


function changeType(newType) {
	if (newType != infoType)
		cycleType();

	cycleClick();
}

function updateContents() {
	if (window.infoType == 0) {
		jQuery('#departures').css('background-color', staticBtnColor);
		jQuery('#arrivals').css('background-color', pushableBtnColor);

		jQuery('#departures').css('background-image', 'url(' + gradient2 + ')');
		jQuery('#arrivals').css('background-image', 'url(' + gradient1 + ')');
	}
	else {
		jQuery('#departures').css('background-color', pushableBtnColor);
		jQuery('#arrivals').css('background-color', staticBtnColor);

		jQuery('#departures').css('background-image', 'url(' + gradient1 + ')');
		jQuery('#arrivals').css('background-image', 'url(' + gradient2 + ')');
	}


	if (events) {
		if (airlineInfo)
			jQuery('.table_airline').click(showAirlineInfo).attr('title', 'Customer service');

		jQuery('.table_airport').click(showStationWindow).attr('title', 'City information');
		jQuery('.gate_col').attr('title', 'Show gate');
	}

	if (mouseVisible)
		showMousePointer();
	else
		hideMousePointer();
}

function showAirlineInfo() {
	var airlines = new Array();
	airlines['SAS'] = new Object({
		code: 'SK',
		number: '05400',
		service: 'SAS Ground Services',
		homepage: 'www.sas.no'
	});
	airlines['Norwegian'] = new Object({
		code: 'DY',
		number: '815 21 815',
		service: 'Røros Flyservice AS',
		homepage: 'www.norwegian.no'
	});
	airlines['Widerøe'] = new Object({
		code: 'WF',
		number: '810 01 200',
		service: 'SAS Ground Services',
		homepage: 'www.wideroe.no'
	});
	airlines['TAP Portugal'] = new Object({
		code: 'TP',
		number: '810 00 015',
		service: 'Menzies',
		homepage: 'www.flytap.com'
	});
	airlines['British Airways'] = new Object({
		code: 'BA',
		number: '815 33 142',
		service: 'Menzies',
		homepage: 'www.britishairways.com'
	});
	airlines['Aeroflot'] = new Object({
		code: 'SU',
		number: '23 35 62 00',
		service: 'SAS Ground Services',
		homepage: 'www.aeroflot.ru'
	});
	airlines['Air Norway'] = new Object({
		code: 'M3',
		number: '72 52 27 90',
		service: 'SAS Ground Services',
		homepage: 'www.airnorway.no'
	});
	airlines['Air France'] = new Object({
		code: 'AF',
		number: '23 50 20 01',
		service: 'SAS Ground Services',
		homepage: 'www.airfrance.no'
	});
	airlines['Blue 1'] = new Object({
		code: 'KF',
		number: '820 70 210',
		service: 'SAS Ground Services',
		homepage: 'www.blue1.com'
	});
	airlines['Lufthansa'] = new Object({
		code: 'LH',
		number: '815 21 815',
		service: 'Røros Flyservice AS',
		homepage: 'www.lufthansa.com'
	});
	airlines['Pakistan International Airlines'] = new Object({
		code: 'PK',
		number: '22 83 36 16',
		service: 'SAS Ground Services',
		homepage: 'www.piac.com.pk'
	});
	airlines['Danish Air Transport'] = new Object({
		code: 'DX',
		number: '57 74 67 00',
		service: 'Røros Flyservice AS',
		homepage: 'www.dat.dk'
	});
	airlines['KLM'] = new Object({
		code: 'KL',
		number: '22 64 37 52',
		service: 'SAS Ground Services',
		homepage: 'www.klm.com'
	});
	airlines['Czech Airlines'] = new Object({
		code: 'OK',
		number: '47 47 51 51',
		service: 'SAS Ground Services',
		homepage: 'www.czechairlines.com'
	});
	airlines['Finnair Oy'] = new Object({
		code: 'AY',
		number: '810 01 100',
		service: 'Menzies',
		homepage: 'www.finnair.com'
	});
	airlines['Estonian Air'] = new Object({
		code: 'OV',
		number: '815 00 422',
		service: 'SAS Ground Services',
		homepage: 'www.estonian-air.ee'
	});
	airlines['Air Baltic'] = new Object({
		code: 'BT',
		number: '05400 / 810 01 200',
		service: 'SAS Ground Services',
		homepage: 'www.airbaltic.com'
	});
	airlines['Icelandair'] = new Object({
		code: 'FI',
		number: '22 03 40 50',
		service: 'SAS Ground Services',
		homepage: 'www.icelandair.com'
	});
	airlines['SN Brussels Airline'] = new Object({
		code: 'SN',
		number: '23 16 25 68',
		service: 'SAS Ground Services',
		homepage: 'www.brusselsairlines.com'
	});
	airlines['Continental Airlines'] = new Object({
		code: 'CO',
		number: '810 03 630',
		service: 'Menzies',
		homepage: 'www.continental.com'
	});

	var airlineName = jQuery(this).text();
	var airline = airlines[airlineName];

	if (airline)
		showMessage(airlineName, '<a target="_blank" href="' + 'http://' + airline.homepage + '/">' + airline.homepage + '</a><br />Customer service: ' + airline.number, 'information.png');
}

function toggleConfigBar() {
	if (jQuery('#cpbar').css('display') == 'none')
		showConfigBar();
	else
		jQuery('#cpbar').fadeOut(1000);
}

function showConfigBar() {
		if (!cpLoaded) {
			jQuery('#airportselspan').load(ajaxPath + 'cp_data.php', {type: 0, selected: station});
			jQuery('#airlineselspan').load(ajaxPath + 'cp_data.php', {type: 1, selected: airline});
			cpLoaded = true;
		}

		jQuery('#cpbar').fadeIn(1000);
}

// Header button cosmetics
function mouseOverIcon(id) {
	if (id != infoType) {
		if (id == 0)
			jQuery('#departures').css('background-image', 'url(' + gradient3 + ')');
		else
			jQuery('#arrivals').css('background-image', 'url(' + gradient3 + ')');
	}
}
function mouseOutIcon(id) {
	if (id == infoType) {
		if (id == 0)
			jQuery('#departures').css('background-image', 'url(' + gradient2 + ')');
		else
			jQuery('#arrivals').css('background-image', 'url(' + gradient2 + ')');
	}
	else {
		if (id == 0)
			jQuery('#departures').css('background-image', 'url(' + gradient1 + ')');
		else
			jQuery('#arrivals').css('background-image', 'url(' + gradient1 + ')');
	}
}

// Dynamic text size
function measureSize() {
	width = getWindowWidth();

	fontSize = (width/70);

	jQuery('#body').css('font-size', fontSize * (fontFactor/100) + 'px');

	centerMessage();
}

function fadeOutPage() {
	jQuery('#everything').fadeOut(400);
	return false;
}
function submitForm() {
	jQuery('#paramsform').submit();
}
