/******************************************************************************
 *                                                                            *
 *  Copyright (C) 2008-2010 Alexander Barth <barth.alexander@gmail.com>.      *
 *                                                                            *
 *  This program is free software: you can redistribute it and/or modify      *
 *  it under the terms of the GNU Affero General Public License as published  *
 *  by the Free Software Foundation, either version 3 of the License, or      *
 *  (at your option) any later version.                                       *
 *                                                                            *
 *  This program is distributed in the hope that it will be useful,           *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 *  GNU Affero General Public License for more details.                       *
 *                                                                            *
 *  You should have received a copy of the GNU Affero General Public License  *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.     *
 *                                                                            *
 ******************************************************************************/

// making this a global variable so that it is accessible for
// debugging/inspecting in Firebug

var wms_url = "Python/web/wms";

/*
var baselayer_url = 'http://labs.metacarta.com/wms/vmap0?';
var baselayer_name = 'basic';
var baselayer_format = 'image/jpeg';
*/

var baselayer_url = 'Python/web/continents?';
var baselayer_name = 'cont';
var baselayer_format = 'image/png';

var Layer = null; 
var dinputs = new Util.DocumentInputs();

var cap = null;
var vsection = null;
var hsection = null;
var chooseServer;

//var WMS_PROXY = 'http://localhost:8081/Python/web/bluemarble';
var WMS_PROXY = 'Python/web/bluemarble';


function preload_images() {
    var list = ["img/folder.png",
		"img/folder-open.png",
		"img/dataset.png",
		"img/dataset_current.png",
		"img/mini_colormap_gray.png",
		"img/mini_colormap_hsv.png",
		"img/mini_colormap_jet.png",
		"img/mini_colormap_Paired.png",
		"img/mini_colormap_RdBu.png"
		];

    for (var i=0; i<list.length; i++) {
	var img = new Image();
	img.src = list[i];
    }
}




function add_layer(Layer) {
    var j;
    var option;

    dinputs.enable();    

    hsection.addLayer(Layer);
    vsection.addLayer(Layer);

    // show a horizontal plot for default time and depth

    //var $tabs = $("#tab").tabs();
    //$tabs.tabs('select', 0);

    // layer changed
    hsection.update();
}


function remove_layer(Layer) {
    hsection.removeLayer(Layer);
    vsection.removeLayer(Layer);
}



//Creation of a custom panel with a ZoomBox control with the alwaysZoom option sets to true				
// from http://openlayers.org/dev/examples/navtoolbar-alwaysZoom.html


OpenLayers.Control.myWMSGetFeatureInfo = OpenLayers.Class(OpenLayers.Control, {
	title: 'Identify features by clicking',

	initialize: function(section,options) {
	    this.section = section;
	    options = options || {};
	    options.handlerOptions = options.handlerOptions || {};

	    OpenLayers.Control.prototype.initialize.apply(this, [options]);

	    var callbacks = {};
	    callbacks["click"] = this.getInfoForClick;
	    this.handler = new OpenLayers.Handler.Click(this, {click: this.getInfoForClick}, 
							this.handlerOptions.click || {});
	},

	activate: function () {
	    if (!this.active) {
		this.handler.activate();
	    }
	    return OpenLayers.Control.prototype.activate.apply(this, arguments);
	},

	deactivate: function () {
	    return OpenLayers.Control.prototype.deactivate.apply(this, arguments);
	},

	getInfoForClick: function(e) {
	    var obj = this.section;

	    console.log('obj',obj);
	    
	    for (var id in obj.analysis_wms) {			
		console.log('layer info',id);
		//obj.figprops[id].set_info('Loading...');
		// formats that we understand
		var preferred_info_formats = ['application/vnd.ogc.gml','text/xml'];
		var info_format = obj.Layers[id].infoFormat(preferred_info_formats);

		var url = obj.analysis_wms[id].getFullRequestString({
			REQUEST: "GetFeatureInfo",
			EXCEPTIONS: "application/vnd.ogc.se_xml",
			BBOX: obj.analysis_wms[id].map.getExtent().toBBOX(),
			X: e.xy.x,
			Y: e.xy.y,
			INFO_FORMAT: info_format,
			QUERY_layers: obj.analysis_wms[id].params.LAYERS,
			WIDTH: obj.analysis_wms[id].map.size.w,
			HEIGHT: obj.analysis_wms[id].map.size.h});

		// closure on id
		var callback = function(id,map,latlon) {
		    return function(resp) {
			obj.show_feature_info(resp,id,latlon,info_format);


		    };						      
		}(id,obj.map,obj.map.getLonLatFromPixel(e.xy),info_format);

		Util.proxy_ajax(url,{},null,callback,{proxy: obj.Layers[id].use_proxy});

	    }
	    
	},

	CLASS_NAME: "OpenLayers.Control.WMSGetFeatureInfo"
});



OpenLayers.Control.CustomNavToolbar = OpenLayers.Class(OpenLayers.Control.Panel, {	
	/**
	 * Constructor: OpenLayers.Control.NavToolbar 
	 * Add our two mousedefaults controls.
	 *
	 * Parameters:
	 * options - {Object} An optional object whose properties will be used
	 *     to extend the control.
	 */
					
					
	initialize: function(section,options) {
	    OpenLayers.Control.Panel.prototype.initialize.apply(this, [options]);
	    this.addControls([
			      new OpenLayers.Control.Navigation(),
			      //Here it come
			      new OpenLayers.Control.ZoomBox({alwaysZoom:true, autoActivate: false}),
			      
			      new OpenLayers.Control.myWMSGetFeatureInfo(section,{autoActivate: false})

			      ]);
	    // To make the custom navtoolbar use the regular navtoolbar style
	    this.displayClass = 'olControlNavToolbar';
	},
					
					
				
	/**
	 * Method: draw 
	 * calls the default draw, and then activates mouse defaults.
	 */
	draw: function() {
	    var div = OpenLayers.Control.Panel.prototype.draw.apply(this, arguments);
	    this.controls[0].activate();
	    return div;
	}
    });
				




function init() {
    var i,
	server, 
	ncap,
	// get query parameters
	query = new Util.query(window.location.search.substring(1)),
	extra_param = {};

    // set section
    server = query.get("server",wms_url);

    // additional parameter passed to getCapabilities request
    

    if (query.has("basedir")) {
        extra_param.basedir = query.get("basedir");
    }


    preload_images();
    hsection = new HorizontalSection();
    vsection = new VerticalSection();

    /*    $("#horizontal_selection").show();
	  $("#vertical_selection").hide();*/


    // load default server
    cap = new OceanBrowser.UI.LayerTree("chooser",server,
					{show_title: true
					});

    cap.events.register('layerSelected', null, add_layer);
    cap.events.register('layerDeselected', null, remove_layer);

    cap.events.register('loaded', null, function() {
	    // debugging
	    /*
	    var li = new OceanBrowser.UI.InfoLayer('toto',cap.layer_infos[4]);
	    li.open();	    
	    */
	    //add_layer(cap.layer_infos[4]);
	});

    cap.load();


    // load servers with 'autoload'

    for (i=0; i < SERVERS.length; i++) {
	if (SERVERS[i].autoload) {
	    console.log(SERVERS[i].name);

	    server = SERVERS[i];
	    ncap = new OceanBrowser.UI.LayerTree("chooser",
						 server.url,
						 {use_proxy: WMS_PROXY,
						  version: server.version,
						  WMS_extensions: server.extension,
						  show_title: true
						 });

	    ncap.events.register('layerSelected', null, add_layer);
	    ncap.events.register('layerDeselected', null, remove_layer);
	    ncap.load();
	}
    }

    // set OpenLayers proxy
    OpenLayers.ProxyHost= "/cgi-bin/proxy.cgi?url=";



    var $tabs = $("#tab").tabs();

    $('#tab').bind('tabsselect', function(event, ui) {
	    if (ui.index === 0) {
		// horizontal section tab

		document.getElementById("button_update").onclick = function() { hsection.update(); };
	    }
	    else {
		// vertical section tab
		
		document.getElementById("button_update").onclick = function() { vsection.update_all(); };
		vsection.onvisible();
	    }

	});

    $tabs.tabs('select', 0);
    document.getElementById("button_update").onclick = function() { hsection.update(); };

    document.getElementById("button_help").onclick    = function () {
	window.open('http://modb.oce.ulg.ac.be/mediawiki/index.php/OceanBrowser','mywindow'); 
    };

    
    //$tabs.tabs('select', 1);

    //console.log('range ',wms_range('2007-12-01/2008-03-20/P1D','ISO8601'));


    // jQuery UI dialogs

    // dinputs.disable();

    $("#about_dialog").dialog({ autoOpen: false, width: 500});
    $("#metadata_dialog").dialog({ autoOpen: false, width: 500});
    $("#settings_dialog").dialog({ autoOpen: false, width: 500});

    // dialog for adding a server

    chooseServer = new OceanBrowser.UI.chooseServer('test',SERVERS);
    chooseServer.events.register('serverSelected',null, function(server) { 
	    var ncap = new OceanBrowser.UI.LayerTree("chooser",
						     server.url,
						     {use_proxy: WMS_PROXY,
						      version: server.version,
						      WMS_extensions: server.extension,
						      show_title: true
						     });

	    ncap.events.register('layerSelected', null, add_layer);
	    ncap.events.register('layerDeselected', null, remove_layer);
	    ncap.load();
	});

    $('#add_server_button').click(function() { chooseServer.open(); });
    $('#button_about').click(function() { $("#about_dialog").dialog('open'); });
    $('#button_settings').click(function() { $("#settings_dialog").dialog('open'); });




    // debugging

    //chooseServer.events.triggerEvent('serverSelected',SERVERS[6]);
    //chooseServer.events.triggerEvent('serverSelected',SERVERS[10]);
    
}







