/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
* license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */

/**
* @requires OpenLayers/Layer/GML.js
* @requires OpenLayers/Layer/Vector.js
* @requires OpenLayers/Ajax.js
*/

/**
* Class: OpenLayers.Layer.GML
* Create a vector layer by parsing a KML file.
*
* Inherits from:
*  - <OpenLayers.Layer.GML>
*/
OpenLayers.Layer.KML = OpenLayers.Class(OpenLayers.Layer.GML, {

    formatObject: null,

    convertGeometries: true,

    skipDrawFeature: false,
    
    initialize: function(name, url, options) {
        var newArguments = [];
        newArguments.push(name, url, options);
        OpenLayers.Layer.GML.prototype.initialize.apply(this, newArguments);

        this.format = OpenLayers.Format.AdvancedKML;

        var fOptions = {};

        OpenLayers.Util.extend(fOptions, this.formatOptions);
        if (this.map && !this.projection.equals(this.map.getProjectionObject())) {
            fOptions.externalProjection = this.projection;
            fOptions.internalProjection = this.map.getProjectionObject();
        }
        this.formatObject = new this.format(fOptions);

    },

    requestSuccess: function(request) {
        var doc = request.responseXML;

        if (!doc || !doc.documentElement) {
            doc = request.responseText;
        }

        this.addFeatures(this.formatObject.read(doc));
        this.convertGeometries = false;
        this.events.triggerEvent("loadend");
    },

    getDataExtent: function() {
        var featuresBounds;
        if (this.features) {
            if (this.features[0])
                featuresBounds = viskort.kmlConvertBounds(this.features[0].geometry.getBounds().clone());
            for (var i = 1; i < this.features.length; i++)
                featuresBounds.extend(viskort.kmlConvertBounds(this.features[i].geometry.getBounds()));
        }

        return featuresBounds;
    },

    drawFeature: function(feature, style) {
    	//alert(feature.geometry.CLASS_NAME);
    	
    	if (this.convertGeometries) {
    		if (feature.geometry.CLASS_NAME == "OpenLayers.Geometry.Point") {
			feature.geometry = viskort.kmlConvertPoint(feature.geometry);
		} 
		else {
			// this transformation method apply to all geometry types 
			// (Point, and Rectangle is the only exception), 
			// since they inherits from OpenLayers.Geometry.Collection
			viskort.kmlTransformGeometry(feature.geometry);
		}
	}
        if (!this.skipDrawFeature)
            OpenLayers.Layer.GML.prototype.drawFeature.apply(this, [feature, style]);
    },
    
    CLASS_NAME: "OpenLayers.Layer.KML"
});
