﻿
var map = {
	URL : W_IMAGES + 'map/',
	mainInit : function(){
		if(!$('#map').length ) return;
		
			App.clear.push(function(){
				map.openRegion();
				//App.history.restoreLink();
			});
		$('<div id="map-tip"> <em class="tip-tl"></em> <em class="tip-tr"></em> <em class="tip-br"></em> <em class="tip-bl"></em> <em class="tip-l"></em> <span></span></div>').appendTo('body').css({top: '-99em', left: '-99em'});

		map.initChange();
		if(!$.support.svg){
			$('#map').prepend('<map name="map-regions" id="map-regions" />');
			map.initIE();
			return;
		}
		if(typeof window.svgInstalled != 'undefined') return;	
		var svg = $('#map').svg({onLoad: function(){
			map.svg = $('#map').svg('get');
			map.svg.load(map.URL + 'map.svg', {onLoad: map.init});
		}});
			
	},
	init : function(){
		var unHoverHandler;
	
		map.hover = false;
		//RESIZE
		map.resetSize(map.svg);
		$(window).resize(function(){
			map.resetSize(map.svg);
		});
		map.resetSize(map.svg);
		
		//HOVER
		$('g.zone' /* , map.svg.root() */).hover(unHoverHandler = function(e){
			map.hover = true;
			map.showTip(e, this.id);
			if($.browser.msie) $('path.region', this).attr({fill: '#2346B0'});
			else $(this).children('path').stop().animate({svgFill: '#c7f9b8', svgStroke : "#c7f9b8"}, 300);
		},function(){
			if($.browser.msie) $('path.region', this).attr({fill: '#fff'});
			else $(this).children('path').stop().animate({svgFill: '#fff', svgStroke : "#999"}, 300);
			
			map.hideTip();
		}).mousemove(unHoverHandler).click(function(){
			map.clickEvent(this.id);
		});
		
	},
	initChange : function(){
		$("#map-change").click(function(){
			$(this).next().fadeIn('fast', function(){
				var list = $(this);
				$(document).one('click', function(){
					list.hide();
				});
			});
		});
		
		map.mapDiv = $('#map');
		map.managers = {};
		$('div.map-managers').children('div').each(function(){
			map.managers[/^map-(.*)$/.exec($(this).attr('id'))[1].toLowerCase()] = $(this);
		}).end().detach();
	}, 
	initIE : function(){
		$.each(map.poly, function(i, el){
			el.coords = $.map(el.coords.split(","), function(coord){ return parseInt(coord) });
		});
		$('#map').append(
			$('<img />').load(map.resize).attr({
				"src": map.URL + map.mapImage,
				"id" : "map-image"
			})
		).append(
			$('<img />').attr({
				'src': map.URL + map.blank,
				'id': 'map-blank',
				"usemap":"#map-regions"
			})
		).append($.map(map.poly, function(el, i){
			return map.poly[i].obj = $('<img />').attr({
				src: map.URL + el.img,
				id: 'png-' + el.name,
				'class': 'png-region'
			}).css({left: map.poly[i].offset[0], top: map.poly[i].offset[1]}).get(0)
		})).addClass('ie');
		this.resize();
		
		$(document).keydown(function(e){
			if(e.keyCode==8){
				window.history.back();
				return false;
			}
		});
	},
	resize : function(){
		//ratio
		var k = 1, timer = {}, unHoverHandler; 
		
		
		$('#map-regions').empty().html(
			$.map(map.poly, function(el){ 
				return '<area href="#map/' + el.name + '" coords="' + el.coords + 	"\" shape=\"poly\" id=\"region-"+el.name+"\">";
			}).join('')
		).children().hover(unHoverHandler = function(e){
			map.hover = true;
			var id = this.id.substr("region-".length);
			map.showTip(e, id);
			$('#png-' + id).show().css('opacity', 1);
			clearTimeout(timer[id])
		}, function(e){
			$('.png-region').hide();
			map.hideTip();
		}).mousemove(unHoverHandler).click(function(){
			//map.clickEvent(this.id.substr("region-".length))
			$('.png-region').hide();
		});
		$('#map').mouseleave(function(){
			$('.png-region').hide();
		});
	},
	resetSize: function(){
		var width = $(map.svg._container).width();
		map.svg.configure({width: width, height: width*0.5805});
		if($.browser.msie) $('#map embed').attr({width: width, height: width*0.5805});
	}, 
	createTip : function(){
		return $('#map-tip');
	},
	showTip: function(e, id){
		var tip = map.createTip(), x = (e.pageX > $(window).scrollLeft() + $(window).width() - 280) ? $(window).scrollLeft() + $(window).width() - 280 : e.pageX;
		
		
		
		tip.show().css({left: x + 40, top: e.pageY - tip.height() - 40});
		$('body').bind('mousemove.tip', function(e){
			var x = (e.pageX > $(window).scrollLeft() + $(window).width() - tip.width() - 60) ? $(window).scrollLeft() + $(window).width() - tip.width() - 60 : e.pageX;
			$('#map-tip').css({left: x + 40, top: e.pageY - tip.height() - 40});
		});
			$(document).bind('mouseenter.fixTip', function(e){
				var dommap = $('#map').get(0), domtip = tip.get(0)
				if($.contains(dommap, e.target) || $.contains(domtip, e.target) || e.target == dommap || e.target == domtip) return;
			});
			var text = $('#map-tip span');
		//EVENT HOVER
		switch(id){	
			case 'siberia_far_eastern':
				text.html('<h5>Сибирский и Дальневосточный<br />федеральные округа</h5>');
				break;
			case 'central':
				text.html('<h5>Центральный федеральный округ</h5>');
				break;
			case 'volga':
				text.html('<h5>Приволжский федеральный округ</h5>');
				break;
			case 'ural':
				text.html('<h5>Уральский федеральный округ</h5>');
				break;
			case 'siberia':
				text.html('<h5>Сибирский федеральный округ</h5>');
				break;
			case 'northwestern':
				text.html('<h5>Северо-Западный<br />федеральный округ</h5>');
				break;
			case 'south':
				text.html('<h5>Южный федеральный округ</h5>');
				break;
			case 'moscow':
				text.html('<h5>Московская область</h5>');
				break;
			case 'saintpetersburg':
				text.html('<h5>Ленинградская область</h5>');
				break;
			default:
				text.html('<h5>Лишний федеральный округ</h5>');
				break;
		}
		if(ie6) tip.width('auto').height('auto').width(function(){
			var w = $(this).width();
			$('em.tip-tl, em.tip-bl', this).width(w+10);
			return w;
		}).height(function(){
			var h = $(this).height();
			$('em.tip-l', this).height(h);
			$('em.tip-tr', this).height(h+10);
			return h;
		});
	},
	hideTip: function(){
	//	if(typeof map.hover != "undefined" && map.hover) return false;
		$('body').unbind('mousemove.tip');
		$(document).unbind('mouseenter.fixTip');
		$('#map-tip').hide();
	},
	tipTimer : null,
	poly: [
		{name: "northwestern", img:"map.nw.gif", offset: [0,0], coords: "66,303,80,292,188,340,203,325,205,352,276,359,304,319,335,305,349,272,358,224,407,174,420,77,346,66,278,211,199,158,119,239,135,282,124,293,109,274,90,271,85,254,1,237,3,261"},
 		{name: "saintpetersburg", img:"map.spb.gif", offset: [74,221], coords: "86,255,90,271,109,273,123,292,135,283,118,239,101,240"},
		{name: "moscow", img:"map.moscow.gif", offset: [75,300], coords: "98,358,118,355,114,337,100,322,87,330"},
		{name: "central", img:"map.central.gif", offset: [30,275], coords: "63,413,96,412,128,367,191,349,188,340,80,292,65,304,34,338,42,380"},
		{name: "south", img:"map.south.gif", offset: [0,404], coords: "63,414,96,412,121,444,100,462,112,495,70,507,54,467,35,461,27,481,6,478,1,438,34,424"},
		{name: "volga", img:"map.volga.gif", offset: [83,316], coords: "97,411,128,455,156,450,182,481,235,499,228,471,238,450,245,426,249,404,276,360,205,352,203,326,188,340,190,348,129,368"},
		{name: "ural", img:"map.ural.gif", offset: [202,208], coords: "230,479,321,466,337,445,338,426,354,433,384,404,439,401,429,288,422,250,407,208,353,252,337,304,304,319,250,406,238,451,228,471"},
		{name: "siberia_far_eastern", img:"map.fe.gif", offset: [311,0], coords: "421,245,427,132,465,106,577,187,663,80,783,13,862,4,953,55,973,188,979,348,979,458,864,554,739,450,717,528,619,550,551,537,541,563,484,559,450,569,418,556,375,540,316,478,323,466,337,446,338,425,359,435,384,404,440,401"}
	],
	clickEvent: function(id){
		if($('#map').is(':visible')){
			App.history.jump(true, 'map/', true);
			delete App.history.noparsing;
		}
		App.history.jump(false, 'map/'+id.toLowerCase());
	},
	openRegion : function(name, callback){
		
		var callback = callback || $.noop, name = name || '';
		
		var fixHover = ($.support.svg) ? function(){
			$('g.zone', map.svg.root()).mouseleave();
		} : $.noop;
		
		if(!map.managers[name.toLowerCase()] && $('#map').is(':visible')) return callback();
		
		$('ul.map-popup li a').removeClass('bold');
		if(map.managers[name.toLowerCase()]){
			map.hideTip();
			$('ul.map-popup li.back').show();
			$('#map-change h3').text($('a[href$='+name.toLowerCase()+']').addClass('bold').text() || null);
			/*$(document).bind('clearAll.map', function(){
				$(this).unbind('.map');
				fixHover();
				map.openRegion('');
			});*/
		}else{
			 $('ul.map-popup li.back').hide();
			$('#map-change h3').text("Выберите регион");
		}
		var wrap = $('#map-wrapper'),
			toAdd = map.managers[name.toLowerCase()] || map.mapDiv;
			
			//stop All      fix height
			wrap.stop(true).height(wrap.height()); 
			
			wrap.children().addClass('absolute');
			
				//fade old
				fixHover();
			wrap.children().fadeTo('fast', 0, function(){ $('.png-region').hide().css('opacity', 0); $(this).detach();  });
				//attach new
			wrap.append( toAdd.stop(true).removeClass('absolute').css('opacity', 0).fadeTo('fast', 1, function(){
				$(this).ieClearType(); 
				map.hideTip();
				if(toAdd == map.mapDiv) $(window).resize();
			}) );
				//newHeight
			wrap.animate({height: toAdd.outerHeight(true)}, 'slow', function(){ 
				$(this).css({height: 'auto'});
				callback(); fixHover(); 
			});
			App.fire(wrap);
		this.hideTip();
	},
	blank: "blank.gif",
	mapImage: "map.gif",
	origWidth: 980,
	origHeight: 570
}
