var Yaina;
if (!Yaina) Yaina = OpenLayers.Class();
if (!Yaina.Layer) Yaina.Layer = OpenLayers.Class();

Yaina.Layer.PhotoCollection = OpenLayers.Class( OpenLayers.Layer.Markers, {
    url: null,
    features: null,
    selectedFeature: null,
    highlightPOI: null,

    initialize: function(name, url, poi, options) {
	var newArguments = new Array()
	newArguments.push(name, options);
        OpenLayers.Layer.Markers.prototype.initialize.apply(this, newArguments);


	// The constructor of OpenLayers.Icon does not actually load the graphics...
	cacheicon1=new Image(22,22);
	cacheicon1.src="http://tracks.yaina.de/camera-active-22px.png";
	cacheicon2=new Image(22,22);
	cacheicon2.src="http://tracks.yaina.de/camera-22px.png";

        this.url = url;
        this.features = new Array();

	var size = new OpenLayers.Size(22,22);
	var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);

	this.icon = new OpenLayers.Icon('http://tracks.yaina.de/camera-22px.png', size, offset);
	this.active_icon = new OpenLayers.Icon('http://tracks.yaina.de/camera-active-22px.png', size, offset);

	this.highlightPOI=poi;

	var results = OpenLayers.loadURL(url, null, this, this.requestSuccess, this.requestFailure);
    },
    destroy: function() {
        this.clearFeatures();
        this.features = null;
        OpenLayers.Layer.Markers.prototype.destroy.apply(this, arguments);
    },
        
    requestSuccess:function(request) {
	var gpxns = "http://www.topografix.com/GPX/1/0";
        var doc = request.responseXML;
        if (!doc || request.fileType!="XML") {
            doc = OpenLayers.parseXMLString(request.responseText);
        }
        if (typeof doc == "string") {
            doc = OpenLayers.parseXMLString(doc);
        }
	
	var highlightFeature = null;

  	var wpt = doc.getElementsByTagName("wpt");		

        for (var i = 0; i< wpt.length; i++) {
		var data = {}; 
		var location = new OpenLayers.LonLat(wpt[i].getAttribute('lon'),wpt[i].getAttribute('lat')).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());

		var title = "Untitled";
		try {
			title = OpenLayers.Util.getNodes(wpt[i], 
				'name')[0].firstChild.nodeValue;
		}
		catch (e) { title="Untitled"; }

		var description = "No description.";
		try {
			description = OpenLayers.Util.getNodes(wpt[i],
				'desc')[0].firstChild.nodeValue;
		}catch (e) {
			var description = "Thumbnail unavailable";
		}

		var time = null;
		try {
			time = OpenLayers.Util.getNodes(wpt[i],
				'time')[0].firstChild.nodeValue;
		}catch (e) { }
		data['timestamp'] = time;

		var comment = null;
		try {
			comment = OpenLayers.Util.getNodes(wpt[i],
				'cmt')[0].firstChild.nodeValue;
		}catch (e) { }

		var link = null;
		try {
			link = OpenLayers.Util.getNodes(wpt[i],
				'link')[0].getAttribute("href");
		} catch (e) { }

		contentHTML='<p title="Click to view picture"><br/>'+description;
		if (comment) contentHTML += '<br/>'+comment;
		if (time) {
			var t1=time.split("T");
			var t2;

			contentHTML += '<br/>'+t1[0]+" ";
		}
		contentHTML += '</p><hr/>';

		data['popupContentHTML'] = contentHTML;

		if (link) data['photoURI'] = link;

		data['layer'] = this;

		var featureWPT = new OpenLayers.Feature(this, location, data);

		if (time == this.highlightPOI) {
			highlightFeature = featureWPT;
			data.icon = this.active_icon.clone();
		} else {
			data.icon = this.icon.clone();
		}

		this.features.push(featureWPT);
		var marker = featureWPT.createMarker();
		marker.events.register('click', featureWPT, this.markerClick);
		this.addMarker(marker);
        }

	if (highlightFeature) {
		this.removeMarker(highlightFeature.marker);
		this.addMarker(highlightFeature.marker);
		var lonlat=highlightFeature.lonlat;
		var thumbdiv=document.getElementById("thumbs");
		var bounds=new OpenLayers.Bounds(lonlat.lon-10, lonlat.lat-10, lonlat.lon+10, lonlat.lat+10);

		for (var k=0; k < this.features.length; k++) {
			var feature=this.features[k];
			if (bounds.containsLonLat(feature.lonlat)) {
				var item = this.addThumbnail(lonlat, feature.data);
				thumbdiv.appendChild(item);
				if (feature.data["timestamp"] == this.highlightPOI) 
					item.onclick();
			}
		}
	}
    },

    requestFailure: function(request) {
	var div=document.getElementById("photo");
	div.innerHTML="GPX file "+this.url+" not found or not accessible.</p>";
    },

    addThumbnail: function(lonlat, data) {
	var item=document.createElement("div");
	item.setAttribute("class", "thumbnail");
	item.setAttribute("ref", data['photoURI']);
	item.setAttribute("id", "thumb-"+data['timestamp']);
	item.setAttribute("time", data['timestamp']);
	item.setAttribute("lat", lonlat.lat);
	item.setAttribute("lon", lonlat.lon);
	item.innerHTML=data['popupContentHTML'];
	item.onclick=this.thumbnailClick;
	item.onmouseover=this.thumbnailMouseOver;
	item.onmouseout=this.thumbnailMouseOut;
	return item;
    },
    markerClick: function(evt) {
	var lonlat;
	var layer;

	layer=this.data['layer'];
	lonlat=this.lonlat;

	var thumbdiv=document.getElementById("thumbs");

	while(thumbdiv.childNodes.length != 0)
		thumbdiv.removeChild(thumbdiv.childNodes[0]);

	var bounds=new OpenLayers.Bounds(lonlat.lon-10, lonlat.lat-10, lonlat.lon+10, lonlat.lat+10);

	for (var k=0; k < layer.features.length; k++)
	{
		var feature=layer.features[k];

		layer.removeMarker(feature.marker);
		feature.destroyMarker();

		if (bounds.containsLonLat(feature.lonlat))
		{
			var item = layer.addThumbnail(lonlat, feature.data);
			thumbdiv.appendChild(item);
			feature.data.icon = layer.active_icon.clone();
		} else {
			feature.data.icon = layer.icon.clone();
		}

		var marker=feature.createMarker();
		marker.events.register('click', feature, layer.markerClick);
		layer.addMarker(marker);
	}

	if (evt)
		OpenLayers.Event.stop(evt);
    },
    clearFeatures: function() {
        if (this.features != null) {
            while(this.features.length > 0) {
                var feature = this.features[0];
                OpenLayers.Util.removeItem(this.features, feature);
                feature.destroy();
            }
        }        
    },

    thumbnailClick: function (evt) {
	var thumbdiv=document.getElementById("thumbs");
	for (k=0; k < thumbdiv.childNodes.length; k++) {
		div=thumbdiv.childNodes[k];
		if (div) {
			div.style.backgroundColor = '#cccccc';
			div.setAttribute("shown", "0");
		}
	}

	var photodiv=document.getElementById("photo");
	while(photodiv.childNodes.length != 0)
		photodiv.removeChild(photodiv.childNodes[0]);

	this.style.backgroundColor = '#808080';
	this.setAttribute("shown", "1");

	var link = this.getAttribute("ref");
	if (link) {
		var img=document.createElement("img");
		img.setAttribute("src", link);
		img.setAttribute("id", "picture");
		img.setAttribute("lon", this.getAttribute("lon"));
		img.setAttribute("lat", this.getAttribute("lat"));
		img.setAttribute("time", this.getAttribute("time"));
		img.setAttribute("title", "Click to zoom in on map");
		img.onclick=Yaina.Layer.PhotoCollection.prototype.photoClick;
		photodiv.appendChild(img);
	}

	if (permalink) permalink.updateLink();
    },

    thumbnailMouseOver: function(evt) {
	if (this.getAttribute("shown") != "1")
		this.style.backgroundColor = '#bbbbbb';
    },

    thumbnailMouseOut: function(evt) {
	if (this.getAttribute("shown") != "1")
		this.style.backgroundColor = '#cccccc';
    },

    photoClick: function(evt)
    {
	var lonlat=new OpenLayers.LonLat(this.getAttribute("lon"), this.getAttribute("lat"));
	map.setCenter(lonlat, 13);
    },

    CLASS_NAME: "Yaina.Layer.PhotoCollection"
});


