var ITGoogleMap = {
	map: [],
	directions: [],
	points: ITMapPoints.points,
	markers: [],
	
	recursiveHindex: 1,
	
	goToPrintPage: function()
	{
		center = this.map.getCenter();
		zoom = this.map.getZoom();
		from = URLEncode($('#dir_from_hidden').attr('value'));
		if(!from)
		{
			from = '';
		}
		
		to = URLEncode($('#dir_to').attr('value'));
		
		window.open('print_map.php?x=' +  center.x + '&y=' + center.y  + '&zoom=' + zoom + '&from=' + from + '&to=' + to);  
	},
	
	initMap: function() {
		// Init map objects
		for (i=1;i<=7;i++) {
//			this.resizeMap();
			this.map[i] = new GMap2(document.getElementById("map_contents_"+i));
			
			if(map_print_page)
			{
				this.map[i].setCenter(new google.maps.LatLng(map_y,map_x), map_zoom);
			}
			else
			{
				var pointIndex = i-1;
				this.map[i].setCenter(new google.maps.LatLng(ITMapPoints.points[pointIndex].lat, ITMapPoints.points[pointIndex].lon), 10);
			}
			
			this.map[i].addControl(new GLargeMapControl());
			this.map[i].addControl(new GMapTypeControl());
			// init directions object
			this.directions[i] = new GDirections(this.map[i], document.getElementById("directions"));
		    GEvent.addListener(this.directions[i] , "load", this.onGDirectionsLoad);
	    	GEvent.addListener(this.directions[i] , "error", this.handleDirErrors);
		}
		// Resize on every window resize event
		window.onresize = ITGoogleMap.resizeMap;
	},

	initMain: function() {
		var latlng = new GLatLng(ITMapPoints.generalPointLat,ITMapPoints.generalPointLon);
		var marker = new GMarker(latlng);
		//
	    //this.map.addOverlay(marker);
		//
		if(ITMapPoints.generalPointText) {
			GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml("<div><h3 style='color:black'>" + ITMapPoints.generalPointText + "</h3></div>");
	    	});
		}
		if(ITMapPoints.generalPointText) {
			marker.openInfoWindowHtml("<div><h3 style='color:black'>" + ITMapPoints.generalPointText + "</h3></div>");
		}
	},

	initPoints: function() {

		var e = function(marker, i) {
			return function() {
				if(ITMapPoints.generalPointText){
					marker.openInfoWindowHtml(ITGoogleMap.points[i].text);
				} else {
					marker.openInfoWindowHtml(ITGoogleMap.points[i].text + ITGoogleMap.points[i].address + '<div id="drv-direction" class="drv-direction"><input type="hidden" id="from_location" value="' + ITGoogleMap.points[i].addr + '" /><input id="to_location" type="text" value="" /> <input type="button" value="Submit" onclick="overlayDirections(document.getElementById(\'from_location\').value, document.getElementById(\'to_location\').value, '+i+');" /></div><div id="show-drv-direction" class="show-drv-direction"><a href="javascript:void(0)" onclick="document.getElementById(\'show-drv-direction\').style.display=\'none\'; document.getElementById(\'drv-direction\').style.display=\'block\';">Driving direction</a></div>');
				}
			}
		}

		var latlng, marker;
		for(var i = 0; i<this.points.length; i++) {
			var blueIcon = new GIcon(G_DEFAULT_ICON);
			
			blueIcon.shadow = "http://maps.google.com/intl/en_ALL/mapfiles/ms/micons/msmarker.shadow.png";
			blueIcon.shadowSize = new GSize(59,32);
			latlng = new GLatLng(this.points[i].lat,this.points[i].lon);
			
			if(i<=21){
				blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/red-dot.png";
				blueIcon.iconSize = new GSize(32, 32);
			}else{
				blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/blue-dot.png";
				blueIcon.iconSize = new GSize(32, 32);
			}
			
			var mapIndex = i+1;
			
			marker = new GMarker(latlng, {icon: blueIcon});
			this.markers[i] = marker;
		    this.map[mapIndex].addOverlay(marker);
			GEvent.addListener(marker, "click", e(marker, i));
		}
	},

	initSide: function() {
		var panel = $("#points");
		for (var i = 0; i < this.points.length; i++) {
			if (ITMapPoints.generalPointText) {
				panel.append("<div class=\"markerHelper\" marker=\""+i+"\">"+(i+1)+") "+this.points[i].text+"</div>");
			} else {
				panel.append("<div class=\"markerHelper\" marker=\""+i+"\">"+(i+1)+") "+this.points[i].side_text+"</div>");
			}
		}

		$('.markerHelper').bind('click', ITGoogleMap.helperClick);

	},

	handleDirErrors: function() {
		error = ITGoogleMap.directions.getStatus().code;

		if (error == G_GEO_UNKNOWN_ADDRESS) {
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + error);
		} else if (error == G_GEO_SERVER_ERROR) {
			alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + error);
		} else if (error == G_GEO_MISSING_QUERY) {
			alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + error);
		} else if (error == G_GEO_BAD_KEY) {
			alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + error);
		} else if (error == G_GEO_BAD_REQUEST) {
			alert("A directions request could not be successfully parsed.\n Error code: " + error);
		} else {
			//alert("An unknown error occurred. Error code: " + error);
		}
	},

	onGDirectionsLoad : function() {

	},

	loadDir: function(from, to, mapIndex) {
		// As default, en_US locale is used.
		// TODO: add locale depending on site language
		var i = mapIndex+1; 
		this.directions[i].load("from: " + from + " to: " + to, {locale:map_lang_full_code});
	},

	search: function() {
		from = $('#dir_from').attr('value');
		to = $('#dir_to').attr('value');
		$('#dir_from_hidden').val(from);
		if(from=="" || from==null){
			alert('The field "From" should be filled.');
			return;
		}
		if(to=="" || to==null){
			alert('The field "To" should be filled.');
			return;
		}
		ITGoogleMap.loadDir(from, to);

	},

	helperClick: function() {
		// 1. getMarker
		m_id = parseInt($(this).attr('marker'));
		marker = ITGoogleMap.markers[m_id];
		point = ITGoogleMap.points[m_id];
		// 2. make directions
		//ITGoogleMap.loadDir(point.lat+", "+point.lon, "Hotel Sant`Elena - Calle Buccari 10 - Sant`Elena - 30132 Venezia");
		if(ITMapPoints.generalPointText) {
			ITGoogleMap.loadDir(point.lat+", "+point.lon, $('#dir_to').attr('value'));
		}
		$('#dir_from_hidden').val(point.lat+", "+point.lon);
		// 3. Open marker window
		if(ITMapPoints.generalPointText) {
			marker.openInfoWindowHtml(ITGoogleMap.points[m_id].text);
		} else {
			marker.openInfoWindowHtml(ITGoogleMap.points[m_id].text + ITGoogleMap.points[m_id].address + '<div id="drv-direction" class="drv-direction"><input type="hidden" id="from_location" value="' + ITGoogleMap.points[m_id].addr + '" /><input id="to_location" type="text" value="" /> <input type="button" value="Submit" onclick="overlayDirections(document.getElementById(\'from_location\').value, document.getElementById(\'to_location\').value);" /></div><div id="show-drv-direction" class="show-drv-direction"><a href="javascript:void(0)" onclick="document.getElementById(\'show-drv-direction\').style.display=\'none\'; document.getElementById(\'drv-direction\').style.display=\'block\';">Driving direction</a></div>');
		}
	   // ITGoogleMap.resetHeight();
	},
	
    resetHeight: function() {
		document.getElementById('col_2').style.height = '';
		document.getElementById('col_1').style.height = '';
		ITGoogleMap.recursiveH();
	}, 
	
	recursiveH: function() {
		while(ITGoogleMap.recursiveHindex < 10)
		{
			ITGoogleMap.recursiveHindex++;
			setTimeout('h();', 3000);
			
		}
	},

	resizeMap: function() {
		/*var width = document.getElementById('content').offsetWidth;
		width = parseInt(width);
		//$('.mapElement').attr('width', (parseInt(width) - 220)+"px;");
		document.getElementById('map_contents').style.width = 358;//(width - 192);//(width - 240); were 130 ! change 06.08 for ie compability
		document.getElementById('mapElement').style.width = 348;//(width - 192);//(width - 240);
		//$('#map_contents').attr('width', (parseInt(width) - 220)+"px;");*/
	}
}


google.load("maps", "2.x", {"language" : map_lang_code});
// Call this function when the page has been loaded
function init() {
	ITGoogleMap.initMap();
	ITGoogleMap.initMain();
	ITGoogleMap.initPoints();
	//ITGoogleMap.initSide();

	if(map_print_page && map_from && map_to)
	{
		ITGoogleMap.loadDir(map_from, map_to);
		ITGoogleMap.map.setCenter(new google.maps.LatLng(map_y,map_x), map_zoom);
	}
}

function overlayDirections(to, from, mapIndex)  
{
    var fromAddress = from;
    var toAddress	= to;
    if(fromAddress == "" || fromAddress == null){
		alert('The field "From" should be filled.');
		return;
	}
  
    ITGoogleMap.loadDir(fromAddress, toAddress, mapIndex);
}

/**
 * urlencode the string
 *
 * @param {string} clearString
 * @return {string}
 */
function URLEncode(clearString) {
    if(!clearString){
         return '';
    }
     var clearString = encodeURIComponent(clearString);
     var re = /%20/g;
     return clearString.replace(re, '+');
}

oldMapType = false;
google.setOnLoadCallback(init);

$(document).ready(function(){
	$('#dir_to').val(ITMapPoints.generalPointLat+", "+ITMapPoints.generalPointLon);
});
