/* Copyright (c) 2006-2007 MetaCarta, Inc., published under a modified BSD license.
 * See http://svn.openlayers.org/trunk/openlayers/repository-license.txt
 * for the full text of the license. */


/**
 * @requires OpenLayers/Tile.js
 *
 * Class: OpenLayers.Tile.WFS2
 * Instances of OpenLayers.Tile.WFS2 are used to manage the image tiles
 * used by various layers.  Create a new image tile with the
 * <OpenLayers.Tile.WFS2> constructor.
 *
 * Inherits from:
 *  - <OpenLayers.Tile>
 */
/**
    * Method: requestSuccess
    * Called on return from request succcess. Adds results via
    * layer.addFeatures in vector mode, addResults otherwise.
    *
    * Parameters:
    * request - {XMLHttpRequest}
    */

OpenLayers.Tile.WFS.prototype.requestSuccess = function(request) {
        var text = request.responseText;
//        alert(text);

        var lines = text.split('\n');
        var columns;
        // length - 1 to allow for trailing new line
        for (var lcv = 0; lcv < (lines.length - 1); lcv++) {
            var currLine = lines[lcv].replace(/^\s*/,'').replace(/\s*$/,'');

            if (currLine.charAt(0) != '#') { /* not a comment */

               	//alert(currLine);
                if (!columns) {
                    //First line is columns
                    columns = currLine.split('\t');
                } else {
                    var vals = currLine.split('\t');
                    var location = new OpenLayers.LonLat(0,0);
                    var title; var url;
                    var description, icon, iconSize, iconOffset, overflow;
                    iconSize = new OpenLayers.Size(16,16);
                    var set = false;
                    for (var valIndex = 0; valIndex < vals.length; valIndex++) {
                        if (vals[valIndex]) {
                            if (columns[valIndex] == 'point') {
                                var coords = vals[valIndex].split(',');
                                location.lon = parseFloat(coords[0]);
                                location.lat = parseFloat(coords[1]);
                                set = true;
                            } else if (columns[valIndex] == 'lat') {
                                location.lat = parseFloat(vals[valIndex]);
                                set = true;
                            } else if (columns[valIndex] == 'lon') {
                                location.lon = parseFloat(vals[valIndex]);
                                set = true;
                            } else if (columns[valIndex] == 'title')
                                title = vals[valIndex];
                            else if (columns[valIndex] == 'image' ||
                                     columns[valIndex] == 'icon')
                                url = vals[valIndex];
                            else if (columns[valIndex] == 'iconSize') {
                                var size = vals[valIndex].split(',');
                                iconSize = new OpenLayers.Size(parseFloat(size[0]),
                                                           parseFloat(size[1]));
                            } else if (columns[valIndex] == 'iconOffset') {
                                var offset = vals[valIndex].split(',');
                                iconOffset = new OpenLayers.Pixel(parseFloat(offset[0]),
                                                           parseFloat(offset[1]));
                            } else if (columns[valIndex] == 'title') {
                                title = vals[valIndex];
                            } else if (columns[valIndex] == 'description') {
                                description = vals[valIndex];
                            } else if (columns[valIndex] == 'overflow') {
                                overflow = vals[valIndex];
                            }
                        }
                    }
                    if (set) {
                      var data = {};
                      if (url != null) {
                          data.icon = new OpenLayers.Icon(url,
                                                          iconSize,
                                                          iconOffset);
                      } else {
                          data.icon = OpenLayers.Marker.defaultIcon();

                          //allows for the case where the image url is not
                          // specified but the size is. use a default icon
                          // but change the size
                          if (iconSize != null) {
                              data.icon.setSize(iconSize);
                          }

                      }
					  //data.icon.setOpacity(0.7);
                      if ((title != null) || (description != null)) {
						  data['popupSize'] = new OpenLayers.Size(200,30);
                      	  var content = '<p id="id_title_' + location.lon + location.lat + '">';
                      	  if (title != null)
	                          content = content + '<b>'+title+'</b>';
                          content += '</p>';
                      	  content += '<p id="id_descr_' + location.lon + location.lat + '">';
                      	  if (description != null) {
	                          content = content + description;
                          }
                          content += '</p>';
		                  content = content.replace( /\n/g, '<br>');
                          data['popupContentHTML'] = content;
                      }

                      //data['overflow'] = "auto";
                      //data['height'] = 160;
                      //data['closeBox'] = true;

                      // We must track both features and markers so they can be properly deallocated later

		            var feature = new OpenLayers.Feature(this, location);
		            feature.closeBox = true;
		            feature.popupClass = AutoSizeFramedCloudMaxSize;
		            feature.data.popupContentHTML = content;
		            //feature.data.overflow = "visible";
		            feature.data.overflow = "auto";
		            feature.data.icon = data.icon;
		            this.features.push(feature);
		            var marker = feature.createMarker();

/*                      var feature = new OpenLayers.Feature(this, location, data);
                      this.features.push(feature);
					  feature.popupClass = AutoSizeFramedCloudMaxSize;
			          feature.closeBox = true;
                      var marker = feature.createMarker();   */
                      if ((title != null) || (description != null)) {
                        marker.events.register('mouseover', feature, this.markerOver);
                        marker.events.register('mouseout', feature, this.markerOut);
                        marker.events.register('click', feature, this.markerClick);
                      }
                      this.layer.addMarker(marker);

                    }
                }
            }
        }
        if (this.events) {
            this.events.triggerEvent("loadend");
        }
    };
    /**
     * Property: markerOver
     *
     * Parameters:
     * evt - {Event}
     */
   OpenLayers.Tile.WFS.prototype.markerOver = function(evt) {
		if (this.popup == null) {
			this.popup = this.createPopup(true);
			map.addPopup(this.popup);
		}
		this.popup.id='info_over';
		this.popup.closeBox=false;
		this.popup.show();
        OpenLayers.Event.stop(evt);
    };

    /**
     * Property: markerOut
     *
     * Parameters:
     * evt - {Event}
     */
   OpenLayers.Tile.WFS.prototype.markerOut = function(evt) {
		if (this.popup != null && this.popup.id!='info_click') {
			this.popup.hide();
		}
        OpenLayers.Event.stop(evt);
    };

    /**
     * Property: markerClick
     *
     * Parameters:
     * evt - {Event}
     */
   OpenLayers.Tile.WFS.prototype.markerClick = function(evt) {
		if (this.popup == null) {
			this.popup = this.createPopup(true);
			map.addPopup(this.popup);
		}
		this.popup.id='info_click';
		this.popup.closeBox=true;
		this.popup.show();
        OpenLayers.Event.stop(evt);
    };

    /**
     * Method: destroyAllFeatures
     * Iterate through and call destroy() on each feature, removing it from
     *   the local array
     */
    OpenLayers.Tile.WFS.prototype.destroyAllFeatures = function() {
        while(this.features.length > 0) {
            var feature = this.features.shift();
// This is the important change ------------
            if( feature.marker != null && this.layer != null)
                      this.layer.removeMarker(feature.marker);
//------------------------------------------
            feature.destroy();
        }
    };


    /**
     * Method: draw
     * Check that a tile should be drawn, and load features for it.
     */
    OpenLayers.Tile.WFS.prototype.draw = function() {
    	//alert('this.layer.singleTile: '+this.layer.singleTile);
// This is the important change ------------
        if( !this.layer.singleTile )
        {
            this.url = this.layer.getURL(this.bounds);
//        	alert(this.url);
        }
//------------------------------------------
        if (OpenLayers.Tile.prototype.draw.apply(this, arguments)) {
            if (this.isLoading) {
                //if already loading, send 'reload' instead of 'loadstart'.
                this.events.triggerEvent("reload");
            } else {
                this.isLoading = true;
                this.events.triggerEvent("loadstart");
            }
        	//alert(this.url);
            this.loadFeaturesForRegion(this.requestSuccess);
        }
// This is a change--------------------------------
        this.drawn = true;
        return true;
//-------------------------------------------------
    };