var _MAP_WRAPPER = new Map_Wrapper();
var _LIST_OF_EXTRA_GRAPHICS = new Array(new Extra_Graphics());
var _OP_USER= new Idle();
var _WIN=null;
var _IMAGES_TO_LOAD=0;
var _jg= null;
var _jg2=null;
var _ESC_KEY_LISTENER=null;
var _CTRL_KEY_DOWN=false;
var _ENTER_KEY_LISTENER=null;
var _SHIFT_KEY_LISTENER=null;
var _DELETE_KEY_LISTENER=null;
var _EVENTS_DRAWING_ENGINE=0;
var _SELECTION_DRAWING_ENGINE=1;
var _ALL_DRAWING_ENGINES=2;
var _SHOW_COORDINATES = true;

function startup()
{
    try{
        
        loading_message(true);
        var params="type=layers&action=load";
        document.getElementById("map_frame").src=_UI_MAP+"?"+params;

        document.onclick=evt_onclick_document;
        
        if(document.addEventListener)
        {
            document.getElementById( _MAP_ID ).addEventListener("mousedown",evt_event_zoomin,false);
            document.getElementById( _MAP_ID ).addEventListener("mousemove",mappa_mouse_over,false);
        }
        else
        {
            document.getElementById( _MAP_ID ).onmousedown=evt_event_zoomin;
            document.getElementById( _MAP_ID ).onmousemove=mappa_mouse_over;
        }
		
        _EVENT_LISTENER=evt_event_zoomin;

        //Keyboard events
        _ESC_KEY_LISTENER=remove_popup;
        if(document.removeEventListener){
            document.removeEventListener("keyup",process_key_pressed,false);
            document.removeEventListener("keydown",process_key_down,false);

        }
        else
        {
            document.onkeyup=null;

            if(document.attachEvent)
                document.releaseCapture();
        }

        if ( document.addEventListener ){
            document.addEventListener("keyup", process_key_pressed, false);
            document.addEventListener("keydown", process_key_down, false);

        }else if ( document.attachEvent ){
            document.attachEvent("onkeyup", process_key_pressed);
            document.attachEvent("onkeydown", process_key_down);

        }else{
            document.onkeyup = process_key_pressed;
            document.onkeydown = process_key_down;

        }

    }catch(e)
    {
        alert("Eventsmanager.startup(): "+e)
    }
}
function evt_onclick_document(event) {
    remove_popup();
}
function process_key_pressed(event) {
    if(!event)
        event=window.event;
    if(event.keyCode == 27){
        if(_ESC_KEY_LISTENER){
            _ESC_KEY_LISTENER.call();
        }
    }else if(event.keyCode == 13){
        if(_ENTER_KEY_LISTENER){
            _ENTER_KEY_LISTENER.call();
        }
    }else if(event.keyCode == 17){
        _CTRL_KEY_DOWN = false;
    }else if(event.keyCode == 16){
        if(_SHIFT_KEY_LISTENER){
            _SHIFT_KEY_LISTENER.call();
        }
    }else if(event.keyCode == 46){
        if(_DELETE_KEY_LISTENER){
            _DELETE_KEY_LISTENER.call();
        }
    }
}
function process_key_down(event) {
    if(!event)
        event=window.event;
    if(event.keyCode == 17){
        _CTRL_KEY_DOWN = true;
    }
}

function evt_menu_mouse_over(element) {
    element.className="menu_mouse_over";

}
function evt_menu_mouse_out(element) {
    element.className="menu_mouse_out";
}

function change_selected_tool(active){
    var array = new Array("pan","zoomin","zoomout","query","planimetry","select","save","measure","capture_point",
        "capture_line", "new_vertex","delete_vertex","move_vertex","split_feature","add_ring","add_island","copy",
        "cut","paste","move_feature","set_scale");
    for(var i=0; i< array.length; i++){
        if(document.getElementById(array[i])){
            document.getElementById(array[i]).className="";
        }
    }
    if(active){
        active.className = "tool_selected";
    }

}
function evt_event_zoom_to_scale(event)
{
    process_mouse_down(event,new Zoom_To_Scale());
}
function evt_but_popup_rotate_map(event)
{
    try{
        if( !event )
            event = window.event;
        var popup = new Popup_Menu_Rotate(this);
        popup.show(event.clientX,event.clientY);
		
    }catch(e)
    {
        alert("Eventsmanager.evt_but_popup_rotate_map(): "+e);
        return false;
    }
}

function evt_event_move(event)
{
    process_mouse_down(event,new Move());
}
function evt_event_zoomin(event)
{
    process_mouse_down(event,new Zoomin());	
}
function evt_event_query_parcel(event)
{
    process_mouse_down(event,new Query_Parcel());
}
function evt_event_zoomout(event)
{
    process_mouse_down(event,new Zoomout());
}

function evt_event_measure(event)
{
    process_mouse_down(event,new Evt_Draw_Circle());
}
function evt_event_planimetry(event)
{
    process_mouse_down(event,new Planimetry());
}
function mappa_mouse_over(event)
{
    try{
        if(!_SHOW_COORDINATES){
            return;
        }
        if(!event)
            event=window.event;

        clear_node(document.getElementById("coords"));
        var px_coords=_MAP_WRAPPER.convert_to_relative_pixel_coords(event.clientX,event.clientY);
        var coords = _MAP_WRAPPER.convert_to_geo( px_coords[0],px_coords [1]);
        document.getElementById("coords").appendChild(document.createTextNode(coords));
        stop_propagating_event(event);
	
    }catch(e)
    {
        alert("Eventsmanager.mappa_mouse_over(): "+e);
        return false;
    }
	
}

function mappa_mouse_move(event)
{
    try{
        if(!event)
            event=window.event;
        _OP_USER.mouse_move(event);
		
    }catch(e)
    {
        alert("Eventsmanager.mappa_mouse_move(): "+e);
        return false;
    }
}
function mappa_mouse_up(event)
{
    try{
       
        if(!event)
            event=window.event;
			
        if( _OP_USER )
        {
            //Remove the registerd events and a display coordinate event
            if(document.removeEventListener)
            {
                document.getElementById( _MAP_ID ).removeEventListener("mousemove",mappa_mouse_move,false);
                document.getElementById( _MAP_ID ).addEventListener("mousemove",mappa_mouse_over,false);
				
            }else
            {
                document.getElementById( _MAP_ID ).onmousemove=mappa_mouse_over;
                document.getElementById( _MAP_ID ).onmouseup=null;
                if(document.attachEvent)
                {
                    document.getElementById( _MAP_ID ).releaseCapture();
                }
            }
			
            _OP_USER.mouse_up(event);

        }
		
    }catch(e)
    {
        alert("Eventsmanager.mappa_mouse_up(): "+e);
        return false;
    }
}
function layer_change(target)
{
    var params="type=layers&action=update&livelli=";
    for(var i=0;i<document.forms[0].elements.length;i++)
    {
        if(document.forms[0].elements[i].checked)
        {
            if(i==0)
                params+=document.forms[0].elements[i].value;
            else
                params+=","+document.forms[0].elements[i].value;
        }
		
    }
    clear_node(document.forms[0]);
    document.getElementById("map_frame").src=_UI_MAP+"?"+params+"&random="+Math.random();
}

function reload_map(params)
{
    try{
        loading_message(true);
        document.getElementById("layers_container").style.visibility="hidden";
        document.getElementById("map_frame").src=_UI_MAP+"?"+params;
    }
    catch(e)
    {
        alert("Eventsmanager.reload_map(): "+e);
        return false;
    }
}

function proccess_map_response(img_url,scale_url,ref_url,scale,minx,maxx,miny,maxy,w,h,id_map)
{
    try{
        _MAP_WRAPPER.update_map(img_url,scale_url,ref_url,scale,minx,maxx,miny,maxy,w,h,id_map);
    }
    catch(e)
    {
        alert("Eventsmanager.proccess_map_response(): "+e);
        return false;
    }
}

function remove_popup()
{
    var popup = document.getElementById("popup");
    if(popup)
    {
        var parent = document.getElementById("appl_body");
        clear_node(popup);
        parent.removeChild(popup);
        //Sets noop
        document.getElementById("tool_no_op").checked=true;
        remove_all_events();
        _OP_USER = new Idle();
    }
    remove_sub_menu();
}

function register_mouse_down_handler(handler)
{
    try{
        if(document.removeEventListener)
            document.getElementById( _MAP_ID ).removeEventListener("mousedown",_EVENT_LISTENER,false);
        else
        {
            document.getElementById( _MAP_ID ).onmousedown=null;
            if(document.attachEvent)
                document.getElementById( _MAP_ID ).releaseCapture();
        }
		
        remove_popup();
		
        _EVENT_LISTENER=handler;
		
        if(document.addEventListener)
        {
            document.getElementById( _MAP_ID ).addEventListener("mousedown",handler,false);
        }
        else
        {
            document.getElementById( _MAP_ID ).onmousedown=handler;
        //14.04.2009 removed for preventing toolbas icons fire events to the map
//        			if(document.attachEvent)
//        				document.getElementById( _MAP_ID ).setCapture();
        }
		

    }catch(e)
    {
        alert("Eventsmanager.register_mouse_down_handler(): "+e);
        return false;
    }
}

function register_mouse_move_handler(event)
{
    try{
        if(document.addEventListener)
        {
            document.getElementById( _MAP_ID ).addEventListener("mousemove",mappa_mouse_move,false);
            document.getElementById( _MAP_ID ).addEventListener("mouseup",mappa_mouse_up,false);
        }else
        {
            document.getElementById( _MAP_ID ).onmousemove=mappa_mouse_move;
            document.getElementById( _MAP_ID ).onmouseup=mappa_mouse_up;
            if(document.attachEvent)
            {
                document.getElementById( _MAP_ID ).setCapture();
            }
        }
	
    }catch(e)
    {
        alert("Eventsmanager.register_mouse_move_handler(): "+e);
        return false;
    }
}

function register_mous_up_handler(event)
{
    try{
        if(document.addEventListener)
        {
            document.getElementById( _MAP_ID ).addEventListener("mouseup",mappa_mouse_up,false);
        }else
        {
            document.getElementById( _MAP_ID ).onmouseup=mappa_mouse_up;
            if(document.attachEvent)
            {
                document.getElementById( _MAP_ID ).setCapture();
            }
        }
		
    }catch(e)
    {
        alert("Eventsmanager.register_mouse_up_handler(): "+e);
        return false;
    }
}

function remove_all_events()
{
    try{
        if(document.removeEventListener)
        {
            document.getElementById( _MAP_ID ).removeEventListener("mousedown",_EVENT_LISTENER,false);
            document.getElementById( _MAP_ID ).removeEventListener("mousemove",mappa_mouse_move,false);
            document.getElementById( _MAP_ID ).removeEventListener("mousemove",mappa_mouse_over,false);
            document.getElementById( _MAP_ID ).removeEventListener("mouseup",mappa_mouse_up,false);
        }
        else
        {
            document.getElementById( _MAP_ID ).onmousedown=null;
            document.getElementById( _MAP_ID ).onmousemove=null;
            document.getElementById( _MAP_ID ).onmouseup=null;

            if(document.attachEvent)
            {
                document.getElementById( _MAP_ID ).releaseCapture();
            }
        }
    }catch(e)
    {
        alert("Eventsmanager.remove_all_events(): "+e);
        return false;
    }
}

function evt_add_layer(name,active,list_objects,list_urls)
{
    try{
        var form= document.forms[0];
        var div = document.createElement("div");
        div.onclick=function(){
            _MAP_WRAPPER.evt_select_layer(this);
        }
        if(_MAP_WRAPPER.is_layer_selected(name))
            div.className="layer_selected";
        else
            div.className="layer";

        var chck = document.createElement("input");
        chck.type='checkbox';
        chck.name='livello';
        chck.onclick=Function('layer_change(this);');
        chck.value=name;
        div.id=name;
        
        div.appendChild(chck)
        div.appendChild(document.createTextNode(name))
        form.appendChild(div);
		
        if(active == "true")
        {
            chck.checked=true;
            for(var i=0;i<list_objects.length;i++)
            {
                var obj_name=list_objects[i];
                var url_image=list_urls[i];
                var img = document.createElement('img');
                img.src=url_image;
                img.onload=layer_image_loaded;
                form.appendChild(img);
                form.appendChild( document.createTextNode(obj_name) );
                form.appendChild(document.createElement("br"));
            }
        }
		
    }catch(e)
    {
        alert("Events_Manager.evt_add_layer(): "+e);
        return false;
    }
}

function layer_image_loaded()
{
    _IMAGES_TO_LOAD--;
    if(_IMAGES_TO_LOAD == 0)
        reload_map("type=map&action=load");
}

function stop_propagating_event(event)
{
    try{
        if(event.stopPropagation)
            event.stopPropagation();
        else
            event.cancelBubble=true;
		
        //Prevent default
        if(event.preventDefault)
            event.preventDefault();
        else
            event.returnValue=false;
    }
    catch(e)
    {
        alert("Eventsmanager.stop_propagating_event() "+e);
        return false;
    }
}

function process_mouse_down(event,obj)
{
    try{
        
        if(!event)
            event=window.event;
        register_mouse_move_handler(event);
		
        _OP_USER = obj;
        _OP_USER.mouse_down(event);
    }
    catch(e)
    {
        alert("process_mouse_down(): "+e);
        return false;
    }
	
}

function draw_extra_graphics(new_graphics,engine_type)
{
    init_graphics_engines(new_graphics,engine_type);
    var graph_engine = null;
    if(engine_type == _SELECTION_DRAWING_ENGINE){
        graph_engine = _jg;
    }else if(engine_type == _EVENTS_DRAWING_ENGINE){
        graph_engine = _jg2;
    }else if(engine_type ==_ALL_DRAWING_ENGINES){
        _jg.setPrintable(false);
        for(var i=0; i < _LIST_OF_EXTRA_GRAPHICS.length; i++){
            _LIST_OF_EXTRA_GRAPHICS[i].draw(_jg);
        }
        _jg.paint();
        return;
    }
    
    for(var i=0; i < _LIST_OF_EXTRA_GRAPHICS.length; i++){
        _LIST_OF_EXTRA_GRAPHICS[i].draw(graph_engine);
    }
    graph_engine.paint();
}


function draw_extra_graphics_object(new_graphics,object,engine_type)
{
    init_graphics_engines(new_graphics,engine_type);
    
    if(engine_type == _SELECTION_DRAWING_ENGINE){
        _jg.setPrintable(false);
        object.draw(_jg);
        _jg.paint();
    }else if(engine_type == _EVENTS_DRAWING_ENGINE){
        _jg2.setPrintable(false);
        object.draw(_jg2);
        _jg2.paint();
    }else if(engine_type ==_ALL_DRAWING_ENGINES){
        _jg2.setPrintable(false);
        object.draw(_jg2);
        _jg2.paint();
        _jg.setPrintable(false);
        object.draw(_jg);
        _jg.paint();
    }
}

function init_graphics_engines(new_graphics,engine_type){
    if(new_graphics){
        if(engine_type == _SELECTION_DRAWING_ENGINE){
            _jg = new jsGraphics(_MAP_ID);
        }else if(engine_type == _EVENTS_DRAWING_ENGINE){
            _jg2 = new jsGraphics(_MAP_ID);
        }else if(engine_type ==_ALL_DRAWING_ENGINES ){
            _jg = new jsGraphics(_MAP_ID);
            _jg2 = new jsGraphics(_MAP_ID);
        }
    }
    else{
        if(engine_type == _SELECTION_DRAWING_ENGINE){
            _jg = _jg == null ? new jsGraphics(_MAP_ID):_jg;
        }else if(engine_type == _EVENTS_DRAWING_ENGINE){
            _jg2 = _jg2 == null ? new jsGraphics(_MAP_ID):_jg2;
        }else if(engine_type ==_ALL_DRAWING_ENGINES ){
            _jg = _jg == null ? new jsGraphics(_MAP_ID):_jg;
            _jg2 = _jg2 == null ? new jsGraphics(_MAP_ID):_jg2;
        }
    }
}


function reset_extra_graphics(engine_type)
{	
    clear_points(engine_type);
    clear_linepath(engine_type);
    clear_lines(engine_type);
    _LIST_OF_SELECTED_OBJECTS.splice(0,_LIST_OF_SELECTED_OBJECTS.length);
    _ID_GEOMETRY = -1;
    
    _jg = _jg == null ? new jsGraphics(_MAP_ID):_jg;
    _jg2 = _jg2 == null ? new jsGraphics(_MAP_ID):_jg2;
	
    for(var i=0; i < _LIST_OF_EXTRA_GRAPHICS.length; i++){
        _LIST_OF_EXTRA_GRAPHICS[i].clear(_jg);
        _LIST_OF_EXTRA_GRAPHICS[i].clear(_jg2);
    }
    _jg.clear();
    _jg = null;
    _jg2.clear();
    _jg2 = null;
    _LIST_OF_EXTRA_GRAPHICS.splice(0,_LIST_OF_EXTRA_GRAPHICS.length);
    _LIST_OF_EXTRA_GRAPHICS.push(new Extra_Graphics());
}
function clear_extra_graphics(engine_type)
{
    init_graphics_engines(false,engine_type);
    if(engine_type == _SELECTION_DRAWING_ENGINE){
        _jg.clear();
    }else if(engine_type == _EVENTS_DRAWING_ENGINE){
        _jg2.clear();
    }else if(engine_type ==_ALL_DRAWING_ENGINES){
        _jg.clear();
        _jg2.clear();
    }
}

function remove_from_extra_graphics(object,engine_type)
{
    for(var i=0; i < _LIST_OF_EXTRA_GRAPHICS.length; i++)
    {
        if(_LIST_OF_EXTRA_GRAPHICS[i] === object)
        {
            _LIST_OF_EXTRA_GRAPHICS.splice(i,1);
            break;
        }
    }
    clear_extra_graphics(engine_type);
}


function evt_create_plot(event)
{
    process_mouse_down(event,new Evt_Create_Plot());
}
function show_popup_menu(event,obj)
{
    try{
        if( !event ){
            event = window.event;
        }
        obj.show(event.clientX,event.clientY);
        change_selected_tool(null);
        stop_propagating_event(event);
    }catch(e)
    {
        alert("Eventsmanager.show_popup_menu(): "+e);
        return false;
    }
}

function change_language(lang){
    window.location.href=window.location.href.replace(/(\?.*)/,"")+"?lang="+lang+"&rand="+Math.random();
}

function evt_but_rotate(event) {
    var popup_menu = document.getElementById("input_popup");
    if(popup_menu != null)
    {
        clear_node(popup_menu);
        document.getElementById("window").removeChild(popup_menu);
    }

    var parent = document.getElementById("window");
    var div_popup = document.createElement("div");
    parent.appendChild(div_popup);

    div_popup.id="input_popup";
    div_popup.style.left=event.clientX+"px";
    div_popup.style.top=event.clientY+"px";
    div_popup.appendChild(document.createTextNode(_MSG_ANGLE+":") );

    var inpt = document.createElement("input");
    inpt.id="angle";
    inpt.className="testo_normale";
    div_popup.appendChild(inpt );

    var button = document.createElement("button");
    button.className="button";
    button.appendChild( document.createTextNode("OK") );
    div_popup.appendChild(button);

    button.onclick=function()
    {
        reload_map("type=map&action=rotate&angle="+document.getElementById("angle").value);
        remove_popup();
        var popup_menu = document.getElementById("input_popup");
        if(popup_menu != null)
        {
            clear_node(popup_menu);
            document.getElementById("window").removeChild(popup_menu);
        }
    }
}