//declare custom layer to talk to mergeAndOutput.*
//request JSON
// {
//   url: <String>,
//   format: <String, jpg/png>,
//   opacity: <Number, 0 - 1>,
//   layers: <String, show:[layerIds], optional>,
//   layerDefs: <String, id1:def1;id2:def2;...>
// }
//response JSON is same as http://resources.esri.com/help/9.3/ArcGISServer/apis/REST/export.html
//scale property not returned
dojo.declare("my.PrintableLayer", esri.layers.DynamicMapServiceLayer, {
	//constructor for layer with custom required option: layers, extent
	constructor: function(url, options) {
		this.layers = options.layers;
		this.initialExtent = this.fullExtent = options.extent;
		this.spatialReference = this.initialExtent.spatialReference;

		this.loaded = true;
		this.onLoad(this);
	},

	//call mergeAndOutput.*, pass request JSON.
	//process response JSON and return image url
	getImageUrl: function(extent, width, height, callback) {
		try {

			var layersJson = [], layerJson;

			dojo.forEach(this.layers, function(layer) {
				if (layer.visible) {
					layerJson = { url: layer.url, format: (layersJson.length == 0 ? "jpg" : "png"), opacity: layer.opacity };

					if (layer.layers) {
						layerJson.layers = "show:" + layer.layers.join(",");
					}
					if (layer.layerDefs) {
						var defs = [];
						dojo.forEach(layer.layerDefs, function(def, index) {
							if (def) {
								defs.push(index + ":" + def);
							}
						});
						layerJson.layerDefs = defs.join(";");
					}
					layersJson.push(dojo.toJson(layerJson));
				}
			});

			//request JSON
			var json = {
				width: map.width,
				height: map.height,
				extent: dojo.toJson(extent.toJson()),
				layers: layersJson
			};

			//send request to mergeAndOutput.php, force proxy use
			esri.request({
				url: this.url,
				postData: dojo.toJson(json),
				handleAs: "json",
				load: function(response, io) {
					//on load, call callback and pass image url
					callback(response.href);
				},
				error: this.onError
			}, true);
		}
		catch (err) {
			this.onError(err);
		}
	}
});
