/* OpenLayers */
OpenLayers.IMAGE_RELOAD_ATTEMPTS = 2;
OpenLayers.Layer.Grid.buffer = 0;
OpenLayers.Layer.Grid.prototype.buffer = 0;

/* VISORUMAT */
VisorUMAT = function() {
	var _this = this;

    this.map;
    this.overview;
	this.layerSwitcher;
	this.panel;
	this.featureInfo;
	this.queryEventHandler;
	this.full_screen;

	this.initial_zoombox = 0;
	this.initial_bounds = new Array();
	this.initial_zoomlevel;
	this.initial_operations = 0;

	// Canviar la mida dels divs per ajustar-nos a la pantalla
    this.resizeTimer = null;

    $(window).bind('resize', function() {
        if (_this.resizeTimer) clearTimeout(_this.resizeTimer);
		_this.resizeTimer = setTimeout(_this.window_resized, 250);
    });

	this.window_resized = function() {
		var borders_vertical = jQuery.browser.msie ? 0 : 0;
		var win = $(window);
		var height = win.height();
		var width = win.width();
		var capsalera = $('#capsalera');
		var contingut = $('#mapDiv');
		var div_contingut = $('#div_contingut');
		var eines_mapa = $('#div_eines_mapa');
		var peupagina = $('#peupagina');
		var content_left = $('#content_left');

		// Toolbox
		var wop = "toolbox width: " + $('#toolBox').width() + "<br/>";
		var tw = 0;
		var th = 0;
		$('#toolBox').children().each(function(i, item) {
			tw = tw + $(item).width();
			th = $(item).height();
		});
		wop += "tw: " + tw;
		var twx = Math.ceil(tw / $('#toolBox').width());
		th = th * twx;
		if (th > 0) {
			$('#toolBox').height(th);
		}

		capsalera_height = $('#capsalera').is(':visible')? capsalera.height() : 0;
		peupagina_height = $('#peupagina').is(':visible')? peupagina.height() : 0;
//		contentleft_height = $('#contentleft_width').is(':visible')? content_left.width() : 0;
//		contentleft_width = $('#contentleft_width').is(':visible')? content_left.width() : 0;
		
		var new_height;
		if ((content_left.height() + capsalera_height) < win.height()) {
			if ((content_left.height() + capsalera_height + eines_mapa.height() + borders_vertical) < win.height()) {
				new_height = win.height() - capsalera_height - peupagina_height - eines_mapa.height() - borders_vertical;
			} else {
				new_height = content_left.height() - eines_mapa.height() - borders_vertical;
			}
		} else {
			new_height = win.height() - capsalera_height - eines_mapa.height() - borders_vertical;
		}

		contingut.height(new_height);
		// sense animació perquè l'IE ho fa a sotregades
		// contingut.animate({height: new_height}, "fast")

		/* Removed
		if (_this.map) {
			var controls = _this.map.getControlsByClass('OpenLayers.Control.OptionsButton');
			for (i in controls) {
				if (controls[i].active) {
					controls[i]._options_position();
				}
			}
		}
		 */
	}

    this.init = function(conf) {
	}
    
    this.ajax_error = function(XMLHttpRequest, textStatus, errorThrown) {
		alert("No s'ha pogut recuperar les dades: " + textStatus);
		popup.setContentHTML('Error');
    }

    this.layer_toggle_visible = function(nom) {
    	var layer = _this.map.getLayersBy('code', nom)[0];
    	
    	if (layer.isBaseLayer) {
        	if (_this.map.baseLayer.name != nom) {
        		var previousBase = _this.map.baseLayer; 
        		layer.setVisibility(true);
        		_this.map.setBaseLayer(layer);
        		previousBase.setVisibility(false);
        	} else {
        		if (_this.baseDefault != undefined) {
            		var previousBase = _this.map.baseLayer; 
            		_this.baseDefault.setVisibility(true);
            		_this.map.setBaseLayer(_this.baseDefault);
            		previousBase.setVisibility(false);
        		}
        	}
    	} else {
    		layer.setVisibility( ! layer.getVisibility());
    	}
    }

    this.visibility_changed = function(event) {
    	var layer = event.object;
    	if (layer.getVisibility()) {
        	if (layer.grupVisibilitat) {
        		var gv = _this['gv_' + layer.grupVisibilitat];
        		for (var i in gv) {
        			if (gv[i] == layer.code) continue;
        			_this.map.getLayersBy('code', gv[i])[0].setVisibility(false);
        		}
        	}
        	
        	$('#layer_' + layer.code).addClass('icon_visible');
    	} else {
        	$('#layer_' + layer.code).removeClass('icon_visible');
    	}

    	layers = _this.map.getLayersBy('sourceLayer', layer.code);
    	for (i in layers) {
    		linked = layers[i];
    		linked.setVisibility(layer.getVisibility());
    	}

    	for (i in _this.map.popups) {
    		popup = _this.map.popups[i];
    		if (popup.sourceLayer == layer.code) {
	    		if (layer.getVisibility()) {
	    			popup.show();
	    		} else {
	    			popup.hide();
	    		}
	    	}
    	}

    	// Identify
    	if (layer.getVisibility() && layer.identify) {
    		$("#layerActiu").val(layer.identify);
    	}
    	
    }

    this.zoom_changed = function(event) {
    	var map = event.object;
    	for (var i in map.layers) {
    		var layer = map.layers[i];
    		if (layer.calculateInRange()) {
    			$('#layer_' + layer.code).removeClass('disabled');
    		} else {
    			$('#layer_' + layer.code).addClass('disabled');
    		}
    	}

    	for (var j in _this) {
    		if (j.substring(3,0) == "ls_") {
    			var layer = map.getLayersByName(j.substring(3))[0];
    			if (layer.calculateInRange()) {
    				for (var k in _this[j]) {
    					$('#layer_' + _this[j][k].name).removeClass('disabled');
    				}
        		} else {
    				for (var k in _this[j]) {
    					$('#layer_' + _this[j][k].name).addClass('disabled');
        			}
        		}
    		}
    	}

    }


	this.identify = function(id, x, y) {
//        pos = this.map.getLonLatFromPixel(event.xy);
		pos = new OpenLayers.LonLat(x, y);
		pixel = this.map.getPixelFromLonLat(pos);
		html = '<div class="identify_loading"></div>';
		popup = new OpenLayers.Popup.FramedCloud(
				null, pos,
	            null, html, null, true,
	            function(){ this.destroy(); }
				);
	    this.map.addPopup(popup);

	    var params = {};
    	params['id'] = id;
    	params['BBOX'] = this.map.getExtent().toBBOX();
    	params['X'] = pixel.x;
    	params['Y'] = pixel.y;
    	params['WIDTH'] = this.map.size.w;
    	params['HEIGHT'] = this.map.size.h;
    	popup._params = params;

    	$.ajax({
    		url: "visor/identify",
    		cache: false,
    		data: params,
    		dataType: "json",
    		error: function(XMLHttpRequest, textStatus, errorThrown) {
    			alert("No s'ha pogut recuperar les dades: " + textStatus);
    			popup.setContentHTML('Error');
    	    },
    	    success: function(data, textStatus){
    		if (data['error'] != undefined) {
    			alert("No s'ha pogut recuperar les dades: " + data['error']);
				popup.setContentHTML('Error');
    			return;
    		}

           	popup.setContentHTML(data['html']);
           	popup.sourceLayer = data['source_layer'];
    	}
    	});
	}

    this.seleccio = function(selector, valor, zoombox, info) {
    	var params = {};
    	params['sel'] = selector;
    	params['valor'] = valor;

    	if (zoombox != undefined) {
        	params['zoombox'] = zoombox;
    	}
    	
    	$.ajax({
    		url: "visor/seleccio",
    		cache: false,
    		data: params,
    		dataType: "json",
    		error: _this.ajax_error,
    	success:
    		function(data, textStatus){
    		if (data['error'] != undefined) {
    			alert("No s'ha pogut recuperar les dades: " + data['error']);
   	    		_this.initial_operations -= 1;
   	    		_this.initial_zoom();
    			return;
    		}

//    		alert('success: ' + data['layerName'] + ' ' + data['fieldName'] + ' - source: ' + data['sourceLayer']);

    		var bounds = new OpenLayers.Bounds(data['box']['minx'], data['box']['miny'], data['box']['maxx'], data['box']['maxy']);
    		_this.add_initial_bounds(300, bounds);
    		_this.initial_operations -= 1;
    		_this.initial_zoom();

    		var layername = "highlight_" + data['layerName'];
//    		for (i in data) {
//    			alert(i + ": " + data[i]);
//    		}
    		
    		var layer = _this.map.getLayersByName(layername)[0];
    		if (layer) {
    			_this.map.removeLayer(layer);
    		}

//    		var filter = data['layerName'] + ':' + data['fieldName'] + " = '" + data['fieldValue'] + "'";
    		var filter = data['tipus'] + ':' + data['fieldName'] + " = '" + data['fieldValue'] + "'";
    		
    		layer = new OpenLayers.Layer.WMS(layername,
                "visor/seleccio_wms?LAYERDEFS=" + filter, 
				{layers: data['layerName'], format: "image/png", transparent: "TRUE"},
				{isBaseLayer: false, visibility: false, buffer: 0});
            _this.map.addLayer(layer);

    		//layer.filter = data['fieldName'] + " LIKE '%" + data['fieldValue'] + "%'";
    		layer.filter = data['fieldName'] + " = '" + data['fieldValue'] + "'";
    		//layer.setLayerFilter(data['layerName'], layer.filter);
    		
    		if (data['sourceLayer']) {
    			layer.sourceLayer = data['sourceLayer'];
    			try {
    				var layer2 = _this.map.getLayersByName(data['sourceLayer'])[0];
    				layer2.setVisibility(true);
    			} catch (e) {}
    		}
    		layer.redraw();
    		layer.setVisibility(true);
    		
        	if (info != undefined) {
        		_this.identify(info, data['box']['minx']/2 + data['box']['maxx']/2, data['box']['miny']/2 + data['box']['maxy']/2);
        	}
    	}
    	});
    }

    this.vista = function(vista) {
    	var params = {};
    	params['vista'] = vista;

    	$.ajax({
    		url: "visor/vista",
    		cache: false,
    		data: params,
    		dataType: "json",
    		error: _this.ajax_error,
    	success:
    		function(data, textStatus){
    		if (data['error'] != undefined) {
    			alert("No s'ha pogut recuperar les dades: " + data['error']);
   	    		_this.initial_operations -= 1;
   	    		_this.initial_zoom();
    			return;
    		}

    		for (i in data['layers']) {
    			var layername = data['layers'][i]['name'];
    			var visible = data['layers'][i]['visible'];
        		var layer = _this.map.getLayersByName(layername)[0];
        		layer.setVisibility(visible == "true");
    		}

    		if (data['box'] != undefined) {
    			var bounds = new OpenLayers.Bounds(data['box']['minx'], data['box']['miny'], data['box']['maxx'], data['box']['maxy']);
    			_this.add_initial_bounds(100, bounds);
    		}
    		_this.initial_operations -= 1;
    		_this.initial_zoom();
    	}
    	});
    }

    this.add_initial_bounds = function(weight, bounds) {
    	this.initial_bounds[weight] = bounds;
    }

    this.initial_zoom = function() {
    	if (_this.initial_operations < 1) {
    		var max = 0; 
    		for (i in _this.initial_bounds) {
    			if (i > max) { max = i; }
    		}

    		var zoom_bounds = _this.initial_bounds[max];
    		if (_this.initial_zoomlevel != undefined) {
    			_this.map.setCenter(zoom_bounds.getCenterLonLat(), _this.initial_zoomlevel);
    		} else {
    			_this.map.zoomToExtent(zoom_bounds);
    		}
    	} else {
//    		alert(_this.initial_operations);
    	}
    }

	this.select_eina_pan = function() {
		panel.getControlsByClass("OpenLayers.Control.Navigation")[0].activate();
	}

    this.layerswitcher_toggle_visible = function(nom, layername) {
    	var layer = _this.map.getLayersBy('code', nom)[0];
		var ls = _this['ls_' + nom];
    	var new_layers = [];

		for (var i = ls.length - 1; i >= 0; i -= 1) {
    		if (ls[i].name == layername) {
    			ls[i].visibility = ! ls[i].visibility;
    			if (ls[i].visibility) {
    				$('#layer_' + layername).addClass('icon_visible');
        		} else {
        			$('#layer_' + layername).removeClass('icon_visible');
        		}
    		}

    		if (ls[i].visibility) {
    			for (j in ls[i].layers) {
        			new_layers.push(ls[i].layers[j]);
    			}
    		}
    	}

    	if (new_layers.length > 0) {
    		layer.params['LAYERS'] = new_layers;
    		layer.setVisibility(true);
    		layer.redraw();
    	} else {
    		layer.setVisibility(false);
    		layer.params['LAYERS'] = new_layers;
    	}
    }
};

	var previousPopup;

	function doOnHover(feature) {
		if (previousPopup != undefined) {
			map.removePopup(previousPopup);
		}

		html = feature.attributes.name + "<br/>" + (feature.attributes.total ? feature.attributes.total : "");
		var popup = new OpenLayers.Popup.FramedCloud(
                        "chicken", 
						feature.geometry.bounds.getCenterLonLat(),
                        null,
                        html,
                        null,
                        true);
		map.addPopup(popup);
		previousPopup = popup;
	}

