var map, infoWindow, latestInfoWindow, directionsDisplay, latestDirectionIco, markerObj, directionsService;
var longestLongitude, longestLatitude;
var mapZoom = 15;
var markers = {};
var markerImages = [];
var image_default = '/templates/default/images/poi.png';
var image_contract = '/templates/default/images/poi_orange.png';
var image_hover = '/templates/default/images/poi_red.png';
var image_latest = '';
var getDirections = false;
var start_point_valuePL = $.language('Street,city');
var fuel_pricePL = $.language('hind');
var fuel_consumptionPL = $.language('kulu');
var start_point_value, end_point_value, latest_start_point_value, latest_end_point_value = '';
var directionTimeoutId, selectedTravelMode, drivingDistanceKilometers, drivingDistanceDuration, startingPointTimeoutId, topKeywordsScrollIntervalId;
var direction_end_color = 'black';
var searchDone, repeatCont = false;

function initialize() {

	if(longestLongitude != 0 || longestLatitude != 0){

		var mapOptions = {
			'zoom': parseInt(mapZoom),
			'center': new google.maps.LatLng(longestLongitude, longestLatitude),
			'mapTypeId': google.maps.MapTypeId.ROADMAP
		}
	}
	else{

		var mapOptions = {
			'zoom': 7,
			'center': new google.maps.LatLng(59.471693, 24.738241),
			'mapTypeId': google.maps.MapTypeId.ROADMAP
		}
	}
	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsService = new google.maps.DirectionsService();
	map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
	directionsDisplay.setMap(map);
	google.maps.event.addListener(map, 'mouseover', function() {

		if(latestInfoWindow) latestInfoWindow.close();
	});

	if( markers.length > 0 ){

		markerObj = jQuery.parseJSON(markers);
		$.each(markerObj, function(k, v){

			if(v.longitude != 0 || v.latitude != 0){

				markerByLocation(v);
			}
		});
	}
}

function infowwindowByMartker(obj,marker){

	if(latestInfoWindow) latestInfoWindow.close();

	var content = '';
	if(obj.data.name)
		content+=obj.data.name;
	if(obj.data.phone)
		content+= '<p style="padding-top:5px;">'+obj.data.phone+'</p>';
	if(obj.data.web)
		content+= '<p style="padding-top:5px;"><a href="'+(obj.data.web.indexOf('http://') > -1 ? obj.data.web : 'http://'+obj.data.web)+'" class="_blank">'+obj.data.web+'</a></p>';
	if(obj.data.street)
		content+= '<p style="padding-top:5px;">'+obj.data.street.replace(',', ' ')+
		(obj.data.city ? ', '+obj.data.city.replace(',', ' ') : '')+
		(obj.data.district ? ', '+obj.data.district.replace(',', ' ') : obj.data.district)+
		(obj.data.region ? ', '+obj.data.region.replace(',', ' ') : '')+
		'</p>';

	infoWindow.setContent('<div style="text-align:left;">'+content+'</div>');
	infoWindow.open(map, marker);

	latestInfoWindow = infoWindow;
}


function markerByLocation(obj){

	//var image = obj.have_contract == 1 ? image_contract : image_default;

	var marker = new google.maps.Marker({
		'position': new google.maps.LatLng(obj.longitude, obj.latitude),
		'map': map,
		/*'icon': image,*/
		'animation': google.maps.Animation.DROP,
		'zIndex' : parseInt(obj.zindex)
	});
	infoWindow = new google.maps.InfoWindow();
	markerImages[parseInt(obj.map_link_id)] = marker;

	/*google.maps.event.addListener(marker, 'click', function() {

		infowwindowByMartker(obj, marker);
		end_point_value = (obj.data.street ? obj.data.street : 'viru')+','+(obj.data.city ? obj.data.city : (obj.data.district ? obj.data.district : 'tallinn'))+',Estonia';
		if(start_point_value && end_point_value)
			calcRoute(start_point_value, end_point_value, 'DRIVING');
	});*/
}

function calcRoute(start, end, selectedTravelMode) {

	/*ICO CHANGER*/
	if(latestDirectionIco)
		$('#'+latestDirectionIco).attr({'class' : 'directionType '+latestDirectionIco});
	$('#'+selectedTravelMode).attr({'class' : 'directionType '+selectedTravelMode+'_O'});

	latestDirectionIco = selectedTravelMode;

	/*CALC ROUTE*/

	var selectedMode = google.maps.TravelMode[selectedTravelMode];
	$('.directionType').removeAttr('style');
	$('#routeError').remove();
	$('#'+selectedTravelMode).css({'font-weight' : 'bold', 'color' : 'red'});

	var request = {
		origin:start,
		destination:end,
		travelMode: selectedMode,
		unitSystem: google.maps.UnitSystem.METRIC
	};
	var distanceRequest = {
		origins:[start],
		destinations:[end],
		travelMode: selectedMode,
		unitSystem: google.maps.UnitSystem.METRIC
	};
	directionsService.route(request, function(result, status) {

		if (status == google.maps.DirectionsStatus.OK) {

			directionsDisplay.setDirections(result);
			var distanceService = new google.maps.DistanceMatrixService();
			distanceService.getDistanceMatrix(distanceRequest, function(response, status){

				drivingDistanceKilometers = response.rows[0].elements[0].distance.text;
				drivingDistanceDuration = response.rows[0].elements[0].duration.text;

				$('#drivingDistanceKilometers').html('<p style="margin-left:5px;">'+$.language('Kilomeetreid')+': '+drivingDistanceKilometers+'</p>');
				$('#drivingDistanceDuration').html('<p style="margin-left:5px;">'+$.language('Kuluv aeg')+': '+drivingDistanceDuration+'</p>');
				//$('#starting_point_loader').hide();
			});
		}
		else{

			if(!start_point_value || !end_point_value)
				$('[name=starting_point]').css({'background' : '#ffcccc'});

			if(start_point_value && end_point_value)
				$('.directionType').parents('p').append('<span id="routeError" style="float:left;color:red;">'+$.language('Cannot calculate route')+'</span>');

			//$('#starting_point_loader').hide();
		}
	});
}

function methodToFixLayout( e ) {

    $('.map_inner_content #map_canvas').width($('.map_inner_content').width()-300);
	$('.map_inner_content #map_canvas').height($(window).height()-200);
	$('#map_canvas_left').height($(window).height()-200);
}

$(document).ready(function(){

	$('.map_inner_content #map_canvas').width($('.map_inner_content').width()-300);
	$('.map_inner_content #map_canvas').height($(window).height()-200);
	$('#map_canvas_left').height($(window).height()-200);

	$('#map_canvas_left_adjustment #detail_link').click(function() {

		if(searchDone == 1){

			$('#map_canvas_left_adjustment #detail_link').css({'background' : 'none', 'color' : direction_end_color, 'padding-left' : '0px', 'padding-right' : '0px'});

			if( $('.map_canvas_left_adjustment').css('display') == 'block' ){

				$('.map_canvas_left_adjustment').hide();
			}
			else{

				$('.map_canvas_left_adjustment').show();
			}
		}
		else{

			$('#search1').css({'background' : '#ffcccc'});
		}
	});

	if(typeof google == 'object')
		initialize();
});

$(window).bind("resize", methodToFixLayout);