// JavaScript Document

function map(eleId, isSearchPanel, zoom, need_update) {
	this.map = null;
	this.eleId = eleId;
	this.placemarks = new Array();
	this.defaultZoom = zoom;
	this.defaultLongitude = 55.76;
	this.defaultLatitude = 37.64;
	this.isSearchPanel = isSearchPanel;

	this.points = new Array();

	this.addPoint = function(mapPoint) {
		this.points.push(mapPoint);
		this.map.addOverlay(mapPoint.placemark);

		return false;
	}

	this.clearAllPoints = function() {
		this.points = new Array();
		this.map.removeAllOverlays();
	}

	this.init = function (need_update) {
		if($("#" + this.eleId).length) {
            this.toggleMapLoader();

            // Создает экземпляр карты и привязывает его к созданному контейнеру
            this.map = new YMaps.Map(YMaps.jQuery("#" + this.eleId)[0]);
            this.map.addControl(new YMaps.TypeControl());
            this.map.addControl(new YMaps.Zoom());
            this.map.enableScrollZoom();

            // Устанавливает начальные параметры отображения карты: центр карты и коэффициент масштабирования
            this.map.setCenter(
                new YMaps.GeoPoint(
                    this.defaultLatitude,
                    this.defaultLongitude
                ),
                this.defaultZoom
            );

            if(this.isSearchPanel) {
                 var searchControl = new YMaps.SearchControl({
                    resultsPerPage: 5,  // Количество объектов на странице
                    useMapBounds: 1,     // Объекты, найденные в видимой области карты
                                        // будут показаны в начале списка
                    width: 200
                });
                this.map.addControl(searchControl);
            }

            if(need_update) {
                YMaps.Events.observe(
                    this.map,
                    this.map.Events.DragEnd,
                    function (ele) {
                        map.updateMap();
                    }
                );

                YMaps.Events.observe(
                    this.map,
                    this.map.Events.SmoothZoomEnd,
                    function (ele) {
                        map.updateMap();
                    }
                );
            }

            var elementId = this.eleId;

            $('.yandex-map-toggle a').click(
                function() {
                    var rel = $(this).attr('rel');
                    $('#' + elementId).toggle();
                    $('.yandex-map-toggle a').toggle();
                    return false;
                }
            );

            $('.yandex-map-toggle a[rel=hide]').hide();

            this.toggleMapLoader();
        }
	}

	this.initSearchForm = function(formId) {
		this.form = $('#' + formId);

		this.form.find('select#city').change(
			function() {
				map.initMetroField();
			}
		);

		this.form.find('input:checkbox[name=type[]]').change(
			function() {
				var value = $(this).attr('value');
				if(value == '991534F324') {
					map.toggleCheckboxes('for-atm');
				}

				map.initCityField();
			}
		);

		this.initMetroField();
		this.updatePoints();

		this.form.submit(
			function() {
				map.updatePoints();
				return false;
			}
		);
	}

	this.page = function(page) {
		this.updateList(page);
	}

	this.updatePoints = function() {
		var cityTitle = this.form.find('select#city option:selected').text();
		var cityValue = this.form.find('select#city').val();

        if($("#" + this.eleId).length) {
            if(cityValue == 0) {
                this.map.setZoom(3);
                cityTitle = 'Россия';
            } else {
                this.map.setZoom(10);
            }
            if(cityTitle) {
                var geocoder = new YMaps.Geocoder(cityTitle, {results: 1});
                var mapObj = this;

                YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
                    if (this.length()) {
                        mapObj.map.setCenter(this.get(0).getGeoPoint())
                        if(!$.browser.mozilla) {
                            mapObj.updateMap();
                        }
                    }
                });

                if($.browser.mozilla) {
                    setTimeout(
                        function() {
                            mapObj.updateMap();
                        },
                        2000
                    );
                }
            }
        } else {
            this.updateMap();
        }
	}

	this.updateMap = function() {
        if($("#" + this.eleId).length) {
            this.toggleMapLoader();

            var formValue = this.form.serialize();

            var top = this.map.getBounds().getTop();
            var left = this.map.getBounds().getLeft();
            var right = this.map.getBounds().getRight();
            var bottom = this.map.getBounds().getBottom();

            $.ajax({
                async: false,
                type: "POST",
                url: '/ajax/atm_map/',
                data: formValue + '&top=' + top + '&left=' + left + '&right=' + right + '&bottom=' + bottom,
                success: function(data, textStatus, XMLHttpRequest) {
                    map.clearAllPoints();
                    if(
                        $(data).find('item').length
                    ) {
                        $(data).find('item').each(
                            function() {
                                var description = '';
                                if($(this).find('addres')) {
                                    description += '<p>' + $(this).find('addres').text() + '</p>';
                                }
                                if($(this).find('metro')) {
                                    description += '<p>Метро: ' + $(this).find('metro').text() + '</p>';
                                }
                                if($(this).attr('round_the_clock') || $(this).attr('receiving_cash')) {
                                    description += '<p>';
                                    if($(this).attr('round_the_clock')) {
                                        description += 'круглосуточно';
                                    }
                                    if($(this).attr('receiving_cash')) {
                                        if($(this).attr('round_the_clock')) {
                                            description += ', ';
                                        }
                                        description += 'функция приема наличных';
                                    }
                                    description += '</p>';
                                }
                                var title = '<a href="' + $(this).attr('uri') + '">' + $(this).find('title').text() + '</a>';

                                var point = new mapPoint(
                                    $(this).find('longitude').text(),
                                    $(this).find('latitude').text(),
                                    title,
                                    description,
                                    $(this).attr('category_id')
                                );

                                map.addPoint(point);
                            }
                        );
                    }

                    map.toggleMapLoader();
                }
            });
        }
		this.updateList();
	}

	this.updateList = function(page, ele) {
		if(!page) page = 1;

		var formValue = this.form.serialize();

		/*var top = this.map.getBounds().getTop();
		var left = this.map.getBounds().getLeft();
		var right = this.map.getBounds().getRight();
		var bottom = this.map.getBounds().getBottom();*/

		this.toggleLoader();

		var text = '';
        if(ele) {
            text = $(ele).val();
        }

		var obj = this;

		$.ajax({
			async: false,
			type: "POST",
			url: '/ajax/atm_map/list.php',
			/*data: formValue + '&top=' + top + '&left=' + left + '&right=' + right + '&bottom=' + bottom + '&page=' + page + '&text=' + text,*/
			data: formValue + '&page=' + page + '&text=' + text,
			success: function(data, textStatus, XMLHttpRequest) {
				$('.yandex-map-search-result').html(data);
				obj.toggleLoader();
			}
		});
	}

	this.toggleMapLoader = function() {
		$('.yandex-map-point-loader').toggle();
	}

	this.toggleLoader = function() {
		$('.yandex-map-loader').toggle();
	}

	this.initCityField = function() {
		var formValue = this.form.serialize();

		$.ajax({
			async: false,
			type: "POST",
			url: '/ajax/city_by_type/',
			data: formValue,
			success: function(data, textStatus, XMLHttpRequest) {
				if(
					$(data).find('success').length
				) {
					map.fillSelectField(
						map.form.find('select#city'),
						$(data).find('success')
					);
					map.form.find('select#city').removeAttr('disabled');
					map.initMetroField();
				} else {
					map.form.find('select#city').attr('disabled', 'disabled');
					map.form.find('select#metro').attr('disabled', 'disabled');
				}
			}
		});
	}

	this.initMetroField = function() {
		$.ajax({
			async: false,
			type: "POST",
			url: '/ajax/metro/',
			data: 'city=' + this.getCityId(),
			success: function(data, textStatus, XMLHttpRequest) {
				if(
					$(data).find('success').length
				) {
					map.fillSelectField(
						map.form.find('select#metro'),
						$(data).find('success')
					);
					map.form.find('select#metro').removeAttr('disabled');
				} else {
					map.form.find('select#metro').attr('disabled', 'disabled');
				}
			}
		});
	}

	this.fillSelectField = function(ele, data) {
		var obj_select = $(ele).get(0);
		obj_select.options.length = 0;

		var i = 0;

		$(data).find('item').each(
			function() {
				obj_select.options[i] = new Option(
					$(this).text(),
					$(this).attr('id')
				);
				if($(this).attr('selected')) {
					obj_select.options[i].selected = true;
				}
				i++;
			}
		);
	}

	this.getCityId = function() {
		return this.form.find('select#city').val();
	}

	this.getMetroId = function() {
		return this.form.find('select#metro').val();
	}

	this.getTypeId = function() {
		return this.form.find('input:checkbox[name=type[]]').val().serialize();
	}

	this.toggleCheckboxes = function(containerId) {
		if(
			$('input:checkbox[value=991534F324]').attr('checked')
		) {
			$('#' + containerId).show();
			$('#' + containerId).find('input').attr('disabled', '');
		} else {
			$('#' + containerId).hide();
			$('#' + containerId).find('input').attr('disabled', 'disabled');
		}

		return false;
	}

	this.init(need_update);
}

function mapPoint(longitude, latitude, title, content, categoryId) {
	this.longitude = longitude;
	this.latitude = latitude;
	this.content = content;

	this.geoPoint = new YMaps.GeoPoint(
		this.latitude,
		this.longitude
	);

	this.baseStyle = new YMaps.Style();
	this.baseStyle.iconStyle = new YMaps.IconStyle();
	this.baseStyle.iconStyle.offset = new YMaps.Point(-15, -36);
	this.baseStyle.iconStyle.size = new YMaps.Point(31, 36);
	this.baseStyle.iconStyle.href = "/f/img/map-point-o.png";
	if(categoryId && categoryId == '991534F324') {
		this.baseStyle.iconStyle.href = "/f/img/map-point-b.png";
	}

	this.placemark = new YMaps.Placemark(
		this.geoPoint,
		{
			draggable: false,
			hasBalloon: true,
			hasHint: false,
			hintOptions: {
				maxWidth: 300
			},
			balloonOptions: {
				maxWidth: 300
			},
			style: this.baseStyle
		}
	);

	this.placemark.description = content;
	this.placemark.name = title;
}

