
PageGMaps = {};

Import.clone(GMaps, PageGMaps);

PageGMaps.pointsXmlFile = '';

PageGMaps.linesXmlFile = '';

PageGMaps.iconsPath = '';

PageGMaps.layersCount = 0;

PageGMaps.layersAndLinesCount = 0;

PageGMaps.checkboxLayerPrefix = 'layer';

PageGMaps.linkToInstitution = '?str={str}&id={id}';

PageGMaps.map = null;

PageGMaps.geo = null;

PageGMaps.markers = {};

PageGMaps.lines = {};

PageGMaps.centerX = GMaps.position.X;
PageGMaps.centerY = GMaps.position.Y;

PageGMaps.selectedLayerId = 0;

//console.dir(PageGMaps);

PageGMaps.labels = {
	  'more' 	: ''
	, 'address' : ''
	, 'phone'	: ''
	, 'fax'		: ''
	, 'email'	: ''
	, 'www'		: ''
};


PageGMaps.init = function(){
    if(GBrowserIsCompatible()){
    	//alert('fdh');
        PageGMaps.map = new GMap2(document.getElementById('mapBox'));

        var typyMapy = PageGMaps.map.getMapTypes();
        typyMapy[0].getName = function(){
            return 'Mapa';
        }
        typyMapy[1].getName = function(){
            return 'Satelita';
        }
        typyMapy[2].getName = function(){
            return 'Hybryda';
        }

	PageGMaps.map.addControl(new GMapTypeControl());
        PageGMaps.map.addControl(new GLargeMapControl3D());

        PageGMaps.map.setCenter(new GLatLng(PageGMaps.centerX, PageGMaps.centerY), PageGMaps.ZOOM);
        //PageGMaps.map.addControl(new GOverviewMapControl());
        PageGMaps.map.enableDoubleClickZoom();
        PageGMaps.map.enableScrollWheelZoom();
        PageGMaps.map.enableContinuousZoom();

        PageGMaps.geo = new GClientGeocoder();
        Info = new GOverlay();

        PageGMaps.loadMarkers();
        PageGMaps.loadLines();
    }
};


function Info(punkt,tekst,klasa)
{
    this.tekst = tekst;
    this.punkt = punkt;
    this.klasa = klasa;
};

Info.initialize = function(mapa)
{
   var kontener = document.createElement("div");
   kontener.className = this.klasa;
   kontener.style.position = 'absolute';
   var span = document.createElement("span");
   span.innerHTML = this.tekst;
   kontener.appendChild(span);
   mapa.getPane(G_MAP_MAP_PANE).appendChild(kontener);
   this.mapa = mapa;
   this.kontener = kontener;
};

Info.remove = function()
{
    this.kontener.parentNode.removeChild(this.kontener);
};

Info.copy = function()
{
    return new info(this.punkt,this.tekst,this.klasa);
};

Info.redraw = function(wymus)
{
    if (!wymus)
        return;
    this.kontener.style.top = (mapa.fromLatLngToDivPixel(this.punkt).y+3)+'px';
    this.kontener.style.left = mapa.fromLatLngToDivPixel(this.punkt).x+'px';
};


PageGMaps.loadMarkersFromSelectedLayers = function(){

};

PageGMaps.loadMarkers = function(){
    PageGMaps.map.clearOverlays();
    //GLog.write('Wczytuję '+url); // w celach diagnostycznych
    GDownloadUrl(PageGMaps.pointsXmlFile, function(xmlContent, callbackCode){
		var xml = GXml.parse(xmlContent);
        var markers = xml.documentElement.getElementsByTagName('point');
		var attributes = ['id', 'name', 'description', 'address', 'phone', 'fax', 'email', 'link'
		, 'icon', 'x', 'y', 'layerId', 'pageId', 'institutionId'];
		var v = {};
        for(var i = 0; i < markers.length; i++){
        	for(var j = 0; j < attributes.length; j++){
        		v[attributes[j]] = markers[i].getAttribute(attributes[j]).replace(/&quot;/g,'"');
        	}

			var id = markers[i].getAttribute('id');
			var layerId = markers[i].getAttribute('layerId');
	if((PageGMaps.selectedLayerId==0) || (PageGMaps.selectedLayerId==layerId)){
	            PageGMaps.markers[id] = {
       	     	  'layerId'	: layerId
            		, 'marker'	: PageGMaps.addMarker(v)
            		};
		}
        }
    });
};

PageGMaps.loadLines = function(){
    PageGMaps.map.clearOverlays();
/*
    GDownloadUrl(PageGMaps.linesXmlFile, function(xmlContent, callbackCode){

    	var xml = GXml.parse(xmlContent);

    	var lines = xml.documentElement.getElementsByTagName('line');

    	var attributes = ['nazwa','layerId','linia_id','linie_wielobok','kolor','grubosc',
    	                  'kolor_tla','przezroczystosc','jezyk_id','point'];
		var v = {};
		var aa={};
        for(var i = 0; i < lines.length; i++){
        	for(var j = 0; j < (attributes.length-1); j++){
        		v[attributes[j]] = lines[i].getAttribute(attributes[j]);
        	}
        	var iter=0;
        	zz_x=new Array();
        	zz_y=new Array();
	        while (xml.documentElement.getElementsByTagName('line')[i].getElementsByTagName('point')[iter]){
	        	aa_x=xml.documentElement.getElementsByTagName('line')[i].getElementsByTagName('point')[iter].getAttribute('polozenie_x');
	        	aa_y=xml.documentElement.getElementsByTagName('line')[i].getElementsByTagName('point')[iter].getAttribute('polozenie_y');
	        	zz_x[iter]=aa_x;
	        	zz_y[iter]=aa_y;
	        	iter++;
	        }
        	v['point']=new Object();
        	v['point']['polozenie_x']=zz_x;
        	v['point']['polozenie_y']=zz_y;
        	//console.dir(v['point']);
        	//console.dir(v);
			var id = lines[i].getAttribute('id');
			var layerId = lines[i].getAttribute('layerId');
			//console.dir(layerId);
            PageGMaps.lines[id] = {
            	  'layerId'		: layerId
            	, 'linia'		: PageGMaps.addLines(v)
            };
        }
    });
	*/
};

PageGMaps.addLines = function(v){
    pun=new Array();
    for(var i=0;i<v['point']['polozenie_x'].length;i++){
    	pun[i]=new GLatLng(v['point']['polozenie_y'][i],v['point']['polozenie_x'][i]);
    }
    last=v['point']['polozenie_x'].length;
	if(v['linie_wielobok']=0){
		polilinia = new GPolyline(pun,v['kolor'],v['grubosc'],v['przezroczystosc']);
	}else{
		pun[last+1]=pun[0];
		polilinia = new GPolygon(pun,v['kolor'],v['grubosc'],v['przezroczystosc'],v['kolor_tla']);
	}
	PageGMaps.map.addOverlay(polilinia);
	//PageGMaps.map.addOverlay(new Info(PageGMaps.map.getCenter(),'Szczecin','zwykly'));
    return polilinia;
};



PageGMaps.addMarker = function(v){
    if(v.icon == ''){
    	var icon = new GIcon(G_DEFAULT_ICON);
        icon.iconSize = new GSize(20, 34);
    }
    else{
    	var icon = new GIcon();
        icon.image = PageGMaps.iconsPath + v.icon;
        icon.iconSize = new GSize(16, 16);
    }

    icon.iconAnchor = new GPoint(15, 12);
    //icon.shadow = '';
    icon.infoWindowAnchor = new GPoint(0, 0);

    var marker = new GMarker(
    	  new GLatLng(parseFloat(v.x), parseFloat(v.y))
    	, {'title': v.name, 'icon': icon}
    );

    var content = '<div><b>' + v.name + '</b></div>';
	if(parseInt(v.institutionId) == 0){
		if(v.description != ''){
			content += '<div>' + v.description + '</div>';
		}
		if(v.link != ''){
			content += '<div><a href="' + v.link + '" target="_blank">' + v.link + '</a></div>';
		}
	}
	else{
		content += '<div>' + v.address + '</div>';
		if(v.phone != ''){
			content += '<div>tel.: ' + v.phone + '</div>';
		}
		if(v.fax != ''){
			content += '<div>fax: ' + v.fax + '</div>';
		}
		if(v.email != ''){
			content += '<div>e-mail: <a href="mailto:' + v.email + '">' + v.email + '</a></div>';
		}
		if(v.link != ''){
			content += '<div>www: <a href="' + v.link + '" target="_blank">' + v.link + '</a></div>';
		}
		if(v.pageId != '' && v.institutionId != ''){
			var href = PageGMaps.linkToInstitution;
			href = href.replace('{str}', v.pageId);
			href = href.replace('{id}', v.institutionId);
			content += '<div style="margin: 5px 0 0 0;"><a href="' + href + '" target="_blank">'
			+ PageGMaps.labels.more + '</a></div>';
		}
	}
	marker.info = '<div style="margin: 0 15px 0 0; width: 400px;">' + content + '</div>';

	PageGMaps.map.addOverlay(marker);

    GEvent.addListener(marker, 'click', function(a, b){
        marker.openInfoWindowHtml(marker.info);
    });

    return marker;
};

PageGMaps.changeLayerVisibility = function(field, index){
	//console.dir(field);
	var form = field.form;
	if(field.type != 'checkbox'){ //jezeli zdarzenie pochodzi od buttona
		field = form[PageGMaps.checkboxLayerPrefix + index];
		field.checked = !field.checked;
	}
	if(index > 0){
		checkboxName = PageGMaps.checkboxLayerPrefix + 0;
		//console.dir(checkboxName);
		form[checkboxName].checked = false;
		//console.dir(field.value+field.checked);
		PageGMaps.visibileLayer(field.value, field.checked);
	}
	else{//jezeli wybrana opcja wszystkie warstwy
		//if(field.checked){
			var checkboxName;
			for(var i = 0; i <= PageGMaps.layersCount; i++){
				checkboxName = PageGMaps.checkboxLayerPrefix + i;
				form[checkboxName].checked = field.checked;
				PageGMaps.visibileLayer(form[checkboxName].value, field.checked);
				//__changeV(form[checkboxName].value, field.checked);
			}
		//}


	}
};

PageGMaps.visibileLayer = function(layerId, isVisible){
	//console.dir('jestesmy w changevisible layer');
	for(var i in PageGMaps.markers){
		if(PageGMaps.markers[i]['layerId'] == layerId){
			with(PageGMaps.markers[i]['marker']){
				isVisible ? show() : hide();
			}
		}
	}
/*	
for(var i in PageGMaps.lines){
		if(PageGMaps.lines[i]['layerId'] == layerId){
			//console.dir(PageGMaps.lines[i]['layerId']);
			//console.dir(layerId);
			with(PageGMaps.lines[i]['linia']){
				isVisible ? show() : hide();
			}
		}
	}
*/
};






