﻿Array.prototype.getNumber = function(o) {
	for(var i=0; i<this.length; i++) {
		if(this[i] === o) {
			return i;
		}
	}
}


Map = function() {
	this.init_DOM();
}

Map.prototype = {
	iMAX_ZOOM: 17,

	iMIN_ZOOM: 13,

	PATH: '/f/1/carlsbad/',

	ICON: 'marker.gif',

	ICON_SIZE: new GSize(1000, 1000),

	init_DOM: function() {
		this.jPopup = $('#flash_container');
		this.jFlash = $('#flash1');
		this.iPopup_max_width = 855;
		this.jShadow = this.jPopup.find('.form_shadow');
		this.jPanorama_block = $('#panorama_list');
		this.jPanorama_list = this.jPanorama_block.find('li a');
		this.jClose = this.jPopup.find('.gal_close');
		this.jMap = $('#map');
		this.jMap_canvas = $('#map_canvas');
		this.map = new GMap2(this.jMap_canvas[0]);

		if($.browser.msie && $.browser.version == 6) {
			this.bIE6 = true;
		}

		this.init();
	},

	init: function() {
		var oThis = this;

		this.resize_map();
		this.resize_flash();
		this.initialize();

		this.close();

		/* При переходе по страницам с помощью history(),
		гугл обновляет стили картинок, при этом добавленные обертки сохраняются,
		из-за чего все расползается. Проверяем, есть ли первая обертка.
		Если есть одна, значит есть все остальные.
		Пробегаем по всем добавленным элементам и удаляем style у картинок. */
		this.fix_images();

		$(window).resize(function() {
			oThis.resize_map();
			oThis.resize_flash();
		});
		
		this.jMap_canvas.mouseup(function() {
			oThis.fix_images();
		});
	},

	resize_map: function() {
		var
			iBody_height = document.documentElement.clientHeight,
			iMap_top = this.jMap[0].offsetTop,
			iPanorama_block_height = this.jPanorama_block[0].offsetHeight;

		if(iBody_height < 820) {
			iBody_height = 820;
		}

		this.jMap_canvas[0].style.height = iBody_height - iMap_top - 320 + 'px';

		var iTop = (this.jMap_canvas[0].offsetHeight - iPanorama_block_height) / 2;
		if(iTop > 0) {
			this.jPanorama_block[0].style.marginTop = (this.jMap_canvas[0].offsetHeight - iPanorama_block_height) / 2 + 'px';
		}
		else {
			this.jPanorama_block[0].style.marginTop = 0;
		}
	},

	initialize: function() {
		this.map.setCenter(new GLatLng(50.222500, 12.883744), this.iMAX_ZOOM);
		var oZoom = new GLargeMapControl();
		this.map.addControl(oZoom);
		this.map.enableScrollWheelZoom();

		this.mm = new GMarkerManager(this.map);

		this.current_zoom = this.map.getZoom();
		this.change_zoom('', this.iMAX_ZOOM);

		var oThis = this;

		GEvent.addListener(this.map, "zoomend", function(oldLevel, newLevel) {
			oThis.current_zoom = newLevel;
			oThis.change_zoom(oldLevel, newLevel);
			oThis.change_position(oldLevel, newLevel);
		});
		
		if(this.map.isLoaded()) {
			$('#lmczb div').load(function() {
				$(this).click(function() {
					oThis.fix_images();
				}).mouseout(function() {
					oThis.fix_images();
				}).mouseleave(function() {
					oThis.fix_images();
				});					
			});
			
			this.jMap_canvas.mouseup(function() {
				setTimeout(function() {
					oThis.fix_images();
				}, 10);
			});
		}

		this.aoMarkers = {
			buildings: {
				marker_0: {
					coords: {x: 50.223572, y: 12.883744},
					link: '/',
					label: true
				},
				marker_1: {
					coords: {x: 50.224983, y: 12.879528},
					link: '/carlsbad/st_lucas_church/',
					label: true
				},
				marker_2: {
					coords: {x: 50.225540, y: 12.881491},
					link: '/carlsbad/mill_colonnade/',
					label: true
				},
				marker_3: {
					coords: {x: 50.222828, y: 12.883465},
					link: '/carlsbad/hot_spring_colonnade/',
					label: true
				},
				marker_4: {
					coords: {x: 50.223274, y: 12.884431},
					link: '/carlsbad/st_magdalene_church/',
					label: true
				},
				marker_5: {
					coords: {x: 50.221039, y: 12.881706},
					link: '/carlsbad/theater/',
					label: true
				}
			},

			springs: {
				marker_6: {coords: {x: 50.226074, y: 12.880976}},
				marker_7: {coords: {x: 50.225952, y: 12.880579}},
				marker_8: {coords: {x: 50.225327, y: 12.881845}},
				marker_9: {coords: {x: 50.225155, y: 12.882081}},
				marker_10: {coords: {x: 50.224976, y: 12.882317}},
				marker_11: {coords: {x: 50.224529, y: 12.882618}},
				marker_12: {coords: {x: 50.224426, y: 12.884216}},
				marker_13: {coords: {x: 50.223995, y: 12.882349}},
				marker_14: {coords: {x: 50.223202, y: 12.882875}},
				marker_15: {coords: {x: 50.223324, y: 12.883111}}
			},

			panorama: {
				marker_16: {
					coords: {x: 50.225108, y: 12.882690},
					xml: 'town1.xml',
					list_item: 0
				},
				/*marker_17: {
					coords: {x: 50.227339, y: 12.880375},
					xml: 'town2.xml',
					list_item: 1
				},*/
				marker_17: {
					coords: {x: 50.227888, y: 12.879227},
					xml: 'town3.xml',
					list_item: 2
				},
				marker_18: {
					coords: {x: 50.229501, y: 12.874067},
					xml: 'town4.xml',
					list_item: 3
				},
				marker_19: {
					coords: {x: 50.230015, y: 12.869389},
					position: {x: 25, y: 15},
					xml: 'town5.xml',
					list_item: 4
				}
			}
		};

		this.current_xml = '';
		this.xmlPath_alt_links = [];

		for(_item in this.aoMarkers.panorama) {
			this.xmlPath_alt_links.push(this.aoMarkers.panorama[_item].xml);
		}

		for(type in this.aoMarkers) {
			this.set_marker(this.aoMarkers[type], type);
		}
	},

	fix_images: function() {
		if($('#marker_0')) {
			for(var i=0; i<20; i++) {
				$('#marker_' + i + ' img').removeAttr('style');
			}
		}
	},

	change_zoom: function(iZoom_old, iZoom_new) {
		this.jMap.removeClass('zoom_' + iZoom_old).addClass('zoom_' + iZoom_new);
	},

	change_position: function() {
		if(!this.jBuildings) {
			this.jBuildings = this.jMap_canvas.find('a.my_marker, .panorama');
		}

		this.jBuildings.each(
			function() {
				var
					me = $(this),
					jImage = me.find('img, div');

				me.css({top: jImage[0].style.top, left: jImage[0].style.left});
				jImage.removeAttr('style');
			}
		);
	},

	set_marker: function(oPtr, type){
		for (key in oPtr) {
			var
				oMarker = oPtr[key],
				point = new GIcon();

			point.image = this.PATH + this.ICON;
			point.iconSize = this.ICON_SIZE;
			point.iconAnchor = new GPoint(0, 0);

			var oPoint = new GMarker(new GLatLng(oMarker.coords.x, oMarker.coords.y), point);

			this.map.addOverlay(oPoint);

			for(var x in oPoint){
				try {
					if( point.image === oPoint[x].__src__ ){
						var true_object = oPoint[x];
						break;
					}
				} catch(e){};
			}

			switch(type) {
				case 'buildings':
					this.building(oPoint, oMarker, key, true_object);
					break;
				case 'springs':
					this.springs(oPoint, key, true_object);
					break;
				case 'panorama':
					this.panorama(oPoint, oMarker, key, true_object);
					break;
				default:
					return false;
			}

			this.mm.refresh();
		}
	},

	building: function(oPoint, oMarker, mark, true_object) {
		var
			jImage = $(true_object),
			jWrapper = $('<a href="' + oMarker.link + '" id="' + mark + '" class="my_marker" style="' + jImage.attr('style') + '"></a>').css({height: '', width: ''});

		jImage.addClass('png').before(jWrapper);

		if (oMarker.label) {
			jWrapper.append(jImage).append('<span class="label png"></span>');
		}

		this.remove_style(jImage);
	},

	springs: function(oPoint, mark, true_object) {
		var jImage = $(true_object);

		jImage.attr({id: mark, 'class': 'spring'});
	},

	panorama: function(oPoint, oMarker, mark, true_object) {
		var
			oThis = this,
			jImage = $(true_object),
			iNum = oThis.xmlPath_alt_links.getNumber(oMarker.xml);

		this.jPanorama_current = [jImage, this.jPanorama_list.eq(iNum)];

		var
			jImage = $(true_object),
			jWrapper = $('<div id="' + mark + '" class="panorama with_hover" style="' + jImage.attr('style') + '"></div>').css({height: '', width: ''});

		jImage.addClass('png').before(jWrapper);
		jWrapper.append(jImage);
		this.remove_style(jImage);

		if(this.bIE6){
			jWrapper.hover(
				function(){
					$(this).addClass('hover');
				},
				function(){
					$(this).removeClass('hover');
				}
			);
		}

		GEvent.addListener(oPoint, "click", function() {
			if(!jImage.hasClass('selected')) {
				if(oThis.jPanorama_current) {
					oThis.deselect_icons();
				}

				oThis.jPanorama_current = [jImage.addClass('selected'), oThis.jPanorama_list.eq(iNum).addClass('selected')];
				oThis.panorama_flash(oMarker.xml);
			}
		});

		oThis.jPanorama_list.eq(iNum).click(function() {
			var me = $(this);

			if(!me.hasClass('selected')) {
				if(oThis.jPanorama_current) {
					oThis.deselect_icons();
				}

				oThis.jPanorama_current = [me.addClass('selected'), jImage.addClass('selected')];
				oThis.panorama_flash(oThis.xmlPath_alt_links[iNum]);

				return false;
			}
		});
	},

	remove_style: function(jImg) {
		jImg.load(function() {
			jImg.removeAttr('style');
		});
    },

	close: function() {
		var oThis = this;

        this.jClose.click(function() {
            if(oThis.jPanorama_current) {
				oThis.deselect_icons();
			}

			oThis.jPopup.addClass('not_display');

			swfobject.removeSWF('flashcontent');
			oThis.jFlash.append('<div id="flashcontent"></div>');
			oThis.jShadow.hide();
		});
	},

	deselect_icons: function() {
		for(var i=0; i<this.jPanorama_current.length; i++) {
			this.jPanorama_current[i].removeClass('selected');
		}
    },

	panorama_flash: function(xmlPath) {
		this.current_xml = this.PATH + xmlPath;
		flash();
		this.show_popup();
	},

	flashIsReady: function() {
		this.jPopup.removeClass('not_display');
		window.document.flashcontent.load(this.current_xml);
		this.jShadow.show();
    },

	show_popup: function() {
		this.resize_flash();
		this.jShadow.show(); /* Нужна для показа ошибки */
		this.jPopup.removeClass('not_display');
	},

	resize_flash: function() {
		if(this.jMap[0].offsetWidth > this.iPopup_max_width) {
			this.jFlash.addClass('centered');
		}
		else {
			this.jFlash.removeClass('centered');
		}
    },

	fix_icons: function(jImage) {
		if(this.bIE6) {
			var
				curr_style = jImage[0].currentStyle,
				x1 = curr_style.backgroundPositionX,
				y1 = Math.abs(parseInt(curr_style.backgroundPositionY)) + 'px',
				x2 = jImage[0].offsetWidth + 'px',
				y2 = parseInt(y1) + jImage[0].offsetHeight + 'px';

			if(!jImage.hasClass('spring')) {
				jImage.css(
					{
						top: curr_style.backgroundPositionY
					}
				);
			}

			jImage.css(
				{
					clip: 'rect(' + y1 + ' ' + x2 + ' ' + y2 + ' ' + x1 + ')',
					height: '1000px',
					//top: curr_style.backgroundPositionY,
					background: 'none'
				}
			);
		}
	}
}

var oMap;

$(function() {
	oMap = new Map();
	$('ins.gal_close').hover(
		function () {$(this).addClass("hover");  if($.browser.msie && Math.floor($.browser.version)==7) $('a', this).removeAttr("style"); },
		function () {$(this).removeClass("hover"); if($.browser.msie && Math.floor($.browser.version)==7) $('a', this).css("top","-68px");}
	);
});


function flashIsReady() {
	oMap.flashIsReady();
}