// ======================================================================================
// |                          nupimap_frontpage.js                                      |
// ======================================================================================
// Pål Jostein Didriksen 26.06.2008

var LegendDiv;
var LegendHTML = "";
var LegendDD = ""; // Dropdown
var LegendDDon = false;
var LegendTmp ="";
var LegendSymbol="";
var LegendPolygon="";
var LegendList = "";
var LegendLists = [];
var LegendIcons = [];
var LegendPolygons = [];
var LegendObjShow = [];

var LegendBounds = new GBounds(0,0,0,0);

var MyOverlay = [];
var ColorsHide = [];

var LogDiv = document.getElementById("logDiv");

var map = null;

var ShowCustom = true; // Use custom tiles (=true) or the regular GMap (=false)
var MapDesign = 0; // 0: Default custom tiles. 1: Google map. 2: Google satellite. 3: Google terrain. 4-?: Alternative custom tiles (not implemented)
var CustomIcons = false; // Use custom icons, selected by admin, or use default icon (smallIcon / smallIconNew)
var UseSetNew = true; // If set to TRUE the 'setnew' value will determine which marker should be desplayed as the most recent.
                      // If set to FALSE the marker with the highest ID on the highest object_id will be desplayed as the most recent.
var Collect = [];

var PolygonIW = true; // Mouseover on legend-element: Show infowindow on polygons instead of changing the color (colorchange can be slow)

var CategoryTimeOut = 10000; // Time in milliseconds before category-selection of markers is reset and all markers are displayed

// marker and polygon categories
var mCategoryName = [];
var mCategoryDescr = [];
var mCategoryIcon = [];
var mCategoryIconOn = [];
var mCategoryIconName = [];
var mObjID = [];

var rootFolder = "/GMaps/"; // Kris / Server
//var rootFolder = "/ezpublish/GMaps/"; // PJ
var ezRoot = '/'; // Kris

var marker = null;
var initialZoom=1;
var customZoom;
var centreLat=35.29356;
var centreLon=8.78906;
centreLon=70;
var customCLat = 0;
var customCLon = 0;
var point2 = new GLatLng(17.9787, 25.1367);
var bubble;
var bWaitText = ""
var bWaitPoint;

var myPolygon = [];
var polygonName = [];
var polygonColour = [];
var polygonObjID = [];
var pCount = 0;
var infoHtml = "";
var pName = "";
var pInfo = "";
var pColour = "";
var pCentre;

var showAllTimeoutID = 0;
var MoveZoomTimeout = 0;

var ObjectID = 0;
var ObjectLoaded = ",";
var ObjectName = "";
var FrontPageID = 0; // ObjectID of the front page - if front page is current, display markers only
var minObjID = 0;

var gmarkers = [];

// Slider
var slider;
var sliderIntervalId = 0;
var sliderWidth = 25;
var sliding = false;
var slideSpeed = 25;
var sliderLeft = 685;


// ========= Define icons ==================
var smallIcon = new GIcon();
smallIcon.image = rootFolder + "img/bullet_blue.png";

smallIcon.iconSize = new GSize(16,16);
smallIcon.iconAnchor = new GPoint(8,8);
smallIcon.infoWindowAnchor = new GPoint(8,8);

var smallIconNew = new GIcon();
smallIconNew.image = rootFolder + "img/red_an1.gif";

smallIconNew.iconSize = new GSize(16,16);
smallIconNew.iconAnchor = new GPoint(8,8);
smallIconNew.infoWindowAnchor = new GPoint(8,8);

// ========= Define overlays (MyButton, MyButton2), to cover repeating parts of the map at zoomlevel 1 ============
// The overlay height is less than the map height to allow copyright info to display under it
function MyButton() { }
MyButton.prototype = new GControl();
MyButton.prototype.initialize = function(map) {
  var container = document.createElement("div");
  myDiv = document.createElement("div");
  this.setButtonStyle_(myDiv);
  container.appendChild(myDiv);
  MyOverlay.push(myDiv);
  map.getContainer().appendChild(container);
  return container;
}

MyButton.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0, 0)); }

  MyButton.prototype.setButtonStyle_ = function(button) {
  //button.style.width="103px";
  button.style.width="12px";
  button.style.height="350px";
  button.style.backgroundImage = "url(" + rootFolder + "img/overlay_left1.png)";
}

function MyButton2() { }
MyButton2.prototype = new GControl();
MyButton2.prototype.initialize = function(map) {
  var container = document.createElement("div");
  var myDiv = document.createElement("div");
  this.setButtonStyle_(myDiv);
  container.appendChild(myDiv);
  map.getContainer().appendChild(container);

  MyOverlay.push(myDiv);

  return container;
}

MyButton2.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 0)); }

  MyButton2.prototype.setButtonStyle_ = function(button) {
  //button.style.width="96px";
  button.style.width="186px";
  button.style.height="370px";
  button.style.backgroundImage = "url(" + rootFolder + "img/overlay_right1.png)";
}

// ========= Define legend overlay ====================================
function MyLegend() { }

MyLegend.prototype = new GControl(true,true);
MyLegend.prototype.initialize = function(map) {
    var container = document.createElement("div");
    var myDiv = document.createElement("div");
    //myDiv.setAttribute("title", "Min_Legend");
    LegendDiv = myDiv;
    
    myDiv.id = "LegendMyDiv";
    this.setButtonStyle_(myDiv);
    container.appendChild(myDiv);
    map.getContainer().appendChild(container);

    return container;
}

MyLegend.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0,0)); }

MyLegend.prototype.setButtonStyle_ = function(button) {
    button.style.width="180px";
    button.style.height="390px";
    button.style.opacity=".80";
    button.style.filter="alpha(opacity=80)";
    button.style.MozOpacity="0.8";
    button.style.KhtmlOpacity="0.5";
    
    if( navigator.appName == "Opera" ) {
        button.style.overflow = "auto";
    } else {
        button.style.overflowY="auto";
        button.style.overflowX="hidden";
    }
}  

function Slide()
{
   if(sliding)
      return;

   sliding = true;
   if(sliderWidth == 180) {
      sliderIntervalId = setInterval('SlideRightRun()', 10);
   } else {
      slider.innerHTML = "";
      sliderIntervalId = setInterval('SlideLeftRun()', 10);
   }
}

function SlideLeftRun()
{
   slider = LegendDiv;
   slider.style.backgroundColor = "#A6BBCD";
   if(sliderWidth <= 180)
   {
      sliderWidth += slideSpeed;
      sliderLeft -= slideSpeed;
      if(sliderWidth>180) {
         sliderWidth = 180;
         sliderLeft = 530;
         sliding = false;
         LegendBounds = new GBounds(530,0,710,390);
         clearInterval(sliderIntervalId);     
         LegendDiv.innerHTML = LegendTmp;

      }
      slider.style.width = sliderWidth + 'px';
      slider.style.left = sliderLeft + 'px';
   }
   else
   {
      sliding = false;
      sliderWidth = 180;
      sliderLeft = 530;
      LegendBounds = new GBounds(530,0,710,390);
      slider.style.width = sliderWidth + 'px';
      slider.style.left = sliderLeft + 'px';
      clearInterval(sliderIntervalId);
      LegendDiv.innerHTML = LegendTmp;
  }
}

function SlideRightRun()
{
   LegendDiv.innerHTML = "";
   slider = LegendDiv;
   
   if(sliderWidth >= 25)
   {
      sliderWidth -= slideSpeed;
      sliderLeft += slideSpeed;
      if(sliderWidth <25) {
          sliding = false;
          sliderWidth = 25;
          sliderLeft = 685;
          LegendBounds = new GBounds(685,0,710,390);
          slider.style.width = sliderWidth + 'px';
          slider.style.left = sliderLeft + 'px';      
          slider.style.backgroundColor = "transparent";
          slider.innerHTML = "<a href='javascript:void(0)' onclick='Slide(LegendDiv)'><img src='" + rootFolder + "img/iw_plus.gif' alt='Info'></a>";
          clearInterval(sliderIntervalId);     
      }
      slider.style.left = sliderLeft + 'px';
      slider.style.width = sliderWidth + 'px';
   }
   else
   {
      sliding = false;
      sliderWidth = 25;
      sliderLeft = 685;
      LegendBounds = new GBounds(685,0,710,390);
      slider.style.width = sliderWidth + 'px';
      slider.style.left = sliderLeft + 'px';      
      slider.style.backgroundColor = "transparent";
      slider.innerHTML = "<a href='javascript:void(0)' onclick='Slide(LegendDiv)'><img src='" + rootFolder + "img/iw_plus.gif' alt='Info'></a>";
      clearInterval(sliderIntervalId);
   }
}

function displayMarkers() {
       // Clear values
       mCategoryName = [];
       mCategoryDescr = [];
       mCategoryIcon = [];
       mCategoryIconOn = [];
       mCategoryIconName = [];

       var countryCode = "";
       
       if( ObjectID == FrontPageID ) {
           var FileName = rootFolder + "getmarkers.php?objectID=0&ObjectMarker=1&Active=1";
       } else {
           var FileName = rootFolder + "getmarkers.php?objectID=" + ObjectID + "&ObjectMarker=0";
       }       
    
        GDownloadUrl(FileName, function(data, responseCode) {
        if(responseCode == 200) {
          var xml = GXml.parse(data);
          
          // ============= Markers (cities / locations) ===================================      
          var markers = xml.documentElement.getElementsByTagName("marker");
          
          for (var i = 0; i < markers.length; i++) 
          {
          
                  var name = markers[i].getAttribute("name");
                  var lat = markers[i].getAttribute("lat");
                  var lng = markers[i].getAttribute("lng");
                  var mCategory = markers[i].getAttribute("category");
                  var objName = markers[i].getAttribute("object_name");
                  var mObjectID = markers[i].getAttribute("object_id");
                  var mID = markers[i].getAttribute("markerID");
                  var setNew = markers[i].getAttribute("setnew");
                  var noIW = markers[i].getAttribute("no_iw");
                  var objectLink;
                  var showIcon = 1;

                  // == INFOWINDOW ==
                  if( markers[i].getAttribute("link") ) {
                      objectLink = ezRoot + markers[i].getAttribute("link");
                  }
                  else {
                      objectLink = "";
                  }
                  
                  var title = name;
                  if( objName ) { 
                      title += ": " + objName; 
                  }

                  // DIV has been added to ebubble.js and is not needed here.
                  var infoHtml = "";

                  
                  // If frontpage map, use link and title of related article as marker caption. If not, display custom text.
                  if( ObjectID == FrontPageID ) {
                      if( objName ) {
                          infoHtml += "<h1>" + objName + "</h1>";
                      }
                              
                      if( objectLink ) {
                          infoHtml += "<p><a href='" + objectLink + "'>G&aring; til artikkelen</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>"; 
                      }
                  } else {
                      infoHtml += "<p>" + name + "</p>";
                  }
                 
                  var point2 = new GLatLng(parseFloat(lat),
                                    parseFloat(lng));


                  //if( CustomIcons ) {
                  if( ObjectID > FrontPageID ) {
                      // == ICON ==
                      var iconName = markers[i].getAttribute("icon_identifier");

                      if( iconName ) {
                      
                          var iconFile = markers[i].getAttribute("icon_file");
                          var iconWidth = markers[i].getAttribute("width");
                          var iconHeight = markers[i].getAttribute("height");
                          var iconAnchorX = markers[i].getAttribute("anchor_x");
                          var iconAnchorY = markers[i].getAttribute("anchor_y");
                          var iconShadow = markers[i].getAttribute("shadow_file");
                          var iconShadowW = markers[i].getAttribute("shadow_width");
                          var iconShadowH = markers[i].getAttribute("shadow_height");
                          var iconDescr = markers[i].getAttribute("description");
                          showIcon =  markers[i].getAttribute("showicon");

                          var MyIcon = new GIcon();
                          MyIcon.image = iconFile;
                          MyIcon.iconSize = new GSize(iconWidth, iconHeight);
                          if( !iconWidth || !iconHeight ) {
                              //alert( "størrelse mangler! " + iconName );
                              // missing size information can produce unexpected results!
                          }
                          
                          if( iconShadow ) {
                              MyIcon.shadow = iconShadow;
                              MyIcon.shadowSize = new GSize(iconShadowW, iconShadowH);
                          }
                          
                          MyIcon.iconAnchor = new GPoint(iconAnchorX, iconAnchorY);
                          MyIcon.infoWindowAnchor = new GPoint(5,1);
                      }
                      else
                      {
                         var MyIcon;
                      }

                      var selectedIcon = MyIcon;
                  }
                  else {
                      // Use default icon 
                      var selectedIcon = smallIcon;

                      if( UseSetNew ) {
                          if( setNew == 1 ) {
                              selectedIcon = smallIconNew;
                          }
                      } else {
                          if( i == (markers.length-1) ) {
                             selectedIcon = smallIconNew;
                          }
                      }
                  } // if( CustomIcons )

                  mObjID.push( markers[i].getAttribute("object_id") );
                  marker = createMarker( point2, infoHtml, selectedIcon, true, mCategory, title, iconName, noIW );
                  map.addOverlay(marker);

                  if( showIcon == 0 ) {
                     marker.hide();
                  }
                  
                  // Add icon info for use in legend
                  if( iconName ) {
                      if( mCategoryIconName.toString().indexOf( iconName ) == -1 ) {
                          mCategoryName.push(mCategory);
                          mCategoryDescr.push(iconDescr);
                          mCategoryIcon.push(iconFile);
                          mCategoryIconName.push(iconName);
                          mCategoryIconOn.push(showIcon);
                      }
                  }
          }

        // Errorhandler
        } else if(responseCode == -1) {
          alert("Data request timed out. Please try later.");
        } else { 
          alert("Request resulted in error. Check XML file is retrievable.");
        }
      });
     // ================================================           

} // function displayMarkers

function createMarker(point, infoHtml, MyIcon, showIW, category, title, iconName, noIW ) {
      title = ""; // -> Don't display tooltip
      
      if( MyIcon ) {
          var marker = new GMarker(point, {icon: MyIcon, title: title});
      }
      else {
          var marker = new GMarker(point, {title: title});
      }

        marker.mycategory = category;
        marker.iconName = iconName;
        marker.title = name;
        gmarkers.push(marker);

        //         new EBubble(map, image,                        imageSize,          contentSize,        contentOffset,   anchor,             noCloseOnClick);
        bubble = new EBubble(map, rootFolder + "img/bubble4d.png",new GSize(157,115), new GSize(141,89), new GPoint(11,11), new GPoint(40,113), true);      
        
        if( showIW ) {
            GEvent.addListener(marker, 'mouseover', function() {
                
                // Do not open infowindow if the point is underneath the legend
                if( !LegendBounds.containsPoint(map.fromLatLngToDivPixel(point)) ) {
                    if( !noIW )
                        bubble.openOnMarker(marker,infoHtml);
                }
            });
            
        } else {
            // Set showIW=false if clicking on the marker will zoom the map instead of opening the infowindow
            GEvent.addListener(marker, 'click', function() {
                var myZoom = map.getZoom();
                myZoom++;
                map.setCenter(point, myZoom); //, pic_customMap);
            });
            
        }

      return marker;
} // function createMarker

function ShowLegend(ShowList) {
    if( ShowList ) {
        LegendDiv.innerHTML = LegendHTML + "<ul class='Legend'>" + LegendList + "</ul>";
        LegendTmp = LegendHTML + "<ul class='Legend'>" + LegendList + "</ul>";
        document.getElementById("tab_symbols").className="";
        document.getElementById("tab_list").className="active";
    } else {
        LegendDiv.innerHTML = LegendHTML + LegendDD + LegendSymbol;
        LegendTmp = LegendHTML + LegendDD + LegendSymbol;
        document.getElementById("tab_symbols").className="active";   
        document.getElementById("tab_list").className="";
    }
    //ShowHide("polygonlegend");
}

function LoadContent(a) {
   if( a != ObjectID ) {
       var oTest = "," + a + ",";
       if( ObjectLoaded.indexOf(oTest) < 0 ) {

           SetObjectID(a, Collect[a]);
           getPolygonLegend();
           displayMarkers();
           displayPolygons();
       
       } else {
           //LogDiv.innerHTML += a + " has already been loaded<br>";
       }
   }
}

function ToggleContent(a) {
       var oTest = "," + a + ",";
       if( LegendObjShow[a] ) {
           // Selected: turn it OFF
           LegendObjShow[a] = false;
           document.getElementById("Toggle_" + a).innerHTML += " x " ;
           // Remove element from legend
           RemovePolygons(a);
           RemoveIcons(a);
           createLegendIcons();
       } else {
           // NOT selected: turn it ON
           SetObjectID(a, Collect[a]);
           LegendObjShow[a] = true;
           document.getElementById("Toggle_" + a).innerHTML += " VALGT " ;
           
           var docI = document.getElementById("markerlegend_" + a);
           if( docI )
               docI.style.display="block";
           var docP = document.getElementById("polygonlegend_" + a);
           if( docP )
               docP.style.display="block";
           
           getPolygonLegend();
           displayMarkers();
           displayPolygons();

       }
}

function RemovePolygons(objID) {
    for(var i=0;i<myPolygon.length;i++) {
        if( polygonObjID[i] == objID ) {
            myPolygon[i].hide();
            map.removeOverlay(myPolygon[i]);
        }
    }
    pCount = myPolygon.length -1;
}

function RemoveIcons(objID) {
    for(var i=0;i<gmarkers.length;i++) {
        if( mObjID[i] ) {
            if( mObjID[i] == objID ) {
                gmarkers[i].hide();
                map.removeOverlay(gmarkers[i]);
            }
        }
    }
}

function CloseIW() {
    if( bubble ) {
        bubble.hide();
    }                
}

function getPolygonLegend() {
        var FileName = rootFolder + "getlegend.php?object_id=" + ObjectLoaded.substring(1, (ObjectLoaded.length)-1)
        LegendPolygon = "";
        LegendPolygons = [];
        GDownloadUrl(FileName, function(data, responseCode) {
            if(responseCode == 200) {
              
              var xml = GXml.parse(data);
              var element = xml.documentElement.getElementsByTagName("element");
              
              var pHeader = "<form id='polygonlegend_";
              var header2 = "'><table>\n";
              var iHeader = "<form id='markerlegend_";
              var iTail = "<tr style='display:none'><td class='icon'></td><td class='chk'><input name='element' type='checkbox' value='0'></td>\n</tr>";
              var tmpL = "";
              
              var prevObjID = 0;
              var prevPolygon = true;
              
              for( var i=0;i<element.length;i++) {
                  var thisObjID = element[i].getAttribute("object_id")
                  
                  if( element[i].getAttribute("type") == "polygon" ) {
                  
                      if( thisObjID != prevObjID ) {
                          if( prevObjID > 0 ) {
                              LegendPolygons[prevObjID] = pHeader + prevObjID + header2 + tmpL + "</table></form>\n\n";
                              tmpL = "";
                          }
                              
                          tmpL += "<tr class='LegendHeader' onmouseover='CloseIW()'><td colspan='2'>\n";
                          tmpL += Collect[thisObjID] + "</td><td class='chk'>";
                          if( LegendDDon ) { tmpL +=  "<img src='" + rootFolder + "img/close4.png' title='Lukk dette elementet' onclick='ToggleContent(" + thisObjID + ")'>" };
                          tmpL += "</td></tr>\n";
                      }
                      
                      tmpL += "<tr onmouseover='CloseIW()'>\n";
                      tmpL += "<td class='icon'><span style='border: thin solid black; background-color:" + element[i].getAttribute("colour") + "; color:" + element[i].getAttribute("colour") + ";'>&#9608;</span></td>\n";
                      tmpL += "<td>" + element[i].getAttribute("description") + "</td>\n";
                      tmpL += "<td class='chk'><input name='element' type='checkbox' onclick='ShowHide(\"polygonlegend\"," + thisObjID + ")' value='" + element[i].getAttribute("colour") + "'";
                      
                      if( element[i].getAttribute("display")>0 )
                          tmpL += " checked";
                      
                      tmpL += " ></td>\n</tr>\n";
                      
                      prevObjID = thisObjID;
                      LegendPolygon += tmpL;
                  
                  } else {
                         
                      if( prevPolygon ) {
                          LegendPolygons[prevObjID] = pHeader + prevObjID + header2 + tmpL + "</table></form>\n";
                          prevPolygon = false;
                          tmpL = "";
                      }

                      if( thisObjID != prevObjID ) {
                          if( prevObjID > 0 && tmpL ) {
                              LegendIcons[prevObjID] = iHeader + prevObjID + header2 + tmpL + iTail + "</table></form>\n";
                              tmpL = "";
                          }
                      }

                      tmpL += "<tr onmouseover='CloseIW()'>\n";
                      tmpL += "<td class='icon'><img src='" + element[i].getAttribute("file") + "'></td>\n";
                      tmpL += "<td>" + element[i].getAttribute("description") + "</td>\n";
                      tmpL += "<td class='chk'><input name='element' type='checkbox' onclick='ShowHide(\"markerlegend\"," + thisObjID + ")' value='" + element[i].getAttribute("identifier") + "'";
                      
                      if( element[i].getAttribute("display")>0 )
                          tmpL += " checked";
                      
                      tmpL += " ></td></tr>\n";
                      
                      prevObjID = thisObjID;
                  }
              }
            
             // BUGFIX: Clicking the icon list does not work when less than 2 elements
             //tmpL += "<tr style='display:none'><td class='icon'></td><td class='chk'><input name='element' type='checkbox' value='0'></td>\n</tr>";
            
              if(prevPolygon)
              	LegendPolygons[prevObjID] = pHeader + prevObjID + header2 + tmpL + "</table></form>\n\n";
              else
              	LegendIcons[prevObjID] = iHeader + prevObjID + header2 + tmpL + iTail + "</table></form>\n\n";
              
              createLegendIcons();
              
              GetShowHideInfo(prevObjID);
        } else if(responseCode == -1) {
          alert("Data request timed out. Please try later. (polygon-legend)");
        } else { 
          alert("Request resulted in error. Check XML file is retrievable. (polygon-legend)");
        }
  
    });

}

function DropDownTest() {

    LegendHTML = "<ul id='menu'><li><!--[if lte IE 6]><a href='#nogo'><table><tr><td><![endif]--><dl class='one'>";
    LegendHTML += "	<dt><a href='../menu/index.html'>DEMOS</a></dt>";
    LegendHTML += "		<dd><a href='../menu/zero_dollars.html' title='The zero dollar ads page'>zero dollars</a></dd>";
    LegendHTML += "		<dd><a href='../menu/embed.html' title='Wrapping text around images'>wrapping text</a></dd>";
    LegendHTML += "		<dd><a href='../menu/em_images.html' title='em size images compared'>em sized images</a></dd>";
    LegendHTML += "	</dl><!--[if lte IE 6]></td></tr></table></a><![endif]--></li></ul>";
    
    LogDiv.innerHTML = LegendHTML;
    
    alert( LegendHTML );

}

function createLegendIcons() {
    // Legend is not available in the frontpage

    LegendSymbol = "";
    LegendHTML = "";
    LegendDiv.style.backgroundColor = "#A6BBCD";

    if( ( ObjectID > 0 ) && ( ObjectID > FrontPageID ) ) {

        LogDiv.innerHTML += LegendHTML + "<br>";


        LegendHTML += "\n\n<ul class='subsection_tabs'>\n";
        LegendHTML += "<li class='tab'><a id='tab_symbols' href='javascript:void(0)' class='active' onclick='ShowLegend(false)'>&nbsp;&nbsp;Symboler&nbsp;&nbsp;</a></li>";
        LegendHTML += "<li class='tab'><a id='tab_list' href='javascript:void(0)' onclick='ShowLegend(true)'>&nbsp;&nbsp;&nbsp;&nbsp;Liste&nbsp;&nbsp;&nbsp;&nbsp;</a></li>";    
        LegendHTML += "<li id='slideStart' class='right'><a href='javascript:void(0)' onclick='Slide()'><img id='slideX' src='" + rootFolder + "img/close4.png' title='Skjul tegnforklaringen'></a></li>";
        LegendHTML += "</ul>";
        
        // DROPDOWN: Create dropdown menu for collected objects (temakart)
        if( Collect ) {
            if( LegendDDon ) {
                LegendDD += "<ul id='menu'><li><!--[if lte IE 6]><a href='#nogo'><table><tr><td><![endif]--><dl class='one'>";
    	        LegendDD += "<dt>";
                LegendDD += "<a href='javascript:void(0)'>Velg elementer &#9660;</a>";
                LegendDD += "</dt>";
    
                for( var i=minObjID;i<Collect.length;i++) {
                    if( Collect[i] ) {
                        LegendDD += "<dd id='Toggle_" + i + "'><a href='javascript:void(0)' onclick='ToggleContent(\"" + i + "\")'>" + "&#9632; " + Collect[i] + "</a>";
                        LegendDD += "</dd>"; //Meny </a></dt>\n";
                    }
                
                }
                
                LegendDD += "</dl><!--[if lte IE 6]></td></tr></table></a><![endif]--></li>";
                LegendDD += "</ul>";
            }
        }

        LegendSymbol += "<div class='legend_content'>";
        
        var oLoaded = ObjectLoaded.split(",");
        oLoaded.sort();
        var prev = 0;
        
        for(var i=0;i<oLoaded.length;i++) {
        	
                if( parseInt(oLoaded[i]) ) {
        			
        			if(prev != oLoaded[i]){            
                    if( LegendObjShow[parseInt(oLoaded[i])] ) {
                        if( LegendPolygons[parseInt(oLoaded[i])] ) {
                            LegendSymbol += LegendPolygons[parseInt(oLoaded[i])];
                        }
                        if( LegendIcons[parseInt(oLoaded[i])] ) {
                            LegendSymbol += LegendIcons[parseInt(oLoaded[i])];
                        }
                    }
                    prev = oLoaded[i];
                   }
                }
        }

        LegendDiv.innerHTML = LegendHTML + LegendDD + LegendSymbol + "</div>";
        
        sliderWidth = 180;
    
        // This defines the area covered by the legend. InfoWindows are not opened when they are underneath the legend
        LegendBounds = new GBounds(530,0,710,390);
    
        ShowLegend(false);
        setTimeout( "ShowHide(\"polygonlegend\",ObjectID)", 2000 );
        ShowHide('polygonlegend', ObjectID);
        //polygonLegendDiv
    }
}

function displayPolygons() {
        ShowObject = ObjectID;
        var FileName = rootFolder + "getpolygons.php?object_id=" + ObjectID; // + "&category_id=" + selectedCat;
        infoHtml = "";

        GDownloadUrl(FileName, function(data, responseCode) {
        if(responseCode == 200) {
          var xml = GXml.parse(data);

        // ============= Polygons (countries / areas) ===================================      

        var polygons = xml.documentElement.getElementsByTagName("polygon");
        var pID = 0;
        for (var pIndex = 0; pIndex < polygons.length; pIndex++) {
             pID = pIndex + pCount;
             
             pName = polygons[pIndex].getAttribute("name");
             
             pInfo = polygons[pIndex].getAttribute("info");
             pColour = polygons[pIndex].getAttribute("colour");
             var pFile = rootFolder + "WorldPolyLines/" + polygons[pIndex].getAttribute("file");
             var pLat = polygons[pIndex].getAttribute("lat");
             var pLng = polygons[pIndex].getAttribute("lng");
             pCentre = new GLatLng(parseFloat(pLat), parseFloat(pLng));
             var pLink = polygons[pIndex].getAttribute("link");

             var trSequence;
             var displayIndex = pIndex +1;
             if(mod(pIndex,2)){trSequence="bgdark"; } else {trSequence="bglight"; }

             var pHtml = "<h1>" + pName + "</h1>" + pInfo;
             if( pLink ) { pHtml += "<br/><a href='" + pLink + "'>Les mer</a>"; }
             
             createPolygon(pFile, pColour, pID, pCentre, pHtml, pName);

       }
       ShowHide('polygonlegend', ObjectID);
       
        // ====================================================================           
        
       // ============= Errorhandler  ===================================     
        } else if(responseCode == -1) {
          alert("Data request timed out. Please try later.");
        } else { 
          alert("Request resulted in error. Check XML file is retrievable. (polygons)");
        }
      });
          // ================================================           

} // function displayPolygons

function createPolygon(pFileName, pColour, pID, pCentre, pHtml, pName ) {
	
    LegendPolygon = "<div class='legend_content'><form id='polygonlegend'></form></div>";
             var newPolygon = "";
             
             GDownloadUrl(pFileName, function(data, responseCode)
             {
                 document.getElementById("infoElementID").style.display = "block";
       
                 //if((200==responseCode)&&(0!=data.length))
                 if((responseCode==200) && (data.length>0))
        	     {
                     var iStart = 0;
                     var arePoints = false;
                     var polylineLevels = "";

                     // File structure is [encoded Levels<br>encoded Polylines<br>...]
        	         do
        	         {
   	                      var iEnd = data.indexOf("<br>",iStart);
   	                      
        		          if( !arePoints)
        		          {//Levels
                              polylineLevels = data.substring(iStart,iEnd);
        			          arePoints = true;
       			          }
        		          else
       			          {//Points
                              newPolygon = new GPolygon.fromEncoded({
  			                      polylines: [{
                                      color: "#228CB4", 
                                      weight: 1, 
                                      opacity:1.0,
        			                  points: data.substring(iStart,iEnd),
        			                  levels: polylineLevels,
        			                  zoomFactor: 2, 
                                      numLevels: 18}], 
        			              fill: true, 
                                  color: pColour, 
                                  opacity: 0.8, 
                                  outline: true
                               });
                              
                              map.addOverlay(newPolygon);
            			      arePoints = false;
            			      
                              // Check if polygon should be hidden 
                              if( ColorsHide.toString().indexOf( pColour ) > -1 ) {
                                  newPolygon.hide();
                              }

                             //         new EBubble(map, image,                        imageSize,          contentSize,        contentOffset,   anchor,             noCloseOnClick);
                             bubble = new EBubble(map, rootFolder + "img/bubble4d.png",new GSize(157,115), new GSize(141,89), new GPoint(11,11), new GPoint(40,113), true);      

                               // Add a listener for clicks to display Infowindows
                              GEvent.addListener(newPolygon, "click", function() {
                                      CloseIW();
                                      
                                      // Do not open infowindow if the point is underneath the legend
                                      if( LegendBounds.containsPoint(map.fromLatLngToDivPixel(pCentre)) ) {
                                          map.panTo(pCentre);
                                          bubble.openOnMap(pCentre,pHtml);
                                      } else {
                                          // Pan map if point is outside visible bounds
                                          var mapBounds = map.getBounds();
                                          if( mapBounds.containsLatLng(pCentre) ) { 
                                              bubble.openOnMap(pCentre,pHtml);
                                          } else {
                                              map.panTo(pCentre);
                                              //bubble.openOnMap(pCentre,pHtml);
                                              bWaitText = pHtml;
                                              bWaitPoint = pCentre;
                                          }
                                      }
                              });
            		     
                             pCount++;
                             myPolygon[pCount] = newPolygon;
                             
                             polygonColour[pCount] = pColour;
                             polygonName[pCount] = pName;
                             polygonObjID[pCount] = ObjectID;
                             
                             if( pName != "Dummy" ) {
                                 if( pName != polygonName[pCount-1] ) {
                                     infoHtml = "<li><span style='background-color:" + pColour + "; color:" + pColour + ";'>&#9608;</span> <a href='javascript:void(0)' onclick='polygonEmphasize(" + pCount + ",false)' >" + pName + "</a></li>";
                                     LegendList += infoHtml;
                                 }
                             }
                           
                         }
                  

                      iStart = iEnd + 4;//jump above '<br>' to the next polylines
       		      }while( data.length > iStart)
    		   }
           	   else
        	   {
        	       //LogDiv.innerHTML += "A problem occured while retrieving data file: " + entitiesUrl[b];
        	   }
               
               
               });
               
             // ToDo: Return array/list of pIDs -> use the list in mouseover-list (legend) (?? - only _main_ polygon needed for this effect) 
}

function polygonEmphasize(pID,Out) {
    if(PolygonIW) {
        GEvent.trigger(myPolygon[pID], "click");        
    } else {
        if( Out )
        {
            myPolygon[pID].setFillStyle({color: polygonColour[pID]});
        }
        else
        {
            myPolygon[pID].setFillStyle({color:'#ffffff'});
        }
    }
}

function mod(divisee,base) {
	// Created 1997 by Brian Risk.  http://members.aol.com/brianrisk
	return Math.round(divisee - (Math.floor(divisee/base)*base));
}

function GetShowHideInfo(shObjID) {
    var c_value = [];
    
    if( !shObjID )
        shObjID = ObjectID;
        
    var docObject = LegendPolygons[shObjID];
    
    if( docObject ) {
        if( docObject.element ) {
    
        for (var i=0; i < docObject.element.length; i++)
        {
            if (docObject.element[i].checked)
            {
                c_value += "selected: " + docObject.element[i].value + "\n";
            } else {
                ColorsHide.push(docObject.element[i].value);
                c_value += "not selected: " + docObject.element[i].value + "\n";
            }
        }
        }

    }

}

function ShowHide(legendID, shObjID) {
    if( !legendID )
        legendID = "polygonlegend";

    if( !shObjID )
        shObjID = ObjectID;

    if( ObjectID > FrontPageID ) {

        var c_value = [];
        var docObject = document.getElementById(legendID + "_" + shObjID);
    
        if( docObject ) {
            if( docObject.element ) {
            
                for (var i=0; i < docObject.element.length; i++)
                {
                    if (docObject.element[i].checked)
                    {
                        ShowOnly( docObject.element[i].value, true, legendID, shObjID );
                        c_value += "selected: " + docObject.element[i].value + "\n";
                    } else {
                        ShowOnly( docObject.element[i].value, false, legendID, shObjID );   
                        c_value += "not selected: " + docObject.element[i].value + "\n";
                    }
                }
                //LogDiv.innerHTML += "You selected the following:\n" + c_value + "<br>\n";
            }
        }
    
    }
}

function ShowOnly(name, show, legendID, shObjID) {
    //LogDiv.innerHTML += " :: ShowOnly " + legendID + " : " + name + " show=" + show + ". shObjID: " + shObjID + "<br>";
    CloseIW();
                       
    if( legendID == "polygonlegend" ) {
        for (var i=0; i<myPolygon.length; i++) {
            if( polygonObjID[i] == shObjID ) {
                if (polygonColour[i] == name) {
                    if( show ) {
                        myPolygon[i].show();
                    } else {
                        myPolygon[i].hide();
                    }
                }
            }
        }
    } else {
        for (var i=0; i<gmarkers.length; i++) {
            if (gmarkers[i].iconName == name) {
                if( show ) {
                    if( gmarkers[i].isHidden() ) {
                        gmarkers[i].show();
                    }
                } else {
                    if( !gmarkers[i].isHidden() ) {
                        gmarkers[i].hide();
                    }
                }
            }
        }
    }
}

// Show and hide markers for selected categories
// http://econym.googlepages.com/example_categories.htm
function show(category,caption) {
        clearTimeout(showAllTimeoutID);

        if( category != '#all' ) { hide('#magnifier'); }
        
        CloseIW();
                        
        for (var i=0; i<gmarkers.length; i++) {
          if (category == '#all' || gmarkers[i].mycategory == category) {
            gmarkers[i].show();
          }
        }
        
        // Display the caption of the selected category
        document.getElementById("infoElementID").innerHTML = "<p>" + caption + "</p>";
}

function hide(category) {

        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory != category) {
            gmarkers[i].hide();
          }
        }
        map.closeInfoWindow();

        CloseIW();       

        showAllTimeoutID = setTimeout( "showAll()", CategoryTimeOut );
}

function showAll() {
   clearTimeout(showAllTimeoutID);
   if( ObjectID == FrontPageID ) {   
       show('#all','');
   }
   clearTimeout(showAllTimeoutID);
}

// Onload: solution run script at window.onload without 
// overriding other onload scripts
// http://www.tek-tips.com/faqs.cfm?fid=4862
function addOnloadEvent(fnc){
       if ( typeof window.addEventListener != "undefined" )
         window.addEventListener( "load", fnc, false );
       else if ( typeof window.attachEvent != "undefined" ) {
         window.attachEvent( "onload", fnc );
       }
       else {
         if ( window.onload != null ) {
           var oldOnload = window.onload;
           window.onload = function ( e ) {
             oldOnload( e );
             window[fnc]();
           };
         }
         else
           window.onload = fnc;
       }
}
     
addOnloadEvent(LoadMap);
addUnloadEvent(UnLoadMap);

function addUnloadEvent(fnc){
       if ( typeof window.addEventListener != "undefined" )
         window.addEventListener( "onunload", fnc, false );
       else if ( typeof window.attachEvent != "undefined" ) {
         window.attachEvent( "onunload", fnc );
       }
       else {
         if ( window.onunload != null ) {
           var oldOnunload = window.onunload;
           window.onunload = function ( e ) {
             oldOnunload( e );
             window[fnc]();
           };
         }
         else
           window.onunload = fnc;
       }
}

// ====================================================

function SetObjectID(objID, objName) {
    ObjectID = objID;
    
    if( objName )
        ObjectName = objName;
    else
        ObjectName = "";

    LegendObjShow[objID] = true;
    
    if( ObjectLoaded.indexOf(","+ObjectID+",") < 0 )
        ObjectLoaded += ObjectID + ",";

}

function SetMapCenter(myCenter, myZoom) {
   customZoom = myZoom;
   var tmpCenter = myCenter.split(",");
   customCLat=tmpCenter[0];
   customCLon=tmpCenter[1];
  
}

function SetMapDesign(a) {
   // 0: Default custom design
   // 1: Google map
   // 2: Google satellite
   // 3: Google terrain
   // 4: Google hybrid

   switch( parseInt(a) ) {
       case 1:
           MapDesign = G_NORMAL_MAP;
           break;
       case 2:
           MapDesign = G_SATELLITE_MAP;
           break;
       case 3:
           MapDesign = G_PHYSICAL_MAP;
           break;
       case 4:
           MapDesign = G_HYBRID_MAP;
           break;
       default:
           MapDesign = 0;
   }

   if( parseInt(a) > 0 )
       if( map ) {
           map.setMapType( MapDesign );
       }    
}

function SetMapCollection(a,b) {
    //alert( a + " " + b );    
    if( a && b ) {
        Collect[a] = b;
		  if( minObjID == 0 ) {
		      minObjID = a;
		  } else {
		      if( a < minObjID ) {
		          minObjID = a;
		      }
		  }	        
    }
    if( Collect.length - minObjID - 1 ) {
        LegendDDon = true;
    }
    
}

function GetPSTiles(a,b){
    var f = rootFolder + "kart512/"+(b)+"_"+a.x+"_"+(a.y)+".png";
    return f;
}

function UnLoadMap() {
   GUnload();
}

function LoadMap() {
        if (GBrowserIsCompatible()) {
        document.getElementById("map").style.backgroundImage = "url(" + rootFolder + "img/loading2.jpg)";
                    
        var startPoint = new GLatLng(centreLat, centreLon);
        var copyright = new GCopyright(1,
                              new GLatLngBounds(new GLatLng(-66.5132604, -90.0000000), new GLatLng(66.5132604, 90.0000000)),
                              0,
                              "<a href=\"http://www.nupi.no\">NUPI</a>");
        var copyrightCollection = new GCopyrightCollection("Norsk utenrikspolitisk institutt");
        copyrightCollection.addCopyright(copyright);

            if( ShowCustom && ( MapDesign == 0 ) ) 
            {
               //create a custom picture layer
              var pic_tileLayers = [ new GTileLayer(copyrightCollection, 0, 17)];
              pic_tileLayers[0].isPng = function() { return true; };
              pic_tileLayers[0].getOpacity = function() { return 1.0; };
              pic_tileLayers[0].getTileUrl = GetPSTiles;
              
              var pic_customMap = new GMapType(pic_tileLayers, new GMercatorProjection(18), "Pic",
                  {maxResolution:4, minResolution:1, errorMessage:"Data not available"});
              
              //Now create the custom map. Would normally be G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP
              map = new GMap2(document.getElementById("map"),{mapTypes:[pic_customMap]});

                map.addControl(new MyButton());
                map.addControl(new MyButton2());
                
                if( ObjectID > FrontPageID ) {
                    map.addControl(new MyLegend());
                }
            }
            else
            {
                map = new GMap2(document.getElementById("map"), {mapTypes: [MapDesign]} );
                map.addControl(new MyLegend());
            }
          
            map.addControl(new GSmallZoomControl());
            map.addControl(new GMapTypeControl());
          
          if( ShowCustom && ( MapDesign == 0 ) ) {
                map.setCenter(startPoint, initialZoom, pic_customMap);
          }
          else
          {
              map.setCenter(startPoint, initialZoom, MapDesign);
          }

            map.enableDoubleClickZoom();
    		map.enableContinuousZoom();
    		map.enableScrollWheelZoom();
    		map.disableDragging();
    		
            if( ObjectName )
                document.getElementById("infoElementID").innerHTML = "<p>" + ObjectName + "</p>"; 

            // Disable and enable dragging according to zoomlevel
            GEvent.addListener(map, "zoomend", function(oldzoom,zoom) {
                if( zoom == 1 ) {
                    for(var i=0;i<MyOverlay.length;i++) {
                        MyOverlay[i].style.display="block";
                    }
                    map.setCenter(new GLatLng(centreLat, centreLon));
                    map.disableDragging();
                    ShowHide('markerlegend');
                } else {
                    if( oldzoom == 1 ) {
                        map.enableDragging();
                        for(var i=0;i<MyOverlay.length;i++) {
                            MyOverlay[i].style.display="none";
                        }
  	        	    }
  	        	    ShowHide('markerlegend');
                }
                
            }); 
            
            // Add a move listener to restrict the bounds range
            GEvent.addListener(map, "moveend", function() {
                //ShowHide('markerlegend');
                
                if( bubble ) {
                    bubble.hide();
                }
                if( bWaitText ) {
                    setTimeout( "bubble.openOnMap(bWaitPoint,bWaitText)", 100 );
                }
            });

            GEvent.addListener(map, "dragend", function() {
                //ShowHide('markerlegend');
            });
            
            
            // Close any infowindow (bubble) when map is clicked
            GEvent.addListener(map, "click", function() {
                CloseIW();
                ShowHide('markerlegend');
            }); 

            GEvent.addListener(map, "mouseover", function() {
                clearTimeout(showAllTimeoutID);
            }); 

            GEvent.addListener(map, "mouseout", function() {
                showAllTimeoutID = setTimeout( "showAll()", CategoryTimeOut );                
            }); 


          LogDiv = document.getElementById("logDiv");

          if( ObjectID > FrontPageID ) {
              getPolygonLegend();
          }
          
          displayMarkers();
          
          if( ObjectID > FrontPageID ) {
              displayPolygons();
          }


          // Check if the map should be zoomed in and panned to custom position
          if( customZoom > 0 ) {
              if( customZoom != initialZoom ) {
                  //alert( "Changing zoom from " + initialZoom + " to " + customZoom );
                  for(var i=initialZoom;i<customZoom;i++) {
                      map.zoomIn();                 
                  }
               }
          }
          if( customCLat != 0 && customCLon != 0 ) {
              map.setCenter(new GLatLng(customCLat, customCLon));
          }
          
          
        } else {
          document.getElementById("map").innerHTML = "<p>Aktiver støtte for javascript i nettleseren for å vise kartet.</p>";
        }
} // function LoadMap