// var markerGroups=new Array();
// markerGroups = { "Parkingi": [], 'Inne': []};

var idInterwal=new Array();
var map;
document.map=0;
var loaded=0;
var cookiename="mapinfo";
var expiredays = 7;


$(window).resize(function() {
	if (startpage!=0){
		$("#routes").css( {height:0} );
		$("#map").css( {height:0} );
		//var temp=$("#route_cell").height()-214;
		var temp=$("#mainTable").height()-250 - 120 -50;
		if(temp<150)
			temp=150;
		$("#routes").css( {height:temp} );
		$("#map").css( {height:$("#route_cell").height()} );

		temp=$("#header").width()-313;
		$("#map_td").css( {width:temp} );
	}
  });



function showWindow()
{
  win = new Window( { className: 'spread', url:'http://www.wp.pl',
    title: 'Simple Window', width:400,
    height:300, destroyOnClose: true, recenterAuto:false } );
  win.showCenter();
}

function initMenu() {

  $('#menu ul').hide();
  //$('#menu ul:first').show();
  $('#menu li a').click(
    function() {
      var checkElement = $(this).next();
      if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        checkElement.slideUp('normal');
        return false;
        }
      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
//         $('#menu ul:visible').slideUp('normal');
        checkElement.slideDown('normal');
        return false;
        }
      }
    );
  }

$(document).ready(function() {initMenu();});


function waiting(sciezka, node)
	{
		if (loaded==1){
			if(sciezka==0)
			{

				createMarkerForNewRoute(edit_noda);

			}
			else
				generateMarker(sciezka);

			clearInterval(idInterwal[node])
			}
	}

function waiting_toogleRoute(pid,lid,id, path)
{

		if (loaded==1){
			toggleRoute(pid,lid,id,path)

			clearInterval(idInterwal[id])
			}
}

function setCookie() {
        maptype = 0;
        for (var i=0;i<document.map.getMapTypes().length;i++) {
          if (document.map.getCurrentMapType() == document.map.getMapTypes()[i]) {
            maptype = i;
          }
        }
        var cookietext = cookiename+"="+document.map.getCenter().lat()+"|"+document.map.getCenter().lng()+"|"+document.map.getZoom()+"|"+maptype;
        if (expiredays) {
          var exdate=new Date();
          exdate.setDate(exdate.getDate()+expiredays);
          cookietext += ";expires="+exdate.toGMTString();
        }
        // == write the cookie ==
        document.cookie=cookietext;

        // == Call GUnload() on exit ==
        GUnload();
        }










function mapaStart(atrib)
	{
			$(document).ready(
			function ()
			{

			if (startpage!=0)
				{
				$("#sidebar").css( {width:313} );
				var temp=$("#header").width()-313;
				$("#map_td").css( {width:temp} );

				$("#routes").css( {height:0} );
				$("#map").css( {height:0} );

				var temp=$("#mainTable").height()-214 - 120 -50;

				if(temp<150)
					temp=150;

				$("#routes").css( {height:temp} );

				temp=$("#route_cell").height();

				$("#map").css( {height:temp} );

				}
			else{
				$("#sidebar").css( {width:350} );
				var temp=$("#header").width()-350;
				$("#map_td").css( {width:temp} );
				$("#map").css( {height:0} );
				temp=$("#route_cell").height();
				$("#map").css( {height:temp} );

				}
			});



// We define the function first
function PrintControl() {
}

// To "subclass" the GControl, we set the prototype object to
// an instance of the GControl object
PrintControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.

PrintControl.prototype.initialize = function(map) {
	var container = document.createElement("div");

	var newimg=document.createElement('img');
	newimg.src='/design/mapa/images/printer.gif'
	newimg.alt='print'

	var printDiv = document.createElement("div");
	this.setButtonStyle_(printDiv);
	container.appendChild(printDiv);
	//printDiv.appendChild(document.createTextNode("<img src='/design/mapa/images/printer.gif' alt='' />"));
	printDiv.appendChild(newimg);
	GEvent.addDomListener(printDiv, "click", function() {

		if ($.browser.msie){
			$('#map').print();
			}
		else{

			var mapAd = '<div class="print_preview">&nbsp;</div>';
			$("#mainTable").append(mapAd);

			if (confirm('Wydrukowany zostanie obszar zaznaczony kolorem żółtym. Kontynuować?')) {
			$('#map').print();
			}

			$(".print_preview").hide();
			}



	});

	map.getContainer().appendChild(container);
	return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
PrintControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(232, 7));
}

// Sets the proper CSS for the given button element.
PrintControl.prototype.setButtonStyle_ = function(button) {
  button.style.backgroundColor = "#fbffff";
  button.style.border = "1px solid black";
  button.style.padding = "1px";
  button.style.marginBottom = "0px";
  button.style.textAlign = "center";
  button.style.width = "2em";
  button.style.cursor = "pointer";

}








		if(GBrowserIsCompatible())
		{

		document.map = new GMap2(document.getElementById("map"));


		var lat = 53.42793169256846;
		var lng = 14.5525390625;
		var zoom = 14;
		var maptype =3;




		if (document.cookie.length>0) {

			cookieStart = document.cookie.indexOf(cookiename + "=");
			if (cookieStart!=-1) {

				cookieStart += cookiename.length+1;
				cookieEnd=document.cookie.indexOf(";",cookieStart);
				if (cookieEnd==-1) {
				cookieEnd=document.cookie.length;
				}
				cookietext = document.cookie.substring(cookieStart,cookieEnd);
				// == split the cookie text and create the variables ==
				bits = cookietext.split("|");
				lat = parseFloat(bits[0]);
				lng = parseFloat(bits[1]);
				zoom = parseInt(bits[2]);
				maptype = parseInt(bits[3]);

			}
		}


		document.map.addMapType(G_PHYSICAL_MAP);
		document.map.enableScrollWheelZoom();
		document.map.addControl(new GLargeMapControl());
		//mapa.disableScrollWheelZoom()
		//map.enableContinuousZoom();
		document.map.addControl(new PrintControl());
// 		document.map.setCenter(new GLatLng(lat,lng), zoom);
// 		document.map.setMapType(maptype);

		document.map.setCenter(new GLatLng(lat,lng),zoom,document.map.getMapTypes()[maptype]);


		document.map.addControl(new GMapTypeControl());
		document.map.addControl(new GScaleControl());

		loaded=1;

		if(atrib=="edit")
			{
				var lat_id = document.getElementById('lat_id_input').value;
				var lng_id = document.getElementById('lng_id_input').value;



				if (document.getElementById(lat_id).value && document.getElementById(lng_id).value )
					{
						var point= new GLatLng(document.getElementById(lat_id).value, document.getElementById(lng_id).value)

					}
				else
					{

						document.getElementById(lat_id).value=lat;
						document.getElementById(lng_id).value=lng;
						var point= new GLatLng(lat,lng)
					}


				var markerPoint = new GMarker(point,{draggable: true});
				document.map.addOverlay(markerPoint);

				GEvent.addListener(markerPoint,'dragend',function()
							{
								zmienStatus(markerPoint.getPoint());
							});


				GEvent.addListener(document.map, "click", function(overlay,latlng) {
          			if (latlng) {
						zmienStatus(markerPoint.getPoint());
						document.map.removeOverlay(markerPoint);
						markerPoint = new GMarker(latlng,{draggable: true});
						document.map.addOverlay(markerPoint);

						GEvent.addListener(markerPoint,'dragend',function()
							{
								zmienStatus(markerPoint.getPoint());
							});


					}
				});




			}

		}

}




function generateMarker(sciezka)
{

	GDownloadUrl(sciezka, function(data) {

		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < markers.length; i++) {

			var link = markers[i].getAttribute("link");
			var type = markers[i].getAttribute("type");
			var id = markers[i].getAttribute("id");
			var nazwa = markers[i].getAttribute("nazwa");
			var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
							parseFloat(markers[i].getAttribute("lon")));

		 	var ikona = new GIcon();

			ikona.image = markers[i].getAttribute("ikona");
			if(markers[i].getAttribute("size")=='small'){
				ikona.iconSize = new GSize(12,20);
				ikona.iconAnchor = new GPoint(6,20);
				ikona.infoWindowAnchor = new GPoint(6,1);

			}
			else{
				ikona.iconSize = new GSize(17, 18);
				ikona.infoWindowAnchor = new GPoint(1,18);
				ikona.iconAnchor = new GPoint(1,18);
				ikona.shadow = "http://mapa.rowerowy.szczecin.pl/design/mapa/images/m_shadow.png";
      			ikona.shadowSize = new GSize(23, 23);
				}


			var marker = createMarker( point, {title: nazwa, icon: ikona},link,id);
			document.map.addOverlay(marker);
			markerGroups[type].push(marker);

  		}
	}
	);

}

function toggleLayer(id,sciezka) {

	if(markerGroups[id][0]==null)
	{
		generateMarker(sciezka);
	}
	else{
		toggleGroup(id);
	}
}

function toggleGroup(type) {


        for (var i = 0; i < markerGroups[type].length; i++) {

        var marker = markerGroups[type][i];
        if (marker.isHidden()) {
          marker.show();

        } else {
          marker.hide();

        }
      }
    }


function createMarker(point, options, link, id) {
 	var marker = new GMarker(point,options);
 	   GEvent.addListener(marker, "click", function() {
     //    window.open(link,'window1','width=520,height=200,scrollbars=1');
		tb_show('tytul',link+'?placeValuesBeforeTB_=savedValues&amp;TB_iframe=true&modal=false',id);

	//	showWindow(link)
        });
	return marker;
}



function zmienStatus(punkt)
		{
			var lat_id = document.getElementById('lat_id_input').value;
			var lng_id = document.getElementById('lng_id_input').value;

 			document.getElementById(lat_id).value=punkt.lat();
 			document.getElementById(lng_id).value=punkt.lng();

		}