/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


(function($, undefined) {


	$.widget("gcTool.mapPrint", $.ui.gcTool, {

		widgetEventPrefix: "mapPrint",

		options: {
			label: OpenLayers.i18n('Print'),
			icons: {
				primary: 'print' // TODO: choose better name
			},
			text: false,
			printFile: 'print.php',
			printFileUrl: null,
			gisclient: null
		},

		_create: function() {
			var self = this;
			var mapOptions = gisclient.getMapOptions();

			$.ui.gcTool.prototype._create.apply(self, arguments);
			
			var container = '<div id="print_dialog"></div>';
			$('body').append(container);
			//LANG
			var html = 
			'<div class="print_settings"><fieldset>' +
			'	<legend>'+OpenLayers.i18n('Print information')+':</legend>' +
			'	<div class="noflow"><label>'+OpenLayers.i18n('Text')+':</label> <textarea name="text">'+gisclient.getMapTitle()+'</textarea></div>' +
			'	<div class="noflow"><label>'+OpenLayers.i18n('Scale')+':</label> <div class="radio_container"><input class="radio" type="radio" name="scale_mode" id="scale_mode_auto" value="auto" checked><label for="scale_mode_auto">'+OpenLayers.i18n('Auto')+'</label><br /> <input class="radio" type="radio" name="scale_mode" id="scale_mode_user" value="user"><label for="scale_mode_user">1: </label><input type="text" name="scale" style="width:70px;" disabled="disabled"></div></div>';
			if(mapOptions.legend) {
				html += '<div class="noflow"><label>'+OpenLayers.i18n('Legend')+':</label> <div class="radio_container"><input class="radio" type="radio" name="legend" id="legend_yes" value="yes" checked><label for="legend_yes">'+OpenLayers.i18n('Yes')+'</label> <input class="radio" type="radio" name="legend" id="legend_no" value="no"><label for="legend_no">'+OpenLayers.i18n('No')+'</label></div></div>';
			}
			html += 
			'	<div class="noflow"><label>'+OpenLayers.i18n('Date')+':</label> <input type="text" name="date" style="width:82px;"></div>' + 
			'</fieldset>' +
			'<fieldset>' +
			'	<legend>'+OpenLayers.i18n('Print properties')+':</legend>' +
			'	<div class="noflow"><label>'+OpenLayers.i18n('Print layout')+':</label> <div class="radio_container"><input class="radio" type="radio" name="direction" id="direction_v" value="vertical" checked><label for="direction_v">'+OpenLayers.i18n('Vertical')+'</label> <input class="radio" type="radio" name="direction" id="direction_h" value="horizontal" ><label for="direction_h">'+OpenLayers.i18n('Horizontal')+'</label></div></div>' +
			'	<div class="noflow"><label>'+OpenLayers.i18n('Print format')+':</label> <div class="radio_container"><select name="formato"><option value="A0">A0</option><option value="A1">A1</option><option value="A2">A2</option><option value="A3">A3</option><option value="A4" selected>A4</option></select></div></div>' +
			'	<div class="noflow"><label>'+OpenLayers.i18n('Format')+':</label> <div class="radio_container"><input class="radio" type="radio" name="format" id="format_HTML" value="HTML" checked><label for="format_HTML">HTML</label> <input class="radio" type="radio" name="format" id="format_PDF" value="PDF"><label for="format_PDF">PDF</label></div>'+
			'	</div>' +
			'</fieldset>' +
			'<div class="buttons"><button name="print">'+OpenLayers.i18n('Print')+'</button> <button name="close">'+OpenLayers.i18n('Close')+'</button></div></div>'+
			//restart
			'<div class="print_loading" style="display:none;"><img src="'+OpenLayers.ImgPath+'ajax-loader.gif"></div>'+
			'<div class="print_results" style="display:none;">'+
			'	<span name="result"></span>'+
			'	<div class="buttons"><button name="restart">'+OpenLayers.i18n('Restart')+'</button> <button name="close">'+OpenLayers.i18n('Close')+'</button></div>'+
			'</div>';
			
			$('#print_dialog').html(html);
			$('#print_dialog').dialog({
				draggable:true,
				title:OpenLayers.i18n('Print settings'),//LANG
				autoOpen: false
			});
			
			$('#print_dialog button[name="restart"]').click(function() {
				self._click();
			});
			$('#print_dialog button[name="print"]').click(function() {
				self._printRequest();
			});
			$('#print_dialog button[name="close"]').click(function() {
				$('#print_dialog').dialog('close')
			});
			$('#print_dialog input[name="scale_mode"]').click(function() {
				var mode = $('#print_dialog input[name="scale_mode"]:checked').val();
				if(mode == 'auto') {
					$('#print_dialog input[name="scale"]').attr('disabled', 'disabled');
				} else {
					$('#print_dialog input[name="scale"]').removeAttr('disabled');
				}
			});
			
			self.options.printFileUrl = gisclient.options.applicationRootUrl + self.options.printFile;
		},
		
		_click: function() {
			$('#print_dialog div.print_results').hide();
			$('#print_dialog div.print_loading').hide();
			$('#print_dialog div.print_settings').show();
			if(!$('#print_dialog').dialog('isOpen')) $('#print_dialog').dialog('open');
			var scale = gisclient.componentObjects.scaleDropDown.getCurrentScale();
			$('#print_dialog input[name="scale"]').val(scale);
			var time = new Date();
			var date = time.getUTCDate()+'/'+(time.getUTCMonth()+1)+'/'+time.getUTCFullYear();
			$('#print_dialog input[name="date"]').val(date);
		},
		
		_deactivate: function() {
			if($('#print_dialog').dialog('isOpen')) $('#print_dialog').dialog('close');
		},
		
		_printRequest: function() {
			var self = this;
			var map = gisclient.map;
			
			$('#print_dialog div.print_results').hide();
			$('#print_dialog div.print_loading').show();
			$('#print_dialog div.print_settings').hide();
			
			var size  = map.getCurrentSize();
			var tiles = [];
			var vectors = {};
			$.each(map.layers, function(layername, layer) {
				if (!layer.getVisibility()) return;
				if (!layer.calculateInRange()) return;
				if(layer.CLASS_NAME == 'OpenLayers.Layer.Vector' && layer.features.length > 0) {
					//vectors[layer.name] = self._getFeatures(layer); not implemented
					return;
				} else {
					for (tilerow in layer.grid) {
						for (tilei in layer.grid[tilerow]) {
							var tile     = layer.grid[tilerow][tilei]
							var url      = layer.getURL(tile.bounds);
							var position = tile.position;
							var opacity  = layer.opacity ? parseInt(100*layer.opacity) : 100;
							tiles[tiles.length] = {url:url, x:position.x, y:position.y, opacity:opacity};
						}
					}
				}
			});

			var mapOptions = gisclient.getMapOptions();
			if(mapOptions.legend) {
				var gcLayersManager = gisclient.componentObjects.gcLayersManager;
				var printLegend = {mapsetUrl:gisclient.options.mapsetURL,themes:[]};
				var themes = gcLayersManager.getThemes();
				$.each(themes, function(themeId, theme) {
				//$.each(gisclient.options.mapsetData.theme, function(themeId, theme) {
					var themeObj = {title:theme.title, id:themeId, groups:[]};
					$.each(gcLayersManager.getLayers(themeId), function(groupId, group) {
					//$.each(gisclient._grepLayersFromTheme(theme), function(groupId, group) {
						if(typeof(group.legend) == 'undefined') return;
						var groupObj = {title:group.title, id:groupId, map:themeId, project:gisclient.getProject(), layers:[]};
						var url = mapOptions.mapsetURL+'legend/'+gisclient.getProject()+'/'+themeId+'-'+groupId+'.png';
						$.each(group.legend, function(e, layerName) {
							var legendObj = {url:url, title:layerName.class_title};
							groupObj.layers.push(legendObj);
						});
						themeObj.groups.push(groupObj);
					});
					printLegend.themes.push(themeObj);
				});
			}

			var bounds = map.calculateBounds();
			var topLeft = new OpenLayers.Geometry.Point(bounds.top, bounds.left);
			var topRight = new OpenLayers.Geometry.Point(bounds.top, bounds.right);
			var distance = topLeft.distanceTo(topRight);
			
			var center = map.getCenter();
			
			var params = {
				viewport_size: [size.w, size.h],
				center: [center.lon, center.lat],
				format: $('#print_dialog input[name="format"]:checked').val(),
				printFormat: $('#print_dialog select[name="formato"]').val(),
				direction: $('#print_dialog input[name="direction"]:checked').val(),
				scale_mode: $('#print_dialog input[name="scale_mode"]:checked').val(),
				scale: $('#print_dialog input[name="scale"]').val(),
				current_scale: gisclient.componentObjects.scaleDropDown.getCurrentScale(),
				text: $('#print_dialog input[name="text"]').val(),
				extent: map.calculateBounds().toBBOX(),
				date: $('#print_dialog input[name="date"]').val(),
				dpi: mapOptions.dpi,
				srid: gisclient.getProjection(),
				pixels_distance: size.w/distance,
				vectors: JSON.stringify(vectors),
				tiles: JSON.stringify(tiles)
			};
			if(mapOptions.legend && $('#print_dialog input[name="legend"]:checked').val() == 'yes') {
				params.legend = JSON.stringify(printLegend);
			}
			
			$.ajax({
				url: self.options.printFileUrl,
				type: 'POST',
				data: params,
				dataType: 'json',
				success: self._success,
				error: function() {
					$('#print_dialog div.print_loading').hide();
                    $('#print_dialog hr').next().remove();
					$('#print_dialog div.print_results span[name="result"]').html(OpenLayers.i18n('Error'));
					$('#print_dialog div.print_results').show();
				}
			});
		},
		
		_success: function(data) {
			$('#print_dialog div.print_loading').hide();
			if(typeof(data.result) != 'undefined' && data.result == 'ok') {
                $('#print_dialog hr').next().remove();
				var link = '<a href="'+data.file+'" target="_blank" rel="file">';
				if(data.format == 'HTML') {
					link += OpenLayers.i18n('View print file');
				} else if(data.format == 'PDF') {
					link += OpenLayers.i18n('Download print file');
				}
				link += '</a>';
				$('#print_dialog div.print_results span[name="result"]').html(link);
				$('#print_dialog div.print_results').show();
			} else {
                $('#print_dialog hr').next().remove();
				$('#print_dialog div.print_results span[name="result"]').html(OpenLayers.i18n('Error'));
				$('#print_dialog div.print_results').show();
			}
		},
		
		_getFeatures: function(layer) {
			var self = this;
			var map = gisclient.map;

			var vectors = [];
			$.each(layer.features, function(e, feature) {
				var renderIntent = feature.renderIntent;
                /* REMOVED: 25/05/2011
				if(feature.style !== null) {
					// get style from feature
				} else {
					// get style from layer
				}
                */
				var vector = {
					geometry:feature.geometry.toString()
				};
				if(typeof(feature.attributes.redline) != 'undefined' && feature.attributes.redline == 1) {
					vector.text = feature.attributes.text;
				}
				vectors.push(vector);
			});
			return vectors;
		}

	});

	$.extend($.gcTool.mapPrint, {
		version: "3.0.0"
	});
})(jQuery);

