// **********************************************************************************************
// *  Global variables.                                                                         *
// **********************************************************************************************

var markers,titles,bounds,map, startPoint, subtypes, tmp, currentbounds;
var marker_types = [];
var type_of_markers = 10;
var startZoom = 7;
var maxZoom = 10;
var centerLatitude = 68.5;
var centerLongitude = 16.0;
var checkbuttons = [];
var allchecked = true;
var pegIcon = new GIcon();
var dropdown = false;
pegIcon.image = "colours/colour101.png";
pegIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
pegIcon.iconSize = new GSize(12, 17);
pegIcon.shadowSize = new GSize(17, 24);
pegIcon.iconAnchor = new GPoint(5, 17);
pegIcon.infoWindowAnchor = new GPoint(9, 2);
pegIcon.infoShadowAnchor = new GPoint(18, 25);
var kuling_types = [];
var openLists = [], oIcount = 0;

// **********************************************************************************************
// *  compactMenu, compactChildren and clickSmack are functions to collapse checkboxes.         *
// **********************************************************************************************
function compactMenu(listID,oAutoCol,oPlMn,oMinimalLink) {
	if( !document.getElementsByTagName || !document.childNodes || !document.createElement ) 
	    { return; }
	var baseElement = document.getElementById( listID ); 
	if( !baseElement ) 
	    { return; }
	compactChildren( baseElement, 0, listID , oAutoCol, oPlMn, baseElement.tagName.toUpperCase(), oMinimalLink && oPlMn );
}

function compactChildren( oOb, oLev, oBsID, oCol, oPM, oT, oML ) {
	if( !oLev ) { oBsID = escape(oBsID); 
	if( oCol ) { openLists[oBsID] = []; } }
	
	for( var x = 0, y = oOb.childNodes; x < y.length; x++ ) { 
	    if( y[x].tagName ) {
		//for each immediate LI child
    		var theNextUL = y[x].getElementsByTagName( oT )[0];
    		if( theNextUL ) {
    			//collapse the first UL/OL child
    			theNextUL.style.display = 'none';
    			//create a link for expanding/collapsing
    			var newLink = document.createElement('A');
    			newLink.setAttribute( 'href', '#' );
    			imglnkid = 'imglnk_'+x; 
    			newLink.setAttribute( 'id', imglnkid  );
    			newLink.onclick = new Function( 'clickSmack(this,' + oLev + ',\'' + oBsID + '\',' + oCol + ',\'' + escape(oT) + '\', \''+imglnkid+'\');return false;');
    			//wrap everything upto the child U/OL in the link
    			if( oML ) { var theHTML = ''; } else {
    				var theT = y[x].innerHTML.toUpperCase().indexOf('<'+oT);
    				var theA = y[x].innerHTML.toUpperCase().indexOf('<A');
    				var theHTML = y[x].innerHTML.substr(0, ( theA + 1 && theA < theT ) ? theA : theT );
    				while( !y[x].childNodes[0].tagName || ( y[x].childNodes[0].tagName.toUpperCase() != oT && y[x].childNodes[0].tagName.toUpperCase() != 'A' ) ) {
    					y[x].removeChild( y[x].childNodes[0] ); }
    			}
    			y[x].insertBefore(newLink,y[x].childNodes[0]);
    			y[x].childNodes[0].innerHTML = oPM + theHTML.replace(/^\s*|\s*$/g,'');
    			theNextUL.MWJuniqueID = oIcount++;
    			compactChildren( theNextUL, oLev + 1, oBsID, oCol, oPM, oT, oML );
            } 
        } 
    }
}

function clickSmack( oThisOb, oLevel, oBsID, oCol, oT, nodeid ) {
	if( oThisOb.blur ) { oThisOb.blur(); }
	oThisOb = oThisOb.parentNode.getElementsByTagName( unescape(oT) )[0];
	if( oCol ) {
		for( var x = openLists[oBsID].length - 1; x >= oLevel; x-=1 ) { if( openLists[oBsID][x] ) {
			openLists[oBsID][x].style.display = 'none'; if( oLevel != x ) { openLists[oBsID][x] = null; }
		} }
		if( oThisOb == openLists[oBsID][oLevel] ) {
		openLists[oBsID][oLevel] = null;
		document.getElementById(nodeid).childNodes[0].src = 'kuling_images/pilned_bunn.gif';
		}
		else { oThisOb.style.display = 'block'; openLists[oBsID][oLevel] = oThisOb; document.getElementById(nodeid).childNodes[0].src = 'kuling_images/pilopp_bunn.gif' }
	} else {
	oThisOb.style.display = ( oThisOb.style.display == 'block') ? 'none' : 'block'; 
			
	}
}

// **********************************************************************************************
// *  Client window handler                                                                     *
// **********************************************************************************************
function windowHeight() {
	// Standard browsers (Mozilla, Safari, etc.)
	if (self.innerHeight)
		return self.innerHeight;
	// IE 6
	if (document.documentElement && document.documentElement.clientHeight)
		return document.documentElement.clientHeight;
	// IE 5
	if (document.body)
		return document.body.clientHeight;
	// Just in case. 
	return 0;
}

// **********************************************************************************************
// *  Client window handler                                                                     *
// **********************************************************************************************
function handleResize() {
    	var height = windowHeight() - document.getElementById('content').offsetHeight - 90;
        document.getElementById('map_slot').style.height = height + 'px';
}

// **********************************************************************************************
// *  Method to retrieve a new icon for each new type.                                          *
// **********************************************************************************************
function getColoredIcon(type){
    var limit = 100;
    //Run through the list until we find the correct type, and return it.
    //Limit: 99 colors
    //Når funnet emne, ta indexsnummeret og lag string som henter riktig ikon.
    var prefix = "kuling_images/colours/colour0";
    var zero = "0";
    var sunny  = ".png";
    var shadow = "s.png";
    var icon_url = new String();
    var numb = new String();
    limit = kuling_types.length<100 ? kuling_types.length : 99;
    for(var index=1;index<limit;index++){
         if(kuling_types[index]==type){
            var suffix = new String(index);
            icon_url = (index<10) ? numb.concat(prefix,zero,suffix) : numb.concat(prefix,suffix); 
            return new GIcon(pegIcon, icon_url.concat(sunny), null, icon_url.concat(shadow));
         }    
    }
    //Default icon if not in list.
    return new GIcon(pegIcon, "kuling_images/colours/colour099.png", null, "kuling_images/colours/colour099s.png");
}

// **********************************************************************************************
// *  Method to create specific marker object. Keeps track of lat and lng, type and supertype,  *
// *  name, and whether or not the marker is currently visible.                                 *
// **********************************************************************************************
function createMarkerObject(lat,lng,myname,type,supertype,url){
    var point = new GLatLng(lat,lng);
    var icon = getColoredIcon(type);
    var name_and_type = myname + " (" + type + ")";
    var marker = new GMarker(point,{icon:icon, draggable: false, title:name_and_type});
        
    GEvent.addListener(marker, "click", function() {
            window.location = url;        
        }); 
    
    var markerObject = {"latitude":lat,"longitude":lng,"type":type,"supertype":supertype,"marker":marker, "title":myname, "type_visible":true};
    return markerObject;
}

// **********************************************************************************************
// *  Method to keep track of different types.                                                  *
// **********************************************************************************************
function registerType(type){
    for(var i=0;i<kuling_types.length;i++){
    if(kuling_types[i]==type)
        return;        
    }
    kuling_types.push(type);
}

// **********************************************************************************************
// *  Creates a nested list containing all marker objects plus data concerning them.            *
// **********************************************************************************************
function createNestedMarkerObjectList(coordinates){
//the variable coordinates is retrieved from within the document, having been set by python code.
//    [{"instances":[[{"lat":"66.4", "lng":"17.2", "title":"Kjempeskogen"}]], "subtopics":[{"instances":[[{"lat":"68.48.", "lng":"15.1", "title":"\u00d8ksnes"}], [{"lat":"68.39", "lng":"15.19", "title":"Bo"}], [{"lat":"68.2042121888185", "lng":"15.2490234375", "title":"Sortland"}], [{"lat":"68.20", "lng":"16.58", "title":"Ballangen"}], [{"lat":"68.31", "lng":"17.0", "title":"Evenes"}], [{"lat":"66.47", "lng":"13.13", "title":"Meloy"}]], "subtopics":[], "title":"Kommune"}], "title":"Geografisk st\u00f8rrelse"}, {"instances":[[{"lat":"67.2", "lng":"14.0", "title":"Sametelt"}]], "subtopics":[], "title":"Etnisitet"}, {"instances":[[{"lat":"67.5", "lng":"15.5", "title":"Stavernvennene"}]], "subtopics":[], "title":"Organisasjon"}];</script>    
    var existing_markers = [];    
    for(var i=0;i<coordinates.length;i++){
        existing_markers.push(createStruct(coordinates[i]));
    } 
    return existing_markers;
}

// **********************************************************************************************
// *  Creates a struct object, with the marker and all relevant data. The method is recursive.  *
// *  Instances and subtopics are part of the struct.                                           *
// **********************************************************************************************
function createStruct(foo_list){
  
    var title = foo_list['title']
    
    var instances = [];
    var subtopics = [];
    registerType(title);
    
    var inst_list = foo_list['instances'];
    for(var i=0;i<inst_list.length;i++){
        var element = createMarkerObject(inst_list[i].lat,inst_list[i].lng,inst_list[i].title,title,null,inst_list[i].url);    
        instances.push(element);
    }    
    
    var subs_list = foo_list['subtopics'];
    for(var i=0;i<subs_list.length;i++){
        subtopics.push(createStruct(subs_list[i]));
    }

    var result = {'title': title, 'instances':instances, 'subtopics':subtopics }  
    return result; 
}  

// **********************************************************************************************
// *  recursive method to add markers and their subtopic-markers to the map.                    *
// **********************************************************************************************
function addMarkersToMap(element_list){
    var instances = element_list.instances;
    if(instances){
        for(var i=0;i<instances.length;i++){
            map.addOverlay(instances[i].marker);
        }
    }
    var subtopics = element_list.subtopics;
    if(subtopics){
        for(var j=0;j<subtopics.length;j++){
            addMarkersToMap(subtopics[j]);    
        }
    }
}

// **********************************************************************************************
// *  Sets the center for the given bounding-box.                                                     *
// **********************************************************************************************
function setCenter(mymap, mybounds){
    var zoomLevel = (mymap.getBoundsZoomLevel(mybounds)>maxZoom) ? maxZoom : mymap.getBoundsZoomLevel(mybounds); 
    var clat = (mybounds.getNorthEast().lat() + mybounds.getSouthWest().lat()) /2;
    var clng = (mybounds.getNorthEast().lng() + mybounds.getSouthWest().lng()) /2;
    mymap.setZoom(zoomLevel);
    mymap.setCenter(new GLatLng(mybounds.getNorthEast().lat(),mybounds.getSouthWest().lng()));
    mymap.setCenter(new GLatLng(clat,clng));
}

// **********************************************************************************************
// *  Toggles the "Vis alle" checkbox according to the other checkboxes' status.                *
// **********************************************************************************************
function toggleMaster(toggle_check){
    var masterCheckBox = document.getElementById("master");
    masterCheckBox.checked = toggle_check;
}

function showOrHideNested(show_subtopic,show){
    map.getInfoWindow().hide();
    for(var i=0;i<markers.length;i++){
        showOrHide(show_subtopic,show,markers[i]);
    }
    recalculateBounds(markers);
    if(!allchecked)
        map.setCenter(new GLatLng(centerLatitude,centerLongitude),startZoom);
}

// **********************************************************************************************
// *  Extends the boundingbox with a factor. This is not an accurate percentage, since          *
// *  the box will be extended both in the north-east and south-west direction.                 *
// **********************************************************************************************
function extendBoundingBox(currentbounds, percentage){
    
    north_east_corner = currentbounds.getNorthEast(); //new GPoint(currentbounds.getNorthEast());
    south_west_corner = currentbounds.getSouthWest(); // new GPoint(currentbounds.getSouthWest());
    
    var ne = north_east_corner.toString();
    var sw = south_west_corner.toString();
    
    var separator = ",";

    var arrayOfStrings = ne.split(separator);
    var latitude = arrayOfStrings[0];
    var longitude = arrayOfStrings[1];    
    latitude = latitude.slice(1);
    longitude = longitude.slice(1,-1);    
    var tmp_lat = parseFloat(latitude);
    var tmp_lng = parseFloat(longitude);
    percentage = parseFloat(percentage);
    tmp_lat *= percentage;
    tmp_lng *= percentage;    
    currentbounds.extend(new GLatLng(tmp_lat,tmp_lng));
    
    arrayOfStrings = sw.split(separator);
    latitude = arrayOfStrings[0];
    longitude = arrayOfStrings[1];    
    latitude = latitude.slice(1);
    longitude = longitude.slice(1,-1);    
    tmp_lat = parseFloat(latitude);
    tmp_lng = parseFloat(longitude);
    
    tmp_lat *= percentage;
    tmp_lng *= percentage;    
    currentbounds.extend(new GLatLng(tmp_lat,tmp_lng));
 }





// **********************************************************************************************
// *  Takes the main list (nested list) runs through it and calucalate bounds and sets the map  *
// * accordingly. Uses the metod calculateBounds.                                               *
// **********************************************************************************************
function recalculateBounds(markers){
    var currentbounds = new GLatLngBounds();
    for(var i=0;i<markers.length;i++){
        var instances = markers[i].instances;
        if(instances)
            currentbounds = calculateBounds(currentbounds,markers[i]);
    }
    extendBoundingBox(currentbounds,1.0025); // approx 1/2 % extension.
    setCenter(map,currentbounds);    
}

// **********************************************************************************************
// *  Recursive method used by recalculateBounds                                                *
// **********************************************************************************************
function calculateBounds(bounds, marker_list){
    var instances = marker_list.instances;
    if(instances){
        for(var i=0;i<instances.length;i++){
                if(!instances[i].marker.isHidden()){
                    bounds.extend(instances[i].marker.getPoint());
                }
            }
        }
    var subtopics = marker_list.subtopics;
    if(subtopics){
        
        for(var j=0;j<subtopics.length;j++){
            bounds = calculateBounds(bounds,subtopics[j]);
        }
    }
    return bounds;    
}

// **********************************************************************************************
// *  Recursive method to investigate whether checkboxes are checked or not.                   *
// **********************************************************************************************
function checkAllVisible(element_list){
    var instances = element_list.instances;
    var are_visible = 0;
    if(instances){
        for(var i=0;i<instances.length;i++){
            if(instances[i].type_visible == false){
                are_visible = are_visible+1;
            }
        }
    }
     var subtopics = element_list.subtopics;
     if(subtopics){
        for(var i=0;i<subtopics.length;i++){
            are_visible = are_visible + checkAllVisible(subtopics[i]);
        }
     }
    return are_visible;
 }

// **********************************************************************************************
// *  Show markers, subtypes are optional.                                                      *
// **********************************************************************************************
function showOrHide(show_subtopic,show,element_list){
    var instances = element_list.instances;
    if(instances){
        for(var i=0;i<instances.length;i++){
            if(show){                
                instances[i].marker.show();
                instances[i].type_visible = true;    
            }else{
                instances[i].marker.hide();
                instances[i].type_visible = false;
            }    
        }
    }
    if(show_subtopic){
        var subtopics = element_list.subtopics;
        if(subtopics){
            for(var i=0;i<subtopics.length;i++){
                showOrHide(show_subtopic,show,subtopics[i]);    
            }
        }
    }
}



// **********************************************************************************************
// *  Show markers, specific subtype.                                                           *
// **********************************************************************************************
function showOrHideType(type,element_list){

    var instances = element_list.instances;
    for(var i=0;i<instances.length;i++){
        if(instances[i].type == type){
            if(instances[i].marker.isHidden()){
                instances[i].marker.show();
                instances[i].type_visible = true;
            }else{
                instances[i].marker.hide();
                instances[i].type_visible = false;
                }
        }
    }
     var subtopics = element_list.subtopics;
     if(subtopics.length>0){
        for(var i=0;i<subtopics.length;i++){
            showOrHideType(type,subtopics[i]);
        }
    }
}

// **********************************************************************************************
// *  Function attached to the checkboxes.                                                      *
// **********************************************************************************************
function wrapperShowOrHideType(type,element_list){
    this.ShowOrHide = function () { 
        for(var i=0;i<markers.length;i++){
            showOrHideType(type,markers[i]);            
        }    
        //This code toggles the master checkbox ("All" according to the others. 
        //If all are on, "All" should be on, if one or more are off, "All" should be off.
        var tmp = 0;
        for(var i=0;i<markers.length;i++){
            tmp +=checkAllVisible(markers[i]);
        }
        if(tmp>0)
            toggleMaster(false);
        else
            toggleMaster(true);
            
        recalculateBounds(markers);    
    }
    
   this.ShowOrHideCurrentSubTypes = function () {

        for(var i=0;i<markers.length;i++){
            showOrHideType(type,markers[i]);            
        }
        
    
        var number_of_visible_subtypes = 0;
        var supertype = document.getElementById(type);
        for(var i=0;i<element_list.length;i++){
            current_list = element_list[i].instances;
            for(var j=0;j<current_list.length;j++){
                if(current_list[j].marker.isHidden()){
                    current_list[j].marker.show();
                    current_list[j].type_visible = true;
                    toggleCheckbox(current_list[j].type,true);
                    number_of_visible_subtypes++;
                }else{
                    current_list[j].marker.hide();
                    current_list[j].type_visible = false;
                    toggleCheckbox(current_list[j].type,false);
                    number_of_visible_subtypes--;
                }
            }
    }
        var tmp = 0;
        for(var i=0;i<markers.length;i++){
            tmp +=checkAllVisible(markers[i]);
        }
        if(tmp>0)
            toggleMaster(false);
        else
            toggleMaster(true);
    
        recalculateBounds(markers);            
    }
}

// **********************************************************************************************
// *  Function to remove all markers except for the type specified.                             *
// *  If the argument is null, all markers will be removed.                                     *
// **********************************************************************************************
function removeAllMarkersExcept(subtype){
    for(i in markers){
        if(markers[i].subtype != subtype || subtype == null){        
            map.removeOverlay(markers[i].marker);
        }    
    }
}

// **********************************************************************************************
// *  Function to move to a specific marker's point. The markers are stored in the global       *
// *  variable "markers". The variable showInfo will control whether an infoWindow will open    * 
// *  after the map has panned to the marker.                                                   *
// **********************************************************************************************
function moveToMarker(element,showinfo, type){
    var marker = element.marker;
    map.panTo(marker.getPoint());
    if(showinfo){
        var html = element.title + "(w" + type + ")";
        marker.openInfoWindowHtml(html);
//        document.location = url
        
    }
}

// **********************************************************************************************
// *  Function to create a form-button which triggers a function call when clicked.             *
// **********************************************************************************************
function createButton(buttonText, newFunction){
    var btn = document.createElement("input");
    btn.type = "button";
    btn.value = buttonText;
    if(btn.attachEvent){      
      btn.attachEvent('onclick', newFunction)
    }
    else if(btn.addEventListener){  
       btn.addEventListener('click', newFunction, false);  
    }
    return btn;
}

// **********************************************************************************************
// *  Initiates the main map, which is global.                                                  *
// **********************************************************************************************
function initiateMap(startPoint,startZoom){
   map = new GMap2(document.getElementById("map_slot"));     
   map.addControl(new GSmallMapControl());
   map.addControl(new GMapTypeControl());
   map.addControl(new GScaleControl());
//   map.setCenter(startPoint,startZoom);
   map.setCenter(new GLatLng(0,0),0);
   return map;
}

// **********************************************************************************************
// *  Hides all div-elements except for those of the given type                                 *
// **********************************************************************************************
function hideDivElementsExcept(type){
    var sideTree = document.getElementById('sidebar_list');
    if(sideTree.hasChildNodes){
        var divs = document.getElementById('sidebar_list').getElementsByTagName("div");
        for(i=0,ilength=divs.length;i<ilength ;i++){
            if(divs[i].type == type){
                divs[i].style.display = "block";
            }else{
                divs[i].style.display = "none";
            }
        }
    }
}

// **********************************************************************************************
// *  Makes all div-elements in the sidebar visible.                                            *
// **********************************************************************************************
function showAllDivs(){
    var sideTree = document.getElementById('sidebar_list');
    if(sideTree && sideTree.hasChildNodes){
        var divs = document.getElementById('sidebar_list').getElementsByTagName("div");
        for(i=0,ilength=divs.length;i<ilength ;i++){
            var div = divs[i];
            div.style.display = "block";
        }
    }
}

function createDivElement(title,subtype){
    var divElement = document.createElement('div');
    divElement.type = subtype;
    divElement.innerHTML  = title + '(' + subtype + ')';
    return divElement;
}

// **********************************************************************************************
// *  Creates a div-element to put in the sidebar.                                              *
// **********************************************************************************************
function createCheckButton(myName,myFunction){
    var checkButton = document.createElement('input');
    checkButton.type = "checkbox";
    checkButton.checked = true;
    checkButton.id = myName;        
            
    if(myName=="Alle")
        checkButton.id = "master";
    
    if(checkButton.attachEvent){      
      checkButton.attachEvent('onclick', myFunction)
    }
    else if(checkButton.addEventListener){  
       checkButton.addEventListener('click', myFunction, false);  
    }    
    checkbuttons.push(checkButton);
    return checkButton;
 }

// **********************************************************************************************
// *  Toggles checkboxes on/off.                                                                *
// **********************************************************************************************
function toggleCheckBoxes(){
    
    if(allchecked)
        allchecked = false;
    else    
        allchecked = true;
    
    for(var i=0;i<checkbuttons.length;i++){
        checkbuttons[i].checked = allchecked;
    }
}

function toggleCheckbox(id, checked_or_not){
//    alert(id + checked_or_not);
    var myCheckButton = document.getElementById(id);
    myCheckButton.checked = checked_or_not;
}

function insertDivElements(element_list,type){
    
    var found_types = false;
    var instances = element_list.instances;
    for(var i=0;i<instances.length;i++){
        if(instances[i].type == type){
            var span_element = document.createElement('span');     
            var listItemLink = span_element.appendChild(document.createElement('a'));                           
            var divElement = createDivElement(instances[i].title, type);
            var element = instances[i];    
            var point = instances[i].marker.getPoint();
            var html  = instances[i].title + "(" +  type + ")";
            var marker = instances[i].marker;
            var func = function (evt){
                var src = evt.target || evt.srcElement;
                var point = src.point;
                var html = src.html;
                var marker = src.marker;
                map.panTo(point);
                marker.openInfoWindowHtml(html);                
            }
            divElement.point = point;
            divElement.html = html;
            divElement.marker= marker;            
     
            if(divElement.attachEvent){      
                divElement.attachEvent('onclick', func)
            }
            else if(divElement.addEventListener){  
                divElement.addEventListener('click', func, false);  
            }
            span_element.appendChild(divElement);
            document.getElementById('sidebar_list').appendChild(span_element);
            found_types = true;
        }
    }

    if(found_types){
        return;
    }else{
        var subtopics = element_list.subtopics;    
        for(var j=0;j<subtopics.length;j++){
            insertDivElements(subtopics[j],type);    
        }
    }
}

function wrapperMoveToMarker(element,showinfo, type){
   this.Move = function () { 
        moveToMarker(element,showinfo,type);
    };   
}

function wrapperAll(show_subtopics){
   this.All = function () { 
    toggleCheckBoxes();    
    showOrHideNested(show_subtopics,allchecked);
    };   
}

function wrapperRemove(type){
   this.Remove = function () { removeAllMarkersExcept(type)};   
}

function showDivElements(type){
    hideDivElementsExcept();
    for(var i=0;i<markers.length;i++){
        insertDivElements(markers[i],type);
    }
}

function showExplicitDiv(){
    var myList = document.getElementById("dropdownmenu")
    var typeindex = myList.options[myList.selectedIndex].text;
    if(typeindex=="Ingen")
        hideDivElementsExcept();
    else{
        showDivElements(typeindex);  
    }
}

//Kan lages rekursiv og ivareta de forskjellige nivåene siden.
function dropDownMenu(myFunction){
    var dropdown = document.createElement('select');
    dropdown.id = "dropdownmenu";
    dropdown.name = "dropdownmenu";
    var opt = document.createElement('option');
    opt.innerHTML= "Ingen";
    dropdown.appendChild(opt);    
       
    for(var i=0;i<markers.length;i++){
        for(var i=0;i<kuling_types.length;i++){
            var opt = document.createElement('option');
            opt.innerHTML = kuling_types[i];
            dropdown.appendChild(opt);    
        }
    }
    dropdown.onchange = showExplicitDiv;
    document.getElementById('sidebar_buttons').appendChild(dropdown);
}

function addNestedMarkerList(markers){
    for(var i=0;i<markers.length;i++)
        addMarkersToMap(markers[i]);
}

function createMiniIcon(marker){
    var img_ikon = marker.getIcon();
    var image_element = document.createElement('img');
    var img_url = img_ikon.image;
    image_element.src = img_url;
    image_element.height = "12";
    image_element.width = "10";
    return image_element;
 }

function createLiElement(type,marker, myFunction){
    var li_element = document.createElement('li');
    li_element.appendChild(createCheckButton(type,myFunction));
    var span_element = document.createElement('span');
    span_element.innerHTML = "  " + type;
    li_element.appendChild(span_element);
    if(marker)
        li_element.appendChild((createMiniIcon(marker)));    
    return li_element;
}

function panToExternal(mymap){
    
    var caller_url = location.href;
    var mark = "marker:";
    if(caller_url.match(mark)){
        var index = caller_url.search(mark);
        var start = index + mark.length;
        var coords = caller_url.substring(start,caller_url.length);
        var separator = ",";
        var arrayOfStrings = coords.split(separator);
        var latitude = arrayOfStrings[0];
        var longitude = arrayOfStrings[1];    
        var newpoint = new GLatLng(latitude,longitude); 
        map.setCenter(newpoint,13);
     }
}


// **********************************************************************************************
// *  Init function is to be called when the page loads.                                        *
// *  This function should only be called ONCE.                                                 *
// *  Here, all markers and corresponding div-elements are inserted into the map and sidebar.   *
// **********************************************************************************************
function init() {
    
    if (GBrowserIsCompatible()) {
    
        var add_remove_markers = false;
        handleResize();
        bounds = new GLatLngBounds();
        startPoint = new GLatLng(centerLatitude,centerLongitude);
        map = initiateMap(startPoint,startZoom);
        var myForm = document.getElementById("myform");
        markers = [];
        markers = createNestedMarkerObjectList(coordinates);
        var showInfoWindow = false;
        addNestedMarkerList(markers);
        var sidebar = document.getElementById('sidebar_buttons');
        var sidebar_list = document.createElement('ul');                    
        sidebar_list.className = "expandable_list";
        sidebar_list.id = "exp_list";
        var showAll = new wrapperAll(true);        
        sidebar_list.appendChild(createLiElement("Alle",null, showAll.All));
        var currenttype; 
        var maintype_had_instances = false; 
               
        for(var i=0;i<markers.length;i++){
            currenttype =  markers[i].title;
            var instances = markers[i].instances;
            if(instances.length>0){

                if(markers[i].subtopics){
                    var showOrHide = new wrapperShowOrHideType(currenttype,markers[i].subtopics);
                    sidebar_list.appendChild(createLiElement(currenttype,instances[0].marker, showOrHide.ShowOrHideCurrentSubTypes));
                }else{
                    var showOrHide = new wrapperShowOrHideType(currenttype,null);
                    sidebar_list.appendChild(createLiElement(currenttype,instances[0].marker, showOrHide.ShowOrHide));
                }

                maintype_had_instances = true;
            }else{
                maintype_had_instances = false; 
            }
                        
            if(markers[i].subtopics){
                var li_element = document.createElement('li');
                subs = markers[i].subtopics;
                var ul_element = document.createElement('ul');
                var had_instances = false;
                for(var j=0;j<subs.length;j++){
                    var sub_topics = subs[j].instances;
                    if(sub_topics.length>0){
                       if(!maintype_had_instances){
                            var showOrHide = new wrapperShowOrHideType(markers[i].title,subs);
                            sidebar_list.appendChild(document.createElement('p'));
                            
                            //her skal underliggende typer styres:  liste over subtopics...må leveres med til funksjonen....
//                            sidebar_list.appendChild(createLiElement(markers[i].title,null, showOrHide.ShowOrHide));
                            sidebar_list.appendChild(createLiElement(markers[i].title,null, showOrHide.ShowOrHideCurrentSubTypes));    
                            maintype_had_instances = true;
                       }
                        currenttype =  subs[j].title;
                        var showOrHide  = new wrapperShowOrHideType(currenttype,null);
                        ul_element.appendChild(createLiElement(currenttype,sub_topics[0].marker, showOrHide.ShowOrHide));
                        had_instances = true;
                    }
                }
                if(had_instances)
                    li_element.appendChild(ul_element);        
            }
            sidebar_list.appendChild(li_element);
        }
        sidebar.appendChild(sidebar_list);
        recalculateBounds(markers);
       //compactMenu('exp_list',true,'&plusmn;');
       compactMenu('exp_list',true,'<img src=\"http://kuling.net/kuling_images/pilned_bunn.gif\" width=\"9\" height=\"15\"  />');
        panToExternal(map);
        
        if(dropdown){        
            var span_element = document.createElement('span');
            span_element.innerHTML = "Emnelister: ";
            sidebar_list.appendChild(span_element);
            dropDownMenu();
        }
    }
}

window.onload = init;
window.onunload = GUnload;

