var Mod_Oilstations_Map = Class.create();

Mod_Oilstations_Map.prototype = {

	initialize : function(mapContent, baseStationUrl)
	{
		this.points 			= new Array();
		this.pointsPositions 	= new Array();

		this.pointsAll = new Array();

		this.baseStationUrl = baseStationUrl;

		this.mapContent = mapContent;

		if ($(mapContent))
		{
			if ($('station_id') && $('station_id').value > 0)
			{
				this.map = new GMap2($(this.mapContent));
				this.map.setUIToDefault();
				//this.map.addControl(new GSmallMapControl());
				this.getStation();
			}
			else
			{

				var mapParams = Object.extend(
					{
						lat	 : 52.0500,
						lng	 : 18.9511,
						zoom	: 6
					},
					this.readMapParams()
				);

				if
				(
					mapParams.query &&
					mapParams.query != 'miasto, ulica lub nazwa stacji' &&
					mapParams.query != 'Poland: city, street' &&
					mapParams.query != 'Польша: город, улиса' &&
					mapParams.query != ''
				)
				{
					$('query').value = mapParams.query;
				}

				this.map = new GMap2($(this.mapContent));
				this.map.setUIToDefault();
				this.map.setCenter(
					new GLatLng(
						mapParams.lat,
						mapParams.lng
					),
					mapParams.zoom
				);
				//this.map.addControl(new GSmallMapControl());

				if ($('submit_show_all'))
				{
					$('submit_show_all').onclick = function()
					{
						this.getAllStations();

						return false;

					}.bind(this)
				}

				$('map-search-form').onsubmit = function()
				{
					if ($('search-mode') && $('search-mode').options[$('search-mode').selectedIndex].value == 'list')
					{
						$('phrase').value = $('query').value;
						return true;
					 }
					 else
					 {
						this.getStations(mapContent);
						return false;
					 }
				}.bind(this);

					GEvent.addListener(
					this.map,
					'moveend',
					function()
					{
						this.saveMapParams();

					}.bind(this)
				);

				this.getStations(mapContent);
			}
		}
	},

	writeMapInfo : function(x, y)
	{
		var resultX = '';
		var resultY = '';

		var hourX    = Math.floor(x);
                var minutesX = Math.floor ((x - hourX) * 60);
                var secondsX = Math.floor (( (x - hourX) * 60 - minutesX) * 6000 ) / 100;

                var hourY    = Math.floor(y);
                var minutesY = Math.floor((y - hourY) * 60);

                var secondsY = Math.floor( ((y - hourY) * 60 - minutesY) * 6000 ) / 100;

                resultX = (hourX) + '°' + (minutesX) + "'" + (secondsX);
                resultX = resultX.sub(',' ,'.', 1) + '"N';

                resultY = (hourY) + '°' + (minutesY) + "'" + (secondsY);
                resultY = resultY.sub(',' ,'.', 1) + '"E';

		$('stationMapInfo').update(
			 resultX + '&nbsp;&nbsp;&nbsp;' + resultY
		);
	},

	saveMapParams : function()
	{
		var oil_types	= '';
		var equipment	= '';
		var carts		= '';

		$$('input.carts').each(
			function(el)
			{
				if (el.checked)
				{
					var id = el.id.sub('carts_', '', 1) * 1;
					carts += (carts == '') ? id : ',' + id;
				}
			}
		);
		$$('input.oil_types').each(
			function(el)
			{
				if (el.checked)
				{
					var id = el.id.sub('oil_types_', '', 1) * 1;
					oil_types += (oil_types == '') ? id : ',' + id;
				}
			}
		);
		$$('input.equipment').each(
			function(el)
			{
				if (el.checked)
				{
					var id = el.id.sub('equipment_', '', 1) * 1;
					equipment += (equipment == '') ? id : ',' + id;
				}
			}
		);

		var query =
			$('query').value.
			sub('miasto, ulica lub nazwa stacji', '', 1).
			sub('Poland: city, street', '', 1).
			sub('Польша: город, улиса', '', 1).
			sub('"', '', 10);


		var params =
			 'lat: '		 + this.map.getCenter().lat() + ',' +
			 'lng: '		 + this.map.getCenter().lng() + ',' +
			 'zoom: '		+ this.map.getZoom() + ',' +
			 'oil_types:['	+ oil_types + '],' +
			 'equipment:['	+ equipment + '],' +
			 'carts:['		+ carts + '],' +
			 'query: "'	  + query + '"';

		//cookie.set('MAP_PARAMS', params, 0);
	},

	readMapParams : function()
	{
		if (cookie.get('MAP_PARAMS'))
		{
			eval('var params = {' + cookie.get('MAP_PARAMS') + '}');

			if (params.carts)
			{
				params.carts.each(
					function(el)
					{
						if ($('carts_' + el))
						{
							$('carts_' + el).checked = true;
						}
					}
				)
			}

			if (params.oil_types)
			{
				params.oil_types.each(
					function(el)
					{
						if ($('oil_types_' + el))
						{
							$('oil_types_' + el).checked = true;
						}
					}
				)
			}

			if (params.equipment)
			{
				params.equipment.each(
					function(el)
					{
						if ($('equipment_' + el))
						{
							$('equipment_' + el).checked = true;
						}
					}
				)
			}
		}
		else
		{
			var params = new Object();
		}
		return params;
	},

	getStation : function()
	{
		new Ajax.Request(
			'/json.php?do=getMapStation',
			{
				method : 'post',
				parameters :
				{
					id : $('station_id').value
				},
				onComplete : function(req)
				{
					eval('var ret=' + req.responseText);

					this.writeMapInfo(
						ret.map_lat,
						ret.map_lng
					);

					this.map.setCenter(
						new GLatLng(
							ret.map_lat,
							ret.map_lng
						),
						10
					);

					this.map.savePosition(); // zeby wracalo poprawnie

					var point = new GLatLng(
						ret.map_lat,
						ret.map_lng
					);

					markId = '2';
					if(ret.map_category == 'kia_formula')
						markId = '3a';
					if(ret.map_category == 'aso_subaru')
						markId = '6';

					this.addPoint(
						point,
						'<a href="#">' + ret.name + '</a>',
						false, false, markId
					)

				}.bind(this)
			}
		)
	},

	prepareShowAllButton : function(newDisplay)
	{

		if (typeof newDisplay == 'undefined')
		{
			var display = 'inline';
			var query 	= $('query').value;

			if
			(
				$('query').value == 'miasto, ulica lub nazwa stacji' ||
				$('query').value == 'Poland: city, street' ||
				$('query').value == 'Польша: город, улиса' ||
				$('query').value == ''
			)
			{
				query = '';
			}

			if (query == '')
			{
				var anyChecked = false;

				$$('input.checkbox-element').each(
					function(el)
					{
						if (el.checked)
						{
							anyChecked = true;
						}
					}
				)

				if (anyChecked == false)
				{
					display = 'none';
				}
			}
		}
		else
		{
			display = newDisplay;
		}

		if($('submit_show_all'))
			$('submit_show_all').setStyle({'display' : display});
	},

	getStations : function(mapContent)
	{
		this.prepareShowAllButton();

		if ($('map-loader').getStyle('display') == 'block')
		{
			return false;
		}

		var query = $('map-search-form').serialize(true);

		$('map-loader').setStyle({'display' : 'block'});

		new Ajax.Request(
			'/json.php?do=getMapStations',
			{
				method : 'post',
				parameters : query,

				onComplete : function(req)
				{
					eval('var ret=' + req.responseText);

					this.removePoints();

					$('alert-not-found').setStyle({'display' : 'none'});

					var maxLat = false;
					var minLat = false;
					var maxLng = false;
					var minLng = false;

					ret.each(
						function(el)
						{
							maxLat = (maxLat === false || el.map_lat > maxLat) ? el.map_lat*1 : maxLat;
							minLat = (minLat === false || el.map_lat < minLat) ? el.map_lat*1 : minLat;
							maxLng = (maxLng === false || el.map_lng > maxLng) ? el.map_lng*1 : maxLng;
							minLng = (minLng === false || el.map_lng < minLng) ? el.map_lng*1 : minLng;

								var len = this.pointsPositions.length;

								this.pointsPositions[len] = el.map_lat + '-' + el.map_lng;

							var point = new GLatLng(
								el.map_lat,
								el.map_lng
							);

							if(query.mapCategory == 'kia_formula') // okretka zeby kia miala szarego fistaszka :)
							{
								this.addPoint(
									point,
									this.prepareHtml(el),
									true, false, '3'
								);
							}
							if(query.mapCategory == 'aso_subaru') // okretka zeby quazar mial zoltego fistaszka :)
							{
								this.addPoint(
									point,
									this.prepareHtml(el),
									true, false, '6'
								);
							}
							else
							{
								this.addPoint(
									point,
									this.prepareHtml(el),
									true
								);
							}

					  }.bind(this)
					);

					$('map-loader').setStyle({'display' : 'none'});

					if (maxLat !== false)
					{
						this.map.setCenter(
							new GLatLng(
								minLat + (maxLat - minLat) / 2,
								minLng + (maxLng - minLng) / 2
							),
							this.map.getBoundsZoomLevel(
								new GLatLngBounds(
									new GLatLng(minLat, minLng),
									new GLatLng(maxLat, maxLng)
								)
							)
						);

						this.map.savePosition();
					}
					else
					{
						$('alert-not-found').setStyle({'display' : 'block'});
						geo = new GClientGeocoder();
						geo.mapa = this.map;
						geo.getLatLng(query.query,function(punkt)
						{
							if (punkt)
							{
								geo.mapa.setCenter (punkt, 10);
								$('query').value = '';
							}
						});
					}
				}.bind(this)
			}
		);
		return true;
	},

	prepareHtml : function(el)
	{
		var html =
			'<div class="gmTip">' +
				'<div class="gmTipBody">' +
					'<div class="gmTipInner">';
		html +=
			'<div class="gmAddr">' +
				'<strong>' + el.name + '</strong><br />' +
				el.zip_code + ' ' + el.city + ', ' + el.street + '<br />';
		if(el.phone && el.phone != '')
			html += 'tel. ' + el.phone + '<br />';
		if(el.email && el.email != '')
			html += 'e-mail: <a href="mailto:' + el.email + '">' + el.email + '</a><br/>';
		if(el.www_address && el.www_address != '')
			html += 'www: <a href="http://' + el.www_address + '" target="_blank">' + el.www_address + '</a><br/>';

		html += '</div>';

		html += '<ul class="gmIcons">';

		for (var i = 1 ; i <= 9 ; i++)
		{
			if (i == 8)
			{
				continue;
			}
			if (el.oil_types.indexOf(i) > -1)
			{
				html += '<li><img style="height: 38px;" src="/images/station_icons/oil_' + i + '.png"/></li>';
		  	}
		}

		/*for (var i = 1 ; i <= 12 ; i++)
		{
			if (el.equipment.indexOf(i) > -1)
			{
				html += '<li><img style="height: 38px;" src="/images/station_icons/eq_' + i + '.png"/></li>';
			}
		}*/

		html += '</ul>';

		if (el.cards_1 || el.cards_2)
		{
			html += '<div class="gmCards">';

			switch ($('currentLang').value)
			{
				case 'en':
					html += '<h4>credit/charge cards:</h4>';
					break;

				case 'ru':
					html += '<h4>платёжные карты:</h4>';
					break;

				default:
					html += '<h4>Akceptowane karty:</h4>';
					break;
			}

			if (el.cards_1)
			{
				html += '<img src="/images/atlas/card_biznes.gif" alt="LOTOS Biznes" />';
			}

			if (el.cards_2)
			{
				html += '<img src="/images/atlas/card_navigator.gif" alt="LOTOS Navigator" />';
			}

			html += '</div>';
		}

		switch ($('currentLang').value)
		{
			case 'en':
				if (el.comment_en && el.comment_en != '')
				{
					html += '<div class="gmInfo"><h4>Message:</h4><p>' + el.comment_en + '</p></div>';
				}
				break;

			case 'ru':
				if (el.comment_ru && el.comment_ru != '')
				{
					html += '<div class="gmInfo"><h4>Message:</h4><p>' + el.comment_ru + '</p></div>';
				}
				break;

			default:
				if (el.comment && el.comment != '')
				{
					html += '<div class="gmInfo"><h4>Komunikat:</h4><p>' + el.comment + '</p></div>';
				}
		}

		if(!$('isQuazar') || $('isQuazar').value != 1)
		{
			html += '<div class="gmMore">';

			switch ($('currentLang').value)
			{
				case 'en':
					html += '<a href="/en' + this.baseStationUrl + el.id + '">more</a>';
					break;

				case 'ru':
					html += '<a href="/ru' + this.baseStationUrl + el.id + '">больше</a>';
					break;

				default:
					html += '<a href="' + this.baseStationUrl + el.id + '">więcej</a>';
			}

			html += '</div>';
		}

		html += '</div></div></div>';

		return html;
	},

	getAllStations : function()
	{
		this.prepareShowAllButton('none');

		if ($('map-loader').getStyle('display') == 'block' && this.pointsAll.length == 0)
		{
			return false;
		}

		$('map-loader').setStyle({'display' : 'block'});

		new Ajax.Request(
			'/json.php?do=getMapStations',
			{
				method : 'post',
				parameters : {currentProfile : $('currentProfile').value},
				onComplete : function(req)
				{
					eval('var ret=' + req.responseText);

					ret.each(
						function(el)
						{
							if (this.pointsPositions.indexOf(el.map_lat + '-' + el.map_lng) == -1)
							{
								var point = new GLatLng(
									el.map_lat,
									el.map_lng
								);

								this.addPoint(
									point,
									this.prepareHtml(el),
									true,
									true
								);
							}

					  	}.bind(this)
					);

					$('map-loader').setStyle({'display' : 'none'});

				}.bind(this)
			}
		);
		return true;
	},

	removePoints : function()
	{
		this.pointsAll.each(
			function(el)
			{
				this.map.removeOverlay(el);

			}.bind(this)
		);
		this.points.each(
			function(el)
			{
				this.map.removeOverlay(el);

			}.bind(this)
		);
		this.pointsPositions 	= new Array();
		this.pointsAll 			= new Array();
		this.points 			= new Array();
	},

	addPoint : function(point, html, putInList, grey, pointId)
	{
		var baseIcon = new GIcon();

		baseIcon.shadow 			= '';
		baseIcon.iconSize 			= new GSize(42, 26);
		baseIcon.shadowSize 		= new GSize(15, 15);
		baseIcon.iconAnchor 		= new GPoint(13, 18);
		baseIcon.infoWindowAnchor 	= new GPoint(9, 2);
		baseIcon.infoShadowAnchor 	= new GPoint(15, 15);

		var icon = new GIcon(baseIcon);

		if(!pointId)
		{
			if(putInList && grey)
				pointId = '1_g';
			else if(putInList)
				pointId = '1';
			else
				pointId = '2';
		}
		icon.image = '/images/map/point_' + pointId + '.png';

		var marker = new GMarker(point, icon);

		if (putInList)
		{
			if (grey === true)
			{
				var len = this.pointsAll.length;
				this.pointsAll[len] = marker;
			}
			else
			{
				var len = this.points.length;
				this.points[len] = marker;
			}
		}


		this.map.addOverlay(marker);

		if (putInList)
		{
			GEvent.addListener(
				marker,
				'click',
				function()
				{
					marker.openInfoWindowHtml(html);

				}.bind(this)
			);
		}
	}
}

