var myLayer = [];
var map;
var Collors = [];
var baloon;

function setVisibleL(val)
{
	for (var i in myLayer) //if (myLayer[i]) myLayer[i].setVisible(val);
	{
		if (typeof myLayer[i] != 'function')
		{
			if (val) map.addOverlay(myLayer[i]);
			else map.removeAllOverlays();
		}
	}
}

function YouFull(val) //надо сделать
{
	//alert(val);
	$('#YMapsID').attr('style','height:900px;width:1300px'); //,'position':'absolute','top':'0px','left':'0px'
	map.redraw(1);
	//alert(map.getContainerSize());
	//document.getElementById("YMapsID").style.height="900px";
	//document.getElementById("YMapsID").style.width="1300px";
	//alert($('#YMapsID').html());
	
}

function resetAll()
{
	setVisibleL(false);
	$('#bill_type').data('type_curr','');
	$("#bill_type > div > span").css({'font-weight':'normal'}); //,'color':'black'
	$("#bill_type > div > input").attr('checked','');
	//$('#pl_id').val('');
}

function createIcon(val, type)
{
	var img='';
	if (val['img']) img="<img src='/getimage.php?img="+val['img']+"' width=300 border=1 style='display:block;'> <br>";
	var point_ = val['map'].split(",");
	var point = new YMaps.GeoPoint(point_[0],point_[1]);
	var placemark = new YMaps.Placemark(point, {style:"example#customPoint"+val['style']});
	placemark.name = val['number'];
	placemark.description = "<b style='font-size:14px;'>"+nositeli[type]['type_name']+" - № "+val['number']+"</b> <br>"+img+"<b>Улица:</b> "+val['address']+" <br> <b>Описание:</b> "+val['descr'];

	return placemark;
}

var blikAll;

function createNav()
{
	var all_pl=0;
	var nas_nav="<div rel='0' id='bill_type_all'><input type='radio' name='radioo' id='radio_0'><span>Показать всё</span><label></label></div>";
	for (var i=0;i<=nositeli.length-1;i++)
	{
		nas_nav+="<div rel='"+nositeli[i]['type']+"'><input type='radio' style='cursor:pointer;' name='radioo' id='radio_"+nositeli[i]['type']+"'><span style='color:"+Collors[i]+";'>"+nositeli[i]['type_name']+"</span> ("+nositeli[i]['options'].length+")</div>";
		
		var myLayerID=nositeli[i]['type'];
		myLayer[myLayerID] = new YMaps.GeoObjectCollection();
		var arrPoints = [];
		var arrPointsGroup = [];
		all_pl+=nositeli[i]['options'].length;
		
		for (var e=0;e<=nositeli[i]['options'].length-1;e++)
		{
			
			var arr=nositeli[i]['options'][e]['arr'];
			var val=nositeli[i]['options'][e];
			
			if (val['map'])
			{
				if (arr>0)
				{
					//alert(nositeli[i]['options'][e]['number']);
					if (typeof nositeli[i]['arr'][arr] != 'object') nositeli[i]['arr'][arr] = [];
					if (typeof nositeli[i]['arr'][arr]['placemark'] != 'object')
					{
						var point_ = val['map'].split(",");
						var point = new YMaps.GeoPoint(point_[0],point_[1]);
						nositeli[i]['arr'][arr]['placemark'] = new YMaps.Placemark(point, {style:"example#customPoint"+val['style']});
						nositeli[i]['arr'][arr]['placemark'].name = '...';
						nositeli[i]['arr'][arr]['placemark'].description = '';
						//alert(i+' '+arr);
						YMaps.Events.observe(nositeli[i]['arr'][arr]['placemark'], nositeli[i]['arr'][arr]['placemark'].Events.BalloonOpen, function(obj) {
						   baloon=obj;
						});
						
					}
					var img="";
					if (val['img']) img="<img src='/getimage.php?img="+val['img']+"' width=100 border=1 style='display:block;'>";
					else img="<img src='/img/spacer.gif' width=100 height=77 border=1 style='display:block;'>";
					var cont="<div style='float:left;margin:0px 10px 0px 0px;text-align:center;text-decoration:underline;cursor:pointer;' onclick='OpenBaloonInGroup(\""+val['number']+"\", \""+i+"\", \""+val['arr']+"\");'>"+img+" "+val['number']+"</div>";
					nositeli[i]['arr'][arr]['placemark'].description += cont;
				}
				else
				{
					arrPoints.push(createIcon(val, i));
				}

			}
		}
		
		for (var u in nositeli[i]['arr'])
		{
			
			if (typeof nositeli[i]['arr'][u] != 'function')
			{
				arrPoints.push(nositeli[i]['arr'][u]['placemark']);
			}
		}
		
		myLayer[myLayerID].add(arrPoints);
		
	}
	
	
	$('#bill_type').html(nas_nav);

	
	
	$('#bill_type').data('type_curr','0');
	
	$('#bill_type > div').css({'float':'left','cursor':'pointer','display':'block','width':'205px','margin':'0px 1px 1px 0px','border':'0xp solid red'});
	
	$('#bill_type > div')
	.click(function(){
		var rel = $(this).attr('rel');
		var type_curr=$('#bill_type').data('type_curr');
		if (rel != type_curr || (rel==0 && type_curr==0))
		{
			resetAll();
	/* 		$("#bill_type > span").each(function(){
				if($(this).attr('rel')==type_curr)
				{
					$(this).css({'font-weight':'normal','color':'black'});
					$('#radio_'+type_curr).attr('checked','');
				}
			});  */ //alert(type_curr)
			
			 //,'color':'red'
			//$('#radio_'+rel).attr('checked','checked');
			$(this).children().each(function(){
				if ($(this).attr('tagName').toLowerCase()=='input') $(this).attr('checked','checked');
				if ($(this).attr('tagName').toLowerCase()=='span') $(this).css({'font-weight':'bold'});
			});
			
			if (rel=='0')
			{
				setVisibleL(true);
			}
			else if (type_curr=='0')
			{
				if (myLayer[rel]) map.addOverlay(myLayer[rel]);//myLayer[rel].setVisible(true);
			}
			else if(type_curr!=rel)
			{
				if (myLayer[type_curr]) map.removeOverlay(myLayer[type_curr]);//myLayer[type_curr].setVisible(false);
				if (myLayer[rel]) map.addOverlay(myLayer[rel]);
			}

			$('#bill_type').data('type_curr', rel);
		}
	});
	$('#bill_type > div > span').css({'text-decoration':'underline'});
	$('#bill_type > div > label').html(" ("+all_pl+")");
	
	$("#bill_type_all").everyTime(2000, 'timer2', function(i) {
		$(this).effect("pulsate", { times:1 }, 1000);
	}, 0);
		
	$("#bill_type_all").one("click", function(){
	  $(this).stopTime('timer2');
	});
	
	$('#resetAll').click(function(){
		resetAll();
	});
	
	$('#pl_id').keydown(function(event){
		if (event.keyCode==13) showBaloon($('#pl_id').val());
	});
	
	$('#PushTheButton').click(function(){
		showBaloon_($('#pl_id').val());
	});
	
	var ParamPl=getParam('pl');
	if (ParamPl>0) showBaloon_(ParamPl);
	
	$('#Full').click(function(){
		YouFull(true);
	});

	
}

function showBaloon_(val)
{
	var pl=val;
	if (pl.length==1) pl="000"+pl;
	if (pl.length==2) pl="00"+pl;
	if (pl.length==3) pl="0"+pl;
	showBaloon(pl);
}

function showBaloon(val)
{
	if (val>0)
	{
		$('#pl_id').val(val);
		for (var i=0;i<=nositeli.length-1;i++)
		{
			for (var e=0;e<=nositeli[i]['options'].length-1;e++)
			{
				//if (nositeli[i]['options'][e]['arr']>0) alert(1);
				if (nositeli[i]['options'][e]['number']==val)
				{
					resetAll();
					var GeoPoint = nositeli[i]['options'][e]['map'].split(",");
					var ddd=createIcon(nositeli[i]['options'][e], i);
					//map.openBalloon(new YMaps.GeoPoint(GeoPoint[0], GeoPoint[1]), ddd.description, {hasCloseButton: true}); //mapAutoPan: 1,margin: [40, 10, 0, 45]
					map.addOverlay(ddd);
					map.setCenter(new YMaps.GeoPoint(GeoPoint[0], GeoPoint[1]), map.getZoom(), YMaps.MapType.MAP);
				}
			}
		}
	}
}

function getParam(sParamName)
{
    var Params = location.search.substring(1).split("&"); // отсекаем «?» и вносим переменные и их значения в массив
    var variable = "";
    for (var i = 0; i < Params.length; i++)
	{ // пробегаем весь массив
        if (Params[i].split("=")[0] == sParamName)
		{ // если это искомая переменная — бинго!
            if (Params[i].split("=").length > 1)
			{
				variable = Params[i].split("=")[1]; // если значение параметра задано, то возвращаем его
				return variable;
			}
        }
    }
    return "";
}

//$(document).ready(function()
window.onload = function()
{
	map = new YMaps.Map( document.getElementById("YMapsID") );
	
	map.setCenter(new YMaps.GeoPoint(32.017942,46.950586), 12, YMaps.MapType.MAP);
	map.enableScrollZoom();
	//map.addControl(new YMaps.TypeControl());
	map.addControl(new YMaps.Zoom());
	map.addControl(new YMaps.ToolBar());
	map.addControl(new YMaps.ScaleLine());
	mMap= new YMaps.MiniMap();
	map.addControl(mMap);
	mMap.setVisible(false);
	
	//YMaps.Events.observe(map,map.Events.BalloonOpen, function (obj) { //центровка  балуна, пока не работает
	   //alert(obj.getBalloonContent().innerHTML);
	   //baloon=obj;
	//});
	
	/*
	YMaps.Events.observe(map, map.Events.BalloonOpen, function (obj) {
	   //var content = obj.getBalloonContent().innerHTML + 'description';
	   //obj.setBalloonContent(content);
	   alert(obj.getBalloonContent().innerHTML);
	});
	*/
	
	
	
	
/* 	YMaps.Events.observe(map,map.Events.Click, function (mEvent) {
		var cont="<span id='coor'>"+mEvent.getGeoPoint()+"</span>";
		map.openBalloon(mEvent.getGeoPoint(), cont, {hasCloseButton:false});
		
		$('#coor').click(function(){
			//alert($(this).html());
			map.closeBalloon();
		});
	}); */

	
/*
	var gCollection = new Array;
	gCollection[0] = new YMaps.GeoObjectCollection("default#greenPoint");
	gCollection[1] = new YMaps.GeoObjectCollection("default#redPoint");

	var point = new YMaps.GeoPoint(28.48333,49.2333);
	var placemark = new YMaps.Placemark(point);
	gCollection[0].add(placemark);
	map.addOverlay(gCollection[0]);
	
	var point = new YMaps.GeoPoint(28.4844,49.2344);
	var placemark = new YMaps.Placemark(point);
	gCollection[1].add(placemark);
	map.addOverlay(gCollection[1]);
*/

	//var placemark = new YMaps.Placemark(new YMaps.GeoPoint(37.7,55.7), {style: s} );
	//placemark.description = 'Добро пожаловать на Яндекс.Карты!';
	//map.addOverlay(placemark);    
	//placemark.openBalloon();
	
	
	var template = new YMaps.Template();
	template.text = "<div><img title=\"$[name|0]\" style=\"height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x];\" src=\"$[style.iconStyle.href]\"\/><div class=\"CustomPointName\">$[name|0]</div></div>";
	//YMaps.Templates.add("example#customPointBlue", template);
	//YMaps.Templates.add("example#customPointRed", template);

	var Icons = [];
	Icons[0] = 'icon_light_blue.png';
	Icons[1] = 'icon_dark_blue.png';
	Icons[2] = 'icon_light_green.png';
	Icons[3] = 'icon_magenta.png';
	Icons[4] = 'icon_orange.png';
	Icons[5] = 'icon_yellow.png';
	Icons[6] = 'icon_gray.png';
	Icons[7] = 'icon_brown.png';
	
	Collors[0] = '#23b9ff';
	Collors[1] = '#2421e2';
	Collors[2] = '#34d42f';
	Collors[3] = '#ff00ff';
	Collors[4] = '#f76d04';
	Collors[5] = '#ffc62a';
	Collors[6] = '#818181';
	Collors[7] = '#bf4a25';
	
	for (var i=0;i<=Icons.length-1;i++)
	{
		var st = new YMaps.Style();
		st.iconStyle = new YMaps.IconStyle("example#customPoint"+i);
		st.iconStyle.offset = new YMaps.Point(-22, -46);
		st.iconStyle.href = "http://mediamapa.com.ua/img/"+Icons[i];
		st.iconStyle.size = new YMaps.Point(39, 42);
		st.iconStyle.shadow = new YMaps.IconShadowStyle();
		st.iconStyle.shadow.offset = new YMaps.Point(0, -25);
		st.iconStyle.shadow.href = "http://mediamapa.com.ua/img/icon_shadow.png";
		st.iconStyle.shadow.size = new YMaps.Point(25, 23);
		YMaps.Styles.add("example#customPoint"+i, st);
		
		YMaps.Templates.add("example#customPoint"+i, template);
	}


/*
	var sBlueLight = new YMaps.Style();
	sBlueLight.iconStyle = new YMaps.IconStyle("example#customPointBlue");
	sBlueLight.iconStyle.offset = new YMaps.Point(-22, -46);
	sBlueLight.iconStyle.href = "http://info.maps.yandex.net/api/i/steelblue/dot.png";
	sBlueLight.iconStyle.size = new YMaps.Point(26, 46);
	sBlueLight.iconStyle.shadow = new YMaps.IconShadowStyle();
	sBlueLight.iconStyle.shadow.offset = new YMaps.Point(0, -25);
	sBlueLight.iconStyle.shadow.href = "http://info.maps.yandex.net/api/i/dot_shadow.png";
	sBlueLight.iconStyle.shadow.size = new YMaps.Point(25, 23);
	YMaps.Styles.add("example#customPointBlue", sBlueLight);
	
	var sRed = new YMaps.Style();
	sRed.iconStyle = new YMaps.IconStyle("example#customPointRed");
	sRed.iconStyle.offset = new YMaps.Point(-22, -46);
	sRed.iconStyle.href = "http://info.maps.yandex.net/api/i/orange/dot.png";
	sRed.iconStyle.size = new YMaps.Point(26, 46);
	sRed.iconStyle.shadow = new YMaps.IconShadowStyle();
	sRed.iconStyle.shadow.offset = new YMaps.Point(0, -25);
	sRed.iconStyle.shadow.href = "http://info.maps.yandex.net/api/i/dot_shadow.png";
	sRed.iconStyle.shadow.size = new YMaps.Point(25, 23);
	YMaps.Styles.add("example#customPointRed", sRed); 
*/

	
	

/*
	myLayerID=2;
	myLayer[myLayerID] = new YMaps.ObjectLayer();
	var arrPoints = [];	
	var point = new YMaps.GeoPoint(28.4823,49.2323);
	arrPoints.push(new YMaps.Placemark(point, {style:"example#customPointRed"}));
	var point = new YMaps.GeoPoint(28.48324,49.2324);
	arrPoints.push(new YMaps.Placemark(point, {style:"example#customPointRed"}));
	myLayer[myLayerID].add(arrPoints);
	myLayer[myLayerID].setVisible(false);
	map.addLayer(myLayer[myLayerID]);
*/


	
	

/* 
nositeli[0] = [];
nositeli[0]['type'] = '4';
nositeli[0]['type_name'] = 'Биллборды 3x6';
nositeli[0]['options'] = [];
nositeli[0]['options'][0] = [];
nositeli[0]['options'][0]['img'] = '';
nositeli[0]['options'][0]['descr'] = '';
nositeli[0]['options'][0]['map'] = '28.4837,49.232865';
nositeli[0]['options'][0]['number'] = '0001';
nositeli[0]['options'][0]['address'] = 'Стахурского (Ботан.сад)';
nositeli[0]['options'][0]['style'] = '0'; 
nositeli[0]['options'][1] = [];
nositeli[0]['options'][1]['img'] = 'b7501ffd8ff857ecb6d80abd91e3f096.jpg';
nositeli[0]['options'][1]['descr'] = '';
nositeli[0]['options'][1]['map'] = '28.482676,49.235265';
nositeli[0]['options'][1]['number'] = '0146';
nositeli[0]['options'][1]['address'] = 'Киевская (подъезд к пл.Октября)';
nositeli[0]['options'][1]['style'] = '0'; 
nositeli[0]['options'][2] = [];
nositeli[0]['options'][2]['img'] = '786253ab6b7103be657d531f5f33910d.jpg';
nositeli[0]['options'][2]['descr'] = 'Центральная улица города, большой транспортный поток';
nositeli[0]['options'][2]['map'] = '28.478041,49.233723';
nositeli[0]['options'][2]['number'] = '0375';
nositeli[0]['options'][2]['address'] = 'Соборная';
nositeli[0]['options'][2]['style'] = '0'; 





nositeli[0]['options'][3] = [];
nositeli[0]['options'][3]['arr'] = '1';
nositeli[0]['options'][3]['img'] = 'df46181e3dffcbca264f9d76c16c8dbb.jpg';
nositeli[0]['options'][3]['descr'] = '222';
nositeli[0]['options'][3]['map'] = '28.516237,49.231488';
nositeli[0]['options'][3]['number'] = '0497';
nositeli[0]['options'][3]['address'] = 'Немировское шоссе';
nositeli[0]['options'][3]['style'] = '0'; 

nositeli[0]['options'][4] = [];
nositeli[0]['options'][4]['arr'] = '1';
nositeli[0]['options'][4]['img'] = '9b8f6ae45cbda6ce2f0b163986cce1ef.jpg';
nositeli[0]['options'][4]['descr'] = '111';
nositeli[0]['options'][4]['map'] = '28.516237,49.231488';
nositeli[0]['options'][4]['number'] = '0498';
nositeli[0]['options'][4]['address'] = 'Немировское шоссе';
nositeli[0]['options'][4]['style'] = '0'; 

nositeli[0]['options'][5] = [];
nositeli[0]['options'][5]['arr'] = '1';
nositeli[0]['options'][5]['img'] = '7964fef138192a4e83ed51c4bf02f345.jpg';
nositeli[0]['options'][5]['descr'] = '333';
nositeli[0]['options'][5]['map'] = '28.516237,49.231488';
nositeli[0]['options'][5]['number'] = '0499';
nositeli[0]['options'][5]['address'] = 'Немировское шоссе';
nositeli[0]['options'][5]['style'] = '0';





nositeli[1] = [];
nositeli[1]['type'] = '5';
nositeli[1]['type_name'] = 'Бэклайты РИА';
nositeli[1]['options'] = [];
nositeli[1]['options'][0] = [];
nositeli[1]['options'][0]['img'] = '2df34f76bafe47adc5a122fbf36f96ba.jpg';
nositeli[1]['options'][0]['descr'] = '';
nositeli[1]['options'][0]['map'] = '28.468662,49.232582';
nositeli[1]['options'][0]['number'] = '0540';
nositeli[1]['options'][0]['address'] = 'пл. Незалежности';
nositeli[1]['options'][0]['style'] = '1';
nositeli[2] = [];
nositeli[2]['type'] = '6';
nositeli[2]['type_name'] = 'Ситилайты';
nositeli[2]['options'] = [];
nositeli[2]['options'][0] = [];
nositeli[2]['options'][0]['img'] = '';
nositeli[2]['options'][0]['descr'] = 'sdf sdf sdf sfd';
nositeli[2]['options'][0]['map'] = '28.437419,49.234212';
nositeli[2]['options'][0]['number'] = '0516';
nositeli[2]['options'][0]['address'] = '0516';
nositeli[2]['options'][0]['style'] = '2'; */





/* {type: '4', type_opt: {type_name: 'Биллборды 3x6', 
options: {img: '', descr: '', map: '28.4837,49.232865', number: '0001', address: 'Стахурского (Ботан.сад)' },
options: {img: 'b7501ffd8ff857ecb6d80abd91e3f096.jpg', descr: '', map: '28.482676,49.235265', number: '0146', address: 'Киевская (подъезд к пл.Октября)' },
options: {img: '2df34f76bafe47adc5a122fbf36f96ba.jpg', descr: '', map: '28.468662,49.232582', number: '0540', address: 'пл. Незалежности' }}} 

nositeli[1] = {type: '10', type_opt: {type_name: 'Пилоны 1,5х3', 
options: {img: '786253ab6b7103be657d531f5f33910d.jpg', descr: 'Центральная улица города, большой транспортный поток.476011,49.2326&spn=0.017212,0.0058&rl=28.476244,49.233241', map: '28.478041,49.233723', number: '0375', address: 'Соборная' 
}}} */

createNav();


/* nositeli[0]['arr'] = [];
nositeli[0]['arr'][1] = [];
nositeli[0]['arr'][1]['map'] = '28.516237,49.231488';
var point = new YMaps.GeoPoint(28.516237,49.231488);
nositeli[0]['arr'][1]['placemark'] = new YMaps.Placemark(point, {style:"example#customPoint1"});
nositeli[0]['arr'][1]['placemark'].name = '...';

var val = [];
val['img']='df46181e3dffcbca264f9d76c16c8dbb.jpg';
img="<img src='/getimage.php?img="+val['img']+"' width=100 border=1 style='display:block;'>";
nositeli[0]['arr'][1]['placemark'].description = "<div style='float:left;text-align:center;text-decoration:underline;cursor:pointer;' onclick='OpenBaloonInGroup(0497, 0, 1);'>"+img+" 111</div>";

val['img']='9b8f6ae45cbda6ce2f0b163986cce1ef.jpg';
img="<img src='/getimage.php?img="+val['img']+"' width=100 border=1 style='display:block;'>";
nositeli[0]['arr'][1]['placemark'].description += "<div style='float:left;text-align:center;text-decoration:underline;cursor:pointer;' onclick='OpenBaloonInGroup(0498, 0, 1);'>"+img+" 222</div>";

val['img']='7964fef138192a4e83ed51c4bf02f345.jpg';
img="<img src='/getimage.php?img="+val['img']+"' width=100 border=1 style='display:block;'>";
nositeli[0]['arr'][1]['placemark'].description += "<div style='float:left;text-align:center;text-decoration:underline;cursor:pointer;' onclick='OpenBaloonInGroup(0499, 0, 1);'>"+img+" 333</div>";

//alert(nositeli[0]['arr'][1]['placemark'].description);
myLayer[4].add(nositeli[0]['arr'][1]['placemark']); */

//alert(nositeli[0]['arr'][96]['placemark'].description);

};



function OpenBaloonInGroup(id, type, group)
{

	var d="<div >"+nositeli[type]['arr'][group]['placemark'].description+"</div>";
	//alert(d);
	for (var e=0;e<=nositeli[type]['options'].length-1;e++)
	{
		if (nositeli[type]['options'][e]['number']==id)
		{
			var img='';
			if (nositeli[type]['options'][e]['img']) img="<img src='/getimage.php?img="+nositeli[type]['options'][e]['img']+"' width=300 border=1 style='display:block;'>";
			var d1 = "<div><b style='font-size:14px;'>"+nositeli[type]['type_name']+" - № "+nositeli[type]['options'][e]['number']+"</b> <br>"+img+"<b>Улица:</b> "+nositeli[type]['options'][e]['address']+" <br> <b>Описание:</b> "+nositeli[type]['options'][e]['descr']+"</div><br>";
		}
	}
	//alert(baloon.getBalloonContent().innerHTML);
	//baloon.maxWidth = 400;
	baloon.setBalloonContent( d1 + d );
	
	//alert(d1 + d);
}


