var debug_vars = [];
var global_polylines = [];
var fixMargin = false;

// gobalna zmienna przechowujac handler do clikniec na mapie, fix do obslugi tworzenia lini na mapie
var click_listener = false;
function downloadMap(mapid){
    if(mapid==''){

        alert("Brak pliku mapy");
        return;
    }
    document.getElementById('inputMapId').value = mapid;
   
    document.getElementById('downloadFile').click();

}

var LSI_SearchPagination_Class = Class.create();
LSI_SearchPagination_Class.prototype = {
    links : [],
    instance : null,
    instance_wrapper: null,
    active: [],
    first: [],
    backward: [],
    previous: [],
    next: [],
    forward: [],
    last: [],
    x:0,
    center:0,
    inMotion:false,
    overlaps_cache: [],
   

    initialize: function(instance) {
        if (instance)
        {
            this.instance =  instance;
            this.x = this.instance.cumulativeOffset()[0];
            
            this.center = this.instance.up('div.pagination_container').getDimensions().width/2;
            new Effect.Move(this.instance, {
                x: this.center,
                y: 0,
                mode: 'absolute'
            });

            this.instance_wrapper = this.instance.up('div.pagination_wrapper');
          
            this.links = this.instance.select('li a');
           
            if (this.links.length > 1) {
                this.active = this.instance.select('a.active');
                this.first = this.instance_wrapper.select('a.first')
                this.backward = this.instance_wrapper.select('a.backward')
                this.previous = this.instance_wrapper.select('a.previous')
                this.next= this.instance_wrapper.select('a.next')
                this.forward = this.instance_wrapper.select('a.forward')
                this.last = this.instance_wrapper.select('a.last')

                this.handleFirst();
                this.handleBackward();
                this.handlePrevious();
                this.handleNext();
                this.handleForward();
                this.handleLast();
            }
            else  {
               this.instance_wrapper.select('div').invoke('hide');
                this.instance_wrapper.setStyle({
                  border: 'none'
                });
            }
        }
    },

    handlePrevious: function() {
        if (this.previous.length > 0) {
            this.previous.each(function (item) {
                item.observe('click', function(event){
                    Event.stop(event);

                    if (this.instance.select('a.active')[0].up('li').previous('li')) {
                        this.animate(this.clickPage(this.instance.select('a.active')[0].up('li').previous('li').down('a')))
                    }
                }.bind(this))
            }.bind(this))
        }
    },

    handleBackward: function() {
        if (this.backward.length > 0) {

            this.backward.each(function (item) {
                item.observe('click', function(event){
                    Event.stop(event);

                    if (this.instance.select('a.active')[0].up('li').previous('li', 4)) {
                        this.animate(this.clickPage(this.instance.select('a.active')[0].up('li').previous('li', 4).down('a')))
                    }
                }.bind(this))
            }.bind(this))
        }
    },

    handleForward: function() {
        if (this.forward.length > 0) {
            this.forward.each(function (item) {
                item.observe('click', function(event){
                    Event.stop(event);

                    if (this.instance.select('a.active')[0].up('li').next('li', 4)) {
                        this.animate(this.clickPage(this.instance.select('a.active')[0].up('li').next('li', 4).down('a')))
                    }
                }.bind(this))
            }.bind(this))
        }
    },

    handleNext: function() {
        if (this.next.length > 0) {            
            this.next.each(function (item) {
                item.observe('click', function(event){
                    Event.stop(event);

                    if (this.instance.select('a.active')[0].up('li').next('li')) {
                        this.animate(this.clickPage(this.instance.select('a.active')[0].up('li').next('li').down('a')))
                    }
                }.bind(this))
            }.bind(this))
        }
    },

    handleFirst: function() {
        if (this.first.length > 0) {
            this.first.each(function (item) {
                item.observe('click', function(event){
                    Event.stop(event);

                    this.animate(this.clickPage(this.links[0]))
                }.bind(this))
            }.bind(this))
        }
    },

    handleLast: function() {
        if (this.last.length > 0) {
            this.last.each(function (item) {
                item.observe('click', function(event){
                    Event.stop(event);

                    this.animate(this.clickPage(this.links[this.links.length-1]))
                }.bind(this))
            }.bind(this))
        }
    },

    clickPage: function (link) {
        if (!this.inMotion) {
            //do some calculation
            if (link) {
                fireEvent(link, 'click')
            }
            this.active[0] = link;
            return link;
        }
        return null;
    },

    animate: function (link) {
        if (link) {
            var current_link_offset = link.cumulativeOffset().left;
            var val = (current_link_offset - (this.x + this.center)) * (-1);
            this.inMotion = true;
            new Effect.Move(this.instance, {
                x: val,
                y: 0,
                mode: 'relative'
            });
            this.inMotion = false;
        }
    }
}


var LSI_main = Class.create();
LSI_main.prototype = {
    map_container_id : false,
    bounds : false,   
    gmarkers : [],
    polylines : [],
    htmls : [],  
    templates : [],
    searchPointMarker : false,
    overlay_id: null,
    default_zoom_lvl : 15,
    overlay_window_maxmize : false,
    overlay_window_reload : false,
    reasons : [], 
    mapclicked : false,
    //another hack here becasue editable is beeing provided by xml inconsistentl
    globaEditable: false,
    gicons: [],
    city_bounds: false,
    
    initialize: function(map_container_id) {    
        if (GBrowserIsCompatible()) {           
            this.map_container_id = map_container_id;            
            this.initializeGlobals();
            this.setupMap();
            this.setupLegend();                       
            this.setupQuickSearch(); 
            this.initializeSearchPaginationLinks();
        }
    },
    
    initializeGlobals: function(){
      
        //        templates
        this.templates["lsiworkstatusTooltip"] = new Template('<tr class="more #{lsiworkstatus_class}"><td style="width:140px;">Status:</td><td class="value">#{lsiworkstatus_value}</td></tr>');
        this.templates["lsiworktypeTooltip"] = new Template('<tr class="more #{lsiworktype_class}"><td style="width:140px;">Typ robót:</td><td class="value">#{lsiworktype_value}</td></tr>');
        this.templates["lsitrafficchangesTooltip"] = new Template('<tr class="more #{lsitrafficchanges_class}"><td style="width:140px;">Zmiana ruchu:</td><td class="value">#{lsitrafficchanges_value}</td></tr>');
        this.templates["lsinetworktypeTooltip"] = new Template('<tr class="more"><td style="width:140px;">Typ sieci:</td><td class="value">#{lsinetworktype_value}</td></tr>');
        this.templates["descriptionTooltip"] = new Template ('<tr class="note more"><td colspan="2" class="long">#{value}</td></tr>');
        this.templates["toolsTooltip"] = new Template ('<tr class="tools"><td colspan="2" class="long" style="text-align:right">#{value}</td></tr>');
        this.templates["dateTooltip"] = new Template ('<tr><td>Termin #{date_target}:</td><td class="value">#{value}</td></tr>');
        this.templates["rangeTooltip"] = new Template  ('<tr class="address"><td colspan="2" class="long">#{value}</td></tr>');
        this.templates["streetTooltip"] = new Template  ('<tr class="address"><td colspan="2" class="long">#{value}</td></tr>');
        this.templates["publicdescriptionTooltip"] = new Template ('<tr class="note more"><td td style="width:140px;">Informacja dodatkowa:</td><td class="value">#{value}</td></tr>');
  
        this.templates["lsiworkstatus"] = new Template('<tr class="more #{lsiworkstatus_class}"><td>Status:</td><td class="value">#{lsiworkstatus_value}</td><td>Zmiana ruchu:</td><td class="value">#{lsitrafficchanges_value}</td></tr>');
        //this.templates["lsiworktype"] = new Template('<tr class="more #{lsiworktype_class}"><td>Typ robót:</td><td class="value">#{lsiworktype_value}</td></tr>');
        //this.templates["lsitrafficchanges"] = new Template('<tr class="more #{lsitrafficchanges_class}"><td>Zmiana ruchu:</td><td class="value">#{lsitrafficchanges_value}</td></tr>');
        this.templates["lsinetworktype"] = new Template('<tr class="more"><td>Typ sieci:</td><td class="value">#{lsinetworktype_value}</td><td>Typ robót:</td><td class="value">#{lsiworktype_value}</td></tr>');
    
        this.templates["tools"] = new Template ('<tr class="tools"><td colspan="2" class="long" style="text-align:right">#{value_map}&nbsp;#{value}</td></tr>');
        this.templates["date"] = new Template ('<tr><td>Termin od:</td><td class="value">#{value_from}</td><td>Termin do:</td><td class="value">#{value_to}</td></tr>');
        this.templates["range"] = new Template  ('<tr class="address"><td colspan="2" class="long">#{value}</td></tr>');
        this.templates["street"] = new Template  ('<tr class="address"><td style="width:25%">#{value}</td><td style="width:50%" colspan="2">#{description}</td><td style="width:25%">&nbsp;</td></tr>');
        this.templates["publicdescription"] = new Template ('<tr class="note more"><td style="width:25%">Informacja dodatkowa:</td><td style="width:50%" colspan="2">#{value}</td></tr>');

        this.templates["map"] = new Template  ('<a href="javascript:downloadMap(#{mapid})" class="edit">Mapa</a>');
	this.templates["edit"] = new Template ('<a href="editConstruction.jsf?editable=true&constructionID=#{id}" class="edit">Edytuj</a>');

	
        this.reasons[G_GEO_SUCCESS]            = "Success";
        this.reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
        this.reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
        this.reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
        this.reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
        this.reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
        this.reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

        var icon = new GIcon(G_DEFAULT_ICON);
        icon.shadow = '';
        
        this.gicons["default"] = new GIcon(icon, "images/anim0217-1_e0.gif");
        this.gicons["default"].iconSize = new GSize(24,26);

        this.gicons["rurek"] = new GIcon(icon, "images/rurek2.gif");
        this.gicons["rurek"].iconSize = new GSize(25,23);

        this.city_bounds = new GLatLngBounds(new GLatLng(51.68468957944199,19.396705627441406), new GLatLng(51.78971848615625, 19.57660675048828));
    },
    
    setupMap: function(){
        this.map = new GMap2(document.getElementById(this.map_container_id));
        this.map.enableScrollWheelZoom();
        if (!$(this.map_container_id).hasClassName('noLines')) {
            this.map.addControl(new GLargeMapControl());
            this.map.addControl(new GMapTypeControl());
            this.map.addControl(new GOverviewMapControl());
            this.map.addControl(new GScaleControl());        
        }
        else {
            this.map.addControl(new GSmallMapControl());
            this.default_zoom_lvl = 12;
        }
        var lat_lng = [];
        if ($('centralPoint')) {
            lat_lng = $('centralPoint').value.split(' ');
        }
        if (lat_lng[0] && lat_lng[1]) {
            this.map.setCenter(new GLatLng(lat_lng[0], lat_lng[1]), this.default_zoom_lvl);
            this.placeSearchPointMarker(lat_lng[0],lat_lng[1],'dummy value');
        //add moveable marker here!
            
        }else {
            this.map.setCenter(new GLatLng(51.75870296431738, 19.456924436381087), this.default_zoom_lvl);
        }
        this.line_manager = new LSI_LineManager(this.map, this.default_zoom_lvl);
        
        GEvent.addListener(this.map, "infowindowclose", function(overlay, latlng){
            
            if ($('li_'+this.overlay_id))
                $('li_'+this.overlay_id).remove();
            if (this.overlay_window_reload != true) 
                this.overlay_window_maxmize = false;

            this.inclose = true;
            
        }.bind(this));

        
        GEvent.addListener(this.map, "infowindowopen", function(overlay, latlng) {
            	            
            if (this.overlay_window_reload == true) 
                this.overlay_window_reload = false;
            
            var point = this.map.getInfoWindow().getPoint();            
            
            $$('a.more').each(function(link){
                link.observe('click', function(event){ 
                    
                    this.overlay_window_maxmize = true;
                    this.overlay_window_reload = true;
                    this.putInfoWindowToHtml();
                    
                    this.openInfoWindowForOverlay(point);
                    Event.stop(event);
                }.bind(this))
            }.bind(this))
            
            $$('a.less').each(function(link){
                link.observe('click', function(event){ 
                    
                    this.overlay_window_maxmize = false;
                    this.overlay_window_reload = true;
                    this.putInfoWindowToHtml();
                    
                    this.openInfoWindowForOverlay(point);
                    Event.stop(event);
                    
                }.bind(this))
            }.bind(this))
        }.bind(this));
        
        GEvent.addListener(this.map, "zoomend", function(old_lvl, new_lvl){
            //this.line_manager.recalculateWeight();
            }.bind(this));
		
        click_listener = GEvent.addListener(this.map, "click", function(overlay, latlng){
            
            if ($(this.map_container_id).hasClassName('searchPointMarker')) {
                this.placeSearchPointMarker(latlng.lat(), latlng.lng(), 'dummy value')                
            } else {                
                if (latlng) {
                    this.mapclicked = latlng
                    
                }
                if (overlay) {
                    if  (this.inclose == true) {
                        this.inclose = false;
                    }
                    else {
                        if (overlay.overlay_id) {
                            var lines_in_proximity = [];
                            this.overlay_id = overlay.overlay_id;                            
                            if (overlay.point) {
                                this.mapclicked = overlay.point;
                                
                                //cache would have to be done per zoome level
                                //var currentZoomLevel = map.getZoom();
                                //if (!this.overlaps_cache[currentZoomLevel][overlay.overlay_id]) {
                                lines_in_proximity = this.line_manager.findLinesInProximity(this.mapclicked);
                                if (lines_in_proximity.length > 1) {
                                    this.overlay_id = this.line_manager.buildInfoWindowIdForLinesInProximity(lines_in_proximity);                                   
                                    //this compariosn might be wrong, need to check this!!!
                                    if (!this.htmls[this.overlay_id]) {                                   
                                        var html = this.line_manager.buildHtmlForLinesInProximity(lines_in_proximity);
                                        this.htmls[this.overlay_id] = html;                                        
                                    }
                                }
                            //    this.overlaps_cache[currentZoomLevel][overlay.overlay_id] = this.overlay_id;
                            //}
                            //else
                            //{
                            //    this.overlay_id = this.overlaps_cache[currentZoomLevel][overlay.overlay_id]
                            //}
                            }
                        }
                        this.openInfoWindowForOverlay(this.mapclicked)
                    }
                }
            }
        }.bind(this));        
    },
    
    
    /**
     * Note: method should be map instance dependant!!!
     */
    setupLegend: function(){
       
        if ($('legend_trigger')) {
            var legend = $('legend'); 
            var legend_trigger = $('legend_trigger');
            legend.hide();

            Event.observe(window, 'resize', function() {
                var pos = legend_trigger.cumulativeOffset();
                legend.setStyle({
                    top:  '57px',
                    left: pos[0] + "px",
                    width: '272px',
                    position:'absolute'
                })
            })

            var dm = $(this.map.getContainer()).getDimensions();
            var height = dm.height - 9;
            var width = dm.width - 21 - legend.getDimensions().width;
            
            $('legend_trigger').setStyle({
                top: '-' + height + 'px',
                left: width + 'px'
            })
            $('legend_trigger').observe('click', function(event){
                var pos = legend_trigger.cumulativeOffset();
                legend.setStyle({
                    top:  '57px',
                    left: pos[0] + "px",
                    width: '272px',
                    position:'absolute'
                })
                Effect.toggle('legend', 'blind', {
                    duration: 0.2
                });
                Event.stop(event);
            });
        }
    },

    /**
     *handles small map for central point definition
     **/
    setupQuickSearch: function() {
        $$('.searchinput').each(function(searchwrapper) {
            var searchinput = searchwrapper.down('input#search');
            var searchtrigger = searchwrapper.down('input#searchtrigger');
            var response = searchwrapper.next('div.prompts');
            var cleanup = searchwrapper.down('div').down('input.cleanup');
            cleanup.observe('click', function(item){
                this.removeSearchMarker();
                $$('div.prompts').each(function(item){
                    new Effect.BlindUp( item.down('ul.prompt_list'), {
                        afterFinish: function () {
                            $(item).innerHTML = ''
                        }
                    })
                })
            }.bind(this));
            response.identify();
            var geo = new GClientGeocoder();
            searchtrigger.observe('click', function(ev){
                this.showAddress(searchinput,response, geo);
                                
                Event.stop(ev)
            }.bind(this));
            
        }.bind(this));
    },
        
    initializeSearchPaginationLinks: function () {
        var searchIDSourceUrl = window.location.href;            
        if ($$('ul.pagination a')[0]) {
            searchIDSourceUrl = $$('ul.pagination a')[0].href;
        }
        if ($('searchID') || get_url_param('searchID', searchIDSourceUrl ) ) {
            var searchID = get_url_param('searchID', searchIDSourceUrl);
            if ($('searchID')) {
                searchID = $F('searchID');
            }
            if(document.getElementById("searchIDHidden")){
                document.getElementById("searchIDHidden").value = searchID;
            }
            // do not use here searchIDSourceUrl as in case its pagination url page number will be wrong...
            var pageNumber = get_url_param('pageNumber', window.location.href);
            if (!pageNumber) {
                pageNumber = 1;
            }            
            //this is done on load so always load first page on load
            this.getLines(LSI_MapHelper.buildSearchLink(searchID, pageNumber), false);
        }
        
        if ($('constructionID') || get_url_param('constructionID', window.location.href ) ) {
            get_url_param('constructionID', window.location.href )
            var constructionID = get_url_param('constructionID', window.location.href );
            if ($('constructionID')) {
                constructionID = $F('constructionID');
            }
            this.getLines(LSI_MapHelper.buildEditLink(constructionID), true);
        }
    },
        
    getLines: function (url, editable) {
        this.globaEditable = editable;
        this.cleanupSearchResults(true);
        var request = GXmlHttp.create();        
        request.open("GET", url, true);
        request.onreadystatechange = function(){
            if (request.readyState == 4) {
                var lines = this.processXml(request.responseText.replace(/(\n)*/,''));
                this.removeLoaderImage();
                if (lines.length > 0) {
                    if (!$(this.map_container_id).hasClassName('noLines')) {                       
                        this.loadLinesToMap(lines);
                    }                   
                    LSI_MapHelper.buildShowOnMapLink(get_url_param('searchID', url), get_url_param('pageNumber', url));
                } 
            }
        }.bind(this)
        request.send(null);        
    }, 
    
    placeSearchPointMarker: function(lat,lng,prompts) {

        var point = new GLatLng(lat,lng);
        
        if (this.searchPointMarker) {
            this.map.removeOverlay(this.searchPointMarker);
        }
        this.map.setCenter(point,this.map.default_zoom_lvl); 
        this.searchPointMarker = new GMarker(point, {
            draggable: true
        });
        GEvent.addListener(this.searchPointMarker, "dragend", function(latlng) {
            this.map.setCenter(latlng,this.map.default_zoom_lvl);
            if ($('centralPoint')) {
                $('centralPoint').value = latlng.lat()+":"+latlng.lng();    
            }
            
        }.bind(this));
        this.map.addOverlay(this.searchPointMarker);
        if ($(prompts)) {
            if ( $(prompts).down('ul.prompt_list')) {
                new Effect.BlindUp( $(prompts).down('ul.prompt_list'), {
                    afterFinish: function () {
                        $(prompts).innerHTML = ''
                    }
                });
            }
        }
        if ($('centralPoint')) {
            $('centralPoint').value = lat+":"+lng;    
        }
    },
    
    showAddress: function(searchinput,response, geo) {
        var search = searchinput.value;

        if (search) {
            var g_index_fix = new RegExp('inflancka', "gi");
            if (search.match(g_index_fix)) {
                search = search + ", Łódź";
            }
        
            var re = new RegExp('polska', "gi");
            if (search.match(re) == null) {
                search = search + ", Polska";
            }


            geo.getLocations(search, function (result)
            {
                mapa.map.clearOverlays();
                var blind_down = false;
                if (result.Status.code == G_GEO_SUCCESS) {             
                    // ===== If there was more than one result, "ask did you mean" on them all =====
                    if (result.Placemark.length > 1) {
                        response.innerHTML = "<ul class=\"prompt_list\" style=\"display:none;\"></ul>";
                        // Loop through the results
                        var list_item = new Template('<li><a href="javascript:mapa.placeSearchPointMarker(#{lat}, #{lng},\'#{response_id}\')">#{address}</a></li>');
                   
                        for (var i=0; i<result.Placemark.length; i++) {
                            
                            var p = result.Placemark[i].Point.coordinates;
                            var point_lat_lng = new GLatLng(p[1], p[0]);
                            //if (mapa.city_bounds.containsLatLng(point_lat_lng) ){
                                blind_down = true;
                                var tmp = list_item.evaluate({
                                    lat: p[1],
                                    lng: p[0],
                                    response_id: response.id,
                                    address: result.Placemark[i].address
                                });
                                response.down('ul.prompt_list').insert(tmp);
                        
                            //}
                        }
                        if (blind_down == true) {
                            response.insert({
                                top: "<h3>Czy szukasz?</h3>"
                            })
                            new Effect.BlindDown( response.down('ul.prompt_list'));
                        }
                   
                    }
                    else {
                        response.innerHTML = "";
                        var p = result.Placemark[0].Point.coordinates;
                        mapa.placeSearchPointMarker(p[1],p[0], response.id)
                    }
                }
                else {
                    var reason="Code "+result.Status.code;
                    if (mapa.reasons[result.Status.code]) {
                        reason = mapa.reasons[result.Status.code]
                    }                    
                }
            }
            );
        }
    },
    
    	
    /**
     * Note: method should be map instance dependant!!!
     */
    
    putInfoWindowToHtml: function(){		
        this.save_html(this.htmls[this.overlay_id]);
        if (this.overlay_window_maxmize == false) {
            if ($('li_'+this.overlay_id).down('table')) $('li_'+this.overlay_id).down('table').style.height = "100px";
            $$('tr.more').each(function(item){
                item.style.display = 'none'
            })
            $$('a.less').each(function(item){
                item.style.display = 'none'
            })
            $$('a.more').each(function(item){
                item.show();
            })            
        }
        else {
            if ($('li_'+this.overlay_id).down('table'))  $('li_'+this.overlay_id).down('table').style.height = "300px";
            $$('tr.more').each(function(item){
                item.style.display = 'block'
            })
            $$('a.more').each(function(item){
                item.hide();
            })
            $$('a.less').each(function(item){
                item.style.display = 'block';
            })
        }          
    },
    
    getLineHtml: function (line, target, line_id, editable, workstatus_class, worktype_class, triffichanges_class, workstatus_value, worktype_value, triffichanges_value, networktype_value, index) {
      
        var line_container = document.createElement('LI');
        line_container = $(line_container);

        line_container.setStyle({
            width: '96%',
            marginBottom : '15px',
            marginLeft : '0'
        });
        
        if (index % 2 == 1) {
            line_container.setStyle({
                background : '#E0E0E0'
            })
        }else  {
            line_container.setStyle({
                border : '2px dashed #E0E0E0',
                padding: '13px',
                background : '#FAFAFA'
            })
        }
        var target_width = '650px';
        var target_margin = (fixMargin)?'15%':'5%';

        if (target != 'searchResult') {          
            line_container = document.createElement('DIV');
            target_width = '350px';
            target_margin = '0';
        }

        
        //parse attribs
        var editlink = line.getAttribute("editlink");
        
        //parse htmlcontent
        line_container.setAttribute('id', 'li_'+line_id);
        
        if(target == 'map'){
             line_container.setAttribute('class', 'infoTooltip');
        }else{
             line_container.setAttribute('class', 'info');
        }

        
        line_container = $(line_container);
        var the_line_container = line_container;

        line_container =  line_container.insert(document.createElement('TABLE')).down('table');
        
        line_container.setStyle({
            width:target_width,
            marginLeft:target_margin
        });
        if (target != 'searchResult') {
            line_container.setStyle({
                height: '300px'
            });
        }
        
      if(target=='map'){

             var street = line.getElementsByTagName('street')[0];
        line_container.insert(this.templates['streetTooltip'].evaluate({
            value: GXml.value(street)
        }))

        var description = line.getElementsByTagName('description')[0];
        line_container.insert(this.templates['descriptionTooltip'].evaluate({
            value: GXml.value(description)
        }))

        var publicdescription = line.getElementsByTagName('publicdescription')[0];
        line_container.insert(this.templates['publicdescriptionTooltip'].evaluate({
            value: GXml.value(publicdescription)
        }))



        line_container.insert(this.templates['lsiworkstatusTooltip'].evaluate({
            lsiworkstatus_class: workstatus_class ,
            lsiworkstatus_value: workstatus_value
        }))
        line_container.insert(this.templates['lsinetworktypeTooltip'].evaluate({
            lsinetworktype_value:networktype_value
        }))
        line_container.insert(this.templates['lsiworktypeTooltip'].evaluate({
            lsiworktype_class: worktype_class ,
            lsiworktype_value:worktype_value
        }))
        line_container.insert(this.templates['lsitrafficchangesTooltip'].evaluate({
            lsitrafficchanges_class: triffichanges_class ,
            lsitrafficchanges_value: triffichanges_value
        }))

        var datefrom = line.getElementsByTagName('datefrom')[0];
        line_container.insert(this.templates['dateTooltip'].evaluate({
            date_target: 'Od',
            value: GXml.value(datefrom)
        }))

        var dateto = line.getElementsByTagName('dateto')[0];
        line_container.insert(this.templates['dateTooltip'].evaluate({
            date_target: 'Do',
            value: GXml.value(dateto)

        }))

      }else{
        var descriptionText = line.getElementsByTagName('description')[0];
        
        var streetText = line.getElementsByTagName('street')[0];
        line_container.insert(this.templates['street'].evaluate({
            value: GXml.value(streetText),
            description: GXml.value(descriptionText)
        }))
         var publicdescriptionText = line.getElementsByTagName('publicdescription')[0];
        line_container.insert(this.templates['publicdescription'].evaluate({
            value: GXml.value(publicdescriptionText)
        }))
                           
        line_container.insert(this.templates['lsiworkstatus'].evaluate({
            lsiworkstatus_class: workstatus_class ,
            lsiworkstatus_value: workstatus_value,
            lsitrafficchanges_value: triffichanges_value
        }))
        line_container.insert(this.templates['lsinetworktype'].evaluate({
            lsinetworktype_value:networktype_value,
            lsiworktype_value: worktype_value
        }))

        
        var datefromText = line.getElementsByTagName('datefrom')[0];
        
        var datetoText = line.getElementsByTagName('dateto')[0];
        line_container.insert(this.templates['date'].evaluate({
            
            value_from: GXml.value(datefromText),
            value_to: GXml.value(datetoText)
        }))
		var mapid = line.getElementsByTagName('mapid')[0];
        
        var map_html = '';
        if(GXml.value(mapid)!=''){

        map_html = this.templates['map'].evaluate({
            mapid:line_id
        });
        }
      }
        /////////


        var tools_html = '';
        var public_search = window.location.href.search('public.jsf');
        if  (public_search < 0) {
            if (editlink) {
                tools_html = this.templates['edit'].evaluate({
                    id: line_id
                });
            }
        }

        if (target != 'searchResult') {
            the_line_container.insert('<div><a href="#" class="more" ><img src="/internal/images/icons/arrow_down.png"/></a><a href="#" class="less"><img src="/internal/images/icons/arrow_up.png"/></a></div>');
        }
        else {
            if (!$('constructionID') &&  public_search < 0 ) {
                line_container.insert(this.templates['tools'].evaluate({
                    value: tools_html,
		  value_map: map_html
                }))
                
            }else{
                if(map_html!=''){
                    line_container.insert(this.templates['tools'].evaluate({
                        value:'',
                      value_map: map_html
                    }))
                }

            }

        }

        //fixes for IE!!
        line_container.select('td').each(function (item) {
            item.setStyle({
                borderBottom: '1px dotted #000000'
            })
        });
        line_container.select('td.long').each(function (item) {
            item.setStyle({
                width: target_width
            })
        });
        line_container.down('tr').down('td').setStyle({
            fontWeight :'bold'
        });
        line_container.select('td.value').each(function (item) {
            item.setStyle({
                fontWeight :'bold'
            })
        });
            

        return the_line_container;
    },
         
    processXml: function(xml_doc){
        var xmlDoc = GXml.parse(xml_doc);
        var lines = xmlDoc.documentElement.getElementsByTagName("line");
        // read each line
        for (var a = 0; a < lines.length; a++)
        {
            var line_container = '';
            var line = lines[a];
            var line_id = line.getAttribute("id");
            var editable = line.getAttribute("editable") == 'editable';
            editable = this.globaEditable;

            var workstatus_class = line.getElementsByTagName('lsiworkstatus')[0].getAttribute("class")
            var workstatus_value = GXml.value(line.getElementsByTagName('lsiworkstatus')[0]);
            var worktype_class = line.getElementsByTagName('lsiworktype')[0].getAttribute("class")
            var worktype_value = GXml.value(line.getElementsByTagName('lsiworktype')[0]);
            var triffichanges_class = line.getElementsByTagName('lsitrafficchanges')[0].getAttribute("class")
            var triffichanges_value = GXml.value(line.getElementsByTagName('lsitrafficchanges')[0]);
            var networktype_value = GXml.value(line.getElementsByTagName('lsinetworktype')[0]);
            var street_value = GXml.value(line.getElementsByTagName('street')[0]);

            var form_value = GXml.value(line.getElementsByTagName('datefrom')[0]);
            var to_value = GXml.value(line.getElementsByTagName('dateto')[0]);
            var networktype_value_text = GXml.value(line.getElementsByTagName('lsinetworktype')[0]);
            var description = GXml.value(line.getElementsByTagName('description')[0]);
            var mapid = GXml.value(line.getElementsByTagName('mapid')[0]);
            
            var points = line.getElementsByTagName("point");
            //if (points.length) {
            line_container = this.getLineHtml(line, 'map', line_id, editable, workstatus_class, worktype_class, triffichanges_class, workstatus_value, worktype_value, triffichanges_value, networktype_value, form_value, to_value, networktype_value_text, description);

            this.line_manager.addLine(this.createLine(line_id, line_container, editable, points, workstatus_class, worktype_class, triffichanges_class, networktype_value, street_value, form_value, to_value, networktype_value_text, description, worktype_value));
            //}

            line_container = this.getLineHtml(line, 'searchResult', line_id, editable, workstatus_class, worktype_class, triffichanges_class, workstatus_value, worktype_value, triffichanges_value, networktype_value, a);
            
            this.addToSearchResults(line_container);
            
            
        }
        
        return this.line_manager.polylines;
    },
    
    createLine: function(line_id, li_html, editable, points, workstatus_class, worktype_class, triffichanges_class, networktype_value, street_value, from_value, to_value, networktype_value_text, description, worktype_value) {
        var pts = [];
        var polyline = null;
        for (var i = 0; i < points.length; i++) {
            pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")), parseFloat(points[i].getAttribute("lng")));
            this.setBounds(pts[i]);
        }
        //if (pts.length){
        this.htmls[line_id] = li_html;
            
        //polyline = new BDCCPolyline(pts, LineHelper.getColourForState(workstatus_class), LineHelper.getSizeForRoadBlock(triffichanges_class), 0.8,'', LineHelper.getLineStyleForWorkType(worktype_class))
        polyline = new GPolyline(pts, LineHelper.getColourForState(workstatus_class), LineHelper.getSizeForRoadBlock(triffichanges_class), 0.8);

        polyline.state = workstatus_class
        polyline.road_block = triffichanges_class;
        polyline.lsiworktype = worktype_class;
        polyline.lsinetworktype_value = networktype_value;
        polyline.overlay_id = line_id;
        polyline.street = street_value;
        polyline.from_value = from_value;
        polyline.to_value = to_value;
        polyline.description = description;
        polyline.worktype_value = worktype_value;
        polyline.networktype_value_text = networktype_value_text;
        polyline.clickable = true;
        polyline.editable = editable
     
        polyline.pts = pts;
     
        return  polyline;
    },
	
    loadMarkersToMap: function() {
        this.gmarkers.each(function (marker){
            //user marker manager...
            this.map.addOverlay(marker);
            GEvent.addListener(marker, "click", function(){
                this.overlay_id = marker.overlay_id;
                this.openInfoWindowForOverlay(marker.getLatLng());
            }.bind(this));
        }.bind(this))
    },

    


    loadLinesToMap: function(polylines) {
        polylines.each(function(polyline) {
            GEvent.clearInstanceListeners(polyline);//safety
            if (polyline.pts.length > 0 ) {
                this.map.addOverlay(polyline);
                if (polyline.getVertexCount() > 0 && !polyline.editable)
                {
                    var v = polyline.getVertex(0);

                    var point = new GLatLng(v.lat(), v.lng())
                    var marker = new GMarker(point,  this.gicons["rurek"]);

                    marker.overlay_id = polyline.overlay_id
                    marker.point = point;

                    this.map.addOverlay(marker)
                    GEvent.addListener(marker, "click", function() {
                        
                        mapa.overlay_id = marker.overlay_id;
                        mapa.map.setCenter(point);
                        mapa.default_zoom_lvl = 16;
                        mapa.map.setZoom(mapa.default_zoom_lvl);
                    //window opening is handled by map click handler
                     
                    })
                }
                
            }
        }.bind(this))
        this.resetMapFromBounds();
    },
    
    
    setBounds: function (point) {
        if (point) {
            if (!this.bounds) {
                this.bounds = new GLatLngBounds();
            }
            this.bounds.extend(point);
        }
    },
    
    resetMapFromBounds: function () {
        if (this.bounds) {
            this.default_zoom_lvl = this.map.getBoundsZoomLevel(this.bounds);
            this.map.setZoom(this.default_zoom_lvl);
            this.map.setCenter(this.bounds.getCenter());
        }
    },
    
    createMarkerFromLine: function(line){
        var parts = line.split("|");
        var lat = parseFloat(parts[0]);
        var lng = parseFloat(parts[1]);
        var html = parts[2];
        var label = parts[3];
        var icon = parts[4];
        var marker_id = parts[5];
        var point = new GLatLng(lat, lng);
        this.htmls[marker_id] = html;
        var marker = new GMarker(point, this.gicons[icon]);
        marker.overlay_id = marker_id;
        marker.enableDragging();
        return marker;
    },
    
    cleanupSearchResults: function (with_loader) {
        var img = '<li class="loader_img"><img src="/internal/images/ajax-loader.gif"/></li>'
        
        if ($$('ul.search_results')[0]) {
            $$('ul.search_results')[0].innerHTML = '';
            if (with_loader){
                if ($$('.loader_img').length > 0 ) {
                    $$('.loader_img').invoke('show');
                }
                else
                    $$('ul.search_results')[0].insert(img);
            }
        }
    },
    //TODO called for each output row, performance might be better here
    removeLoaderImage: function () {
        $$('.loader_img').invoke('hide')
    },

    addToSearchResults: function (li_html) {
        if ($$('ul.search_results')[0]) {
            $$('ul.search_results')[0].appendChild(li_html);
        }
        
    //        $$('#search_results ul li.info').each(function (item, index) {
    //            if (index % 2 == 1) {
    //                if (!item.hasClassName('odd')) {
    //                    item.addClassName('odd')
    //                }
    //            }else  {
    //                if (item.hasClassName('odd')) {
    //                    item.removeClassName('odd');
    //                }
    //            }
    //        })
    },
       	 
    openInfoWindowForOverlay: function (point){
        this.putInfoWindowToHtml();
        var html_id = 'li_'+this.overlay_id;
        this.map.openInfoWindow(point, document.getElementById(html_id));
    },
	
    save_html: function (html) {
        if (!document.getElementById(html.id)) {
            $(this.map.getContainer()).down('div').insert({
                bottom: html
            }).select('a.line_popup').each(function(item){                
                item.observe('click', function(event){
                    Event.stop(event);
                    mapa.overlay_id = item.getAttribute('href');
                    mapa.openInfoWindowForOverlay(mapa.mapclicked);
                })
            });
        }
    },

    removeSearchMarker: function () {
        this.map.removeOverlay(this.searchPointMarker);
        this.searchPointMarker = null;
        if ($('centralPoint')) {
            $('centralPoint').value = '';
        }
        if ($('search')) {
            $('search').value = '';
        }
    }

    
}

