var map; // object of the map
var windowOpen = 0; // current state of the info window (0=close;1=open)
var customIcon; // custom defined icon
var gmarkers = []; // all the markers currently displayed - freight map
var optionId = '';
var resultInfoHtml = [];
var openResult = 0;

$(document).ready(function() {
	if( $("#map").length != 0 ) {
		// just for the freight map

		if( $('#mapControlBlock').length > 0 ) {
			// tabs behaviour and data clearing
			$('.mapControl a').click( function() {
				$('.mapResults').css('display','none'); // close the route results panel
				if( !$(this).hasClass('current') ) {
					$('.mapControl').removeClass('current');
					$(this).parent().parent().addClass('current');
					map.clearOverlays(); // clear all markers in the map
					clearMapInputs(); // clear all the select
					gmarkers.length = 0; // reset the markers
					resultInfoHtml = []; // reset the results
					openResult = 0;
					mapLoader();
				}
				return false;
			});

			// event listener for the "Timetables and ports" and "Contact info" select inputs
			// and triggers the click in the respective marker
			$('.mapControl.first, .mapControl.third').click(function(e) {	
				var sId = '#' + $(this).attr('id'); // get id menu
				optionId = $(sId + ' select option:selected').attr('id');
				if( optionId.length > 0 ) {
					if(optionId.substr(7) != openResult) {
						clickTrigger( optionId.substr(7) );
					}
				}
			});

			// close button - results info window
			$('a.infoWindowCloseButton').click(function() {
				$(this).parent().parent().css('display','none');
				// show all markers
				for (var j=0; j<gmarkers.length; j++) {
					gmarkers[j].show();
				}
			});	
		}
		
		// load "Freight map"
		if($("#map.freightPort").length > 0) {
			if (GBrowserIsCompatible()) {
				gMapsFreightPort(portdata);
			}
			// display a warning if the browser was not compatible
			else {
				alert("Sorry, the Google Maps API is not compatible with this browser");
			}
		} 
		else if( $("#map.timetable").length > 0 ) {
			mapLoader();	
		}
		
	}
});


/**
* Loads the map of the freight maps
**/
function mapLoader() {
	if( typeof(window[map]) == 'undefined' ) {
		map = new GMap2(document.getElementById("map"));
	}
	
	var section = $('.mapControl.current li a').attr('id');
	if(GBrowserIsCompatible()) {
		switch(section){
			case 'timetables':
				gMapsTimetable(timetablesAndPortsItems, timetablesAndPortsDepartureInfo);
				break;
			case 'route':
				gMapsRoutes();
				break;
			case 'contact':
				gMapsContactInfo();
				break;
		}
	}
	else {
		// display a warning if the browser was not compatible
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}
}

/**
* Freight port map
* Arguments:
* 	- portdata : array with the places relative to this port
*		ex: [{"coordinates":"52.396017,4.826517","text":"Gate"}];
**/
function gMapsFreightPort(portdata) {
	var centerCoordinates = portdata[0].coordinates.split(',');

	map = new GMap2(document.getElementById("map"));
	map.setCenter(new GLatLng(centerCoordinates[0],centerCoordinates[1]), zoom_level);
	map.setMapType(G_NORMAL_MAP);
	map.addControl(new GLargeMapControl());

	setMarkerIcon("");
	var markerOptions = { };

	for(var p=0; p<portdata.length; p++) {
		var coordAux = portdata[p].coordinates.split(',');
		var lat = coordAux[0];
		var lng = coordAux[1];
		var portPoint = new GLatLng(lat, lng);
		// contents of the info window -  on hover and click
		infoHtml = "";
		infoHtml = '<div class="infoContent" style="display: block; font-size: 12px;">';
		infoHtml = infoHtml + '<h3 style="font-size: 14px; font-weight: bold; margin-bottom: 20px;">'+ portdata[p].text +'</h3>';
		infoHtml = infoHtml + '<div>' + map_i18n.get_directions +': <a href="http://maps.google.com/maps?saddr=&daddr=' + lat + ', ' + lng + '" onclick="window.open(this.href); return false;">' + map_i18n.to_here +'</a>&nbsp; - &nbsp;<a href="http://maps.google.com/maps?saddr=' + lat + ', ' + lng + '&daddr=" onclick="window.open(this.href); return false;">' + map_i18n.from_here +'</a></div>';
		infoHtml = infoHtml + '</div>';

		var portMarker = createMarker(portPoint, infoHtml, markerOptions, infoHtml);
		map.addOverlay(portMarker);
	}
}


/**
* Freight map - Timetables and ports
* Arguments:
* 	- items : list of ports
* 	- info : full ports data
**/
function gMapsTimetable(items, info) {
	populateInputs(items, '.mapControl.current');
	
	map.setCenter(new GLatLng(55.218923,19.763672), 4);
	map.setMapType(G_NORMAL_MAP);
	map.addControl(new GLargeMapControl());

	resultInfoHtml = [];
	var infoHtmlAux = 0;
	var markerId = 0;

	setMarkerIcon("harbor-small");

	for(var key in info) {		
		latlng = info[key].coordinates.split(',');
		var portPoint = new GLatLng(latlng[0],latlng[1]);
		
		var markerOptions = { icon:customIcon, title:info[key].name };
		
		//contents of the info window - on click	
		resultInfoHtml[infoHtmlAux] = "";
		resultInfoHtml[infoHtmlAux] = '<div style="display: block; font-size: 12px; margin-bottom: 15px;">';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<h3 style="font-size: 14px; font-weight: bold; margin-bottom: 15px; width: 350px;">' + info[key].name + '</h3>';
		
		// to
		var toLength = info[key].to.length;
		if( toLength > 0 ) {
			resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<table style="display: block; margin-bottom: 15px;">';
			for(var d=0; d<toLength; d++) {
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr>';
				if(d==0) {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux]+ '<td style="font-weight: bold; width: 50px;">To:</td>';
				}
				else {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<td></td>';
				}
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<td><strong>' + info[key].to[d].name + '</strong> ' + info[key].to[d].frequency + ' ' + map_i18n.departures_per_week;
				
				if(info[key].to[d].ext_url != '' && info[key].to[d].ext_url_text != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + ', <a href="' + info[key].to[d].ext_url + '">' + info[key].to[d].ext_url_text + '</a>';
				}

				if(info[key].to[d].transshipment != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + ', transshipment via ' + info[key].to[d].transshipment;
				}

				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</td>';				
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</tr>';
			}
			resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</table>';
		}

		//from
		var fromLength = info[key].from.length;
		if( fromLength > 0 ) {
			resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<table style="display: block; margin-bottom: 15px;">';
			for(var d=0; d<fromLength; d++) {
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr>';
				if(d==0) {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<td style="font-weight: bold; width: 50px;">From:</td>';
				}
				else {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<td></td>';
				}
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<td><strong>' + info[key].from[d].name + '</strong> ' + info[key].from[d].frequency + ' ' + map_i18n.arrivals_per_week;
				if(info[key].from[d].ext_url != '' && info[key].from[d].ext_url_text != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + ', <a href="' + info[key].from[d].ext_url + '">' + info[key].from[d].ext_url_text + '</a>';
				}
				if(info[key].from[d].transshipment != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + ', transshipment via ' + info[key].from[d].transshipment;
				}
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</td>';
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</tr>';
			}
			resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</table>';
		}
		// links
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<div style="display: block;">';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<a style="margin-right: 15px;" href="' + info[key].link_to_info + '"> <span style="font-size: 10px; vertical-align: middle;">&gt;</span> ' + info[key].name + ' ' + map_i18n.port_information +'</a>';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<a href="' + info[key].link_to_timetable + '"> <span style="font-size: 10px; vertical-align: middle;">&gt;</span> ' + map_i18n.overall_timetable +'</a>';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</div>';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</div>';	
	
		var portMarker = createMarker(portPoint, "", markerOptions, '', markerId);
		map.addOverlay(portMarker);
		
		infoHtmlAux++;
		markerId ++;
	}
}


/**
* Freight map - Contact info
**/
function gMapsContactInfo() {
	map.setCenter(new GLatLng(55.218923,19.763672), 4);
	map.setMapType(G_NORMAL_MAP);
	map.addControl(new GLargeMapControl());

	setMarkerIcon("company");
	var markerOptions = { icon:customIcon };

	resultInfoHtml = [];
	var infoHtmlAux = 0;
	var markerId = 0;

	for(var key in contactPoints) {
		var latlng = key.split(',');

		var portPoint = new GLatLng(parseFloat(jQuery.trim(latlng[0])), parseFloat(jQuery.trim(latlng[1])) );

    if(contactPoints[key].contacts_link != "") {
            var contactsLink = contactPoints[key].contacts_link;
    }
    else {
            var contactsLink = "";
    }

		// contents of the info window - on click
		resultInfoHtml[infoHtmlAux] = '<div style="display: block; font-size: 12px;">';
		
		for(var cKey in contactPoints[key]) {
			
			if(cKey != 'name' && cKey != 'city' && cKey != 'contacts_link') {
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<h3 style="font-size: 14px; font-weight: bold; width: 380px">' +  contactPoints[key][cKey].name;
				
				if(contactPoints[key][cKey].service_name != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + ', <a href="' + contactPoints[key][cKey].service_url + '">' + contactPoints[key][cKey].service_name + '</a>';
				}
				
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</h3>';
				if(contactPoints[key][cKey].status != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + contactPoints[key][cKey].status;
				}
			}
			
			if(cKey != 'name' && cKey != 'city' && cKey != 'contacts_link') {
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<h4 style="font-size: 12px; font-weight: bold; margin-bottom: 15px; width: 350px;">' + contactPoints[key][cKey].address_title + '</h4>';
								
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<table style="display: block; font-size: 12px;" >';
				
				if(contactPoints[key][cKey].visiting_address1 != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th style="width: 110px; display: block;">' + map_i18n.visiting_address +':</th>';
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<td>' + contactPoints[key][cKey].visiting_address1;
					if(contactPoints[key][cKey].visiting_address1 != "") {
						resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<br />' + contactPoints[key][cKey].visiting_address2;										}
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</td></tr>';
				}

				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th>&nbsp;</th><td></td></tr>';
				
				if( (contactPoints[key][cKey].cs_email || contactPoints[key][cKey].email || contactPoints[key][cKey].sales_email) != null) {
					if (contactPoints[key][cKey].sales_email == null && contactPoints[key][cKey].cs_email == null) {
						resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th>' + map_i18n.e_mail_address +'</th><td>';
						if(contactPoints[key][cKey].email != null) {
							resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + contactPoints[key][cKey].email;
						}
						resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</td></tr>';
					}
					if(contactPoints[key][cKey].cs_email != null) {
						resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th>' + map_i18n.e_mail_to_customer_service +': </th><td>' + contactPoints[key][cKey].cs_email + '</td></tr>';
					}
					if(contactPoints[key][cKey].sales_email != null) {
						resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th>' + map_i18n.e_mail_to_sales +': </th><td>' + contactPoints[key][cKey].sales_email + '</td></tr>';
					}
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th>&nbsp;</th><td></td></tr>';
				}
				
				if(contactPoints[key][cKey].phone != '') {
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th>' + map_i18n.telephone_to_exchange +'</th><td>';
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + contactPoints[key][cKey].phone;
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</td></tr>';
					resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<tr><th>&nbsp;</th><td></td></tr>';
				}
				resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</table>';
			}
		}	
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<div style="display: block;">';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '<a href="'+ contactsLink +'"> <span style="font-size: 10px; vertical-align: middle;">&gt;</span> ' + map_i18n.more_contact_info +'</a>';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</div>';
		resultInfoHtml[infoHtmlAux] = resultInfoHtml[infoHtmlAux] + '</div>';
		
		var portMarker = createMarker(portPoint, '', markerOptions, '', markerId);
		map.addOverlay(portMarker);
		
		infoHtmlAux++;
		markerId ++;
	}

	// prepare array to populate the input field
	var contactInfoListItems = [];
	var i = 0;
	for(var key in contactPoints) {		
		contactInfoListItems[i] = {'name': contactPoints[key].city + ', ' + contactPoints[key].name, 'code': key};
		i++;
	}
	populateInputs(contactInfoListItems, '#companyList');
}


/**
* createMarker - it creates a marker in the map with hover and click 
* info windows;
*
* This function creates a new marker in the map.
* It handles the tooltips both on hover and on clicking.
* Arguments:
* 	- point : the point where the marker will be centered;
* 	- infoHtml : the html of the info window;
* 	- mOptions : options of marker;
* 	- hoverInfoHtml : the html of the tooltip info window;
**/
function createMarker(point, infoHtml, mOptions, hoverInfoHtml, markerId) {
	var marker = new GMarker(point,mOptions);
	marker.mId = markerId;
	// load hover behaviour if there is hover content to be shown
	if(hoverInfoHtml.length > 0) {
		GEvent.addListener(marker, "mouseover", function() {
			if( windowOpen == 0) {
				marker.openInfoWindowHtml(hoverInfoHtml);
			}
		});
		GEvent.addListener(marker, "mouseout", function() {
			if( windowOpen == 0) {
				marker.closeInfoWindow();
			}
		});
	}
	
	if(infoHtml.length > 0) {
		GEvent.addListener(marker, "click", function() {
			marker.closeInfoWindow();
			windowOpen = 1;
			marker.openInfoWindowHtml(infoHtml);
		});
		GEvent.addListener(marker, "infowindowclose", function() {
			marker.closeInfoWindow();
			windowOpen = 0;
		});
	}

	if(infoHtml.length == 0) {
		GEvent.addListener(marker, "click", function() {
			//clickTrigger( marker.Ik.substring(6) );
			clickTrigger( marker.mId );
		});
	}

	gmarkers.push(marker);
	return marker;
}


/**
* Set a custom gmaps icon
*	image - name of the image to be used;
**/
function setMarkerIcon(image) {
	if(image.length == 0) {
		image = "default";	
	}

	switch(image) {
		case "harbor":
			customIcon = new GIcon(G_DEFAULT_ICON);
			customIcon.image = img_path + "img/gmaps-icon-"+ image +".png";
			customIcon.iconSize = new GSize(44,17);
			customIcon.iconAnchor = new GPoint(24,1);
			customIcon.infoWindowAnchor = new GPoint(21,8);
			break;
		case "harbor-small":
			customIcon = new GIcon(G_DEFAULT_ICON);
			customIcon.image = img_path + "img/gmaps-icon-"+ image +".png";
			customIcon.iconSize = new GSize(24,10);
			customIcon.iconAnchor = new GPoint(12,5);
			customIcon.infoWindowAnchor = new GPoint(12,4);
			break;
		case "company":
			customIcon = new GIcon(G_DEFAULT_ICON);
			customIcon.image = img_path + "img/gmaps-icon-"+ image +".png";
			customIcon.iconSize = new GSize(10,10);
			customIcon.iconAnchor = new GPoint(5,5);
			customIcon.infoWindowAnchor = new GPoint(5,5);
			break;
		default:
			customIcon = new GIcon(G_DEFAULT_ICON);
			break;
	}
	
	customIcon.shadow  = ""; //remove marker shadow
	customIcon.printShadow = "";
	customIcon.printImage = img_path + "img/gmaps-icon-"+ image +"-print.gif"; 
	customIcon.mozPrintImage = img_path + "img/icon-"+ image +"-moz-print.gif";
	
	customIcon.transparent = img_path + "img/gmaps-icon-"+ image +"-transparent.png";
}


/**
* Populate inputs
*	items - list of options to be inserted;
*	element - element where to add the options;
**/
function populateInputs(items, element) {
	var optionList = '';
	var itemsLength = items.length;
	for(var i=0; i<itemsLength; i++) {
		optionList = '<option id="marker-'+ i +'" value="' + items[i].code + '">' + items[i].name + '</option>';
		$(element + ' select').append(optionList);
	}
}


/**
* Triggers the click marker event
* 	m - the number of the marker
**/
function clickTrigger(m) {
	openResult = m;

	// hide all markers
	for (var i=0; i<gmarkers.length; i++) {
		gmarkers[i].hide();
	}
	
	$('.mapResults #content').html('');
	$('.mapResults #content').html(resultInfoHtml[m]);
	$('.mapResults').show();
}


/**
* Clearing of all the inputs in Freight Map
**/
function clearMapInputs() {
	$('#mapControlBlock select').each(function() {
		$(this).children().slice(1).remove(); //slice(1) because the index 0 is the message
	});
}













