﻿/* 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,

    clientKml: null,

    skipDrawFeature: false,

    initialize: function(name, url, options, internalprojection, clientKml) {
        var newArguments = [];
        newArguments.push(name, url, options);
        OpenLayers.Layer.GML.prototype.initialize.apply(this, newArguments);

        this.clientKml = clientKml;

        this.format = OpenLayers.Format.AdvancedKML;

        var fOptions = {};

        OpenLayers.Util.extend(fOptions, this.formatOptions);
        if (options.projection && options.projection != internalprojection) {
            fOptions.externalProjection = new OpenLayers.Projection(options.projection);
            fOptions.internalProjection = new OpenLayers.Projection(internalprojection);
        }

        // TEST TEST TEST
        //fOptions.externalProjection = new OpenLayers.Projection("EPSG:4326");
        //fOptions.internalProjection = new OpenLayers.Projection("EPSG:25832");

        this.formatObject = new this.format(fOptions);

    },

    loadGML: function() {
        if (!this.loaded) {
            if (this.clientKml) {
                this.loaded = true;
                this.readDoc(this.clientKml);
            }
            else {
                var results = OpenLayers.loadURL(this.url, null, this, this.requestSuccess, this.requestFailure);
                this.loaded = true;
            }
        }
    },

    requestSuccess: function(request) {
        var doc = request.responseXML;

        if (!doc || !doc.documentElement) {
            doc = request.responseText;
        }

        this.readDoc(doc);
    },

    readDoc: function(doc) {
        var readdoc = this.formatObject.read(doc);
        this.addFeatures(readdoc);
        this.events.triggerEvent("loadend");
    },

    getDataExtent: function() {
        var featuresBounds;
        if (this.features) {
            if (this.features[0])
                featuresBounds = this.features[0].geometry.getBounds().clone();
            for (var i = 1; i < this.features.length; i++)
                featuresBounds.extend(this.features[i].geometry.getBounds());
        }
        return featuresBounds;
    },

    drawFeature: function(feature, style) {
        if (!this.skipDrawFeature) {
            OpenLayers.Layer.GML.prototype.drawFeature.apply(this, [feature, style]);
        }
    },

    CLASS_NAME: "OpenLayers.Layer.KML"
});
