var map;
var mapId; //jinam
var pointsColl = new Array();
var pointsCollLen = 0;
var iconsColl = new Array(); //local
var maxPoints = 0;
var actPoints = 0; //jinam

var openingNew = false;       // when openingNew is true, "closeinfoevent" is not processed

// externally called
function InitMapScripts() {
  window.onload = load;
}

function PointsCollPush(point, refresh) {
  pointsColl[pointsCollLen] = point;
  
  if(pointsCollLen < maxPoints) {
    point.setHiddenPay(false, refresh);
  }
  else {
    point.setHiddenPay(true, refresh);
  }

  pointsCollLen++;
  
  UpdateActPointsCounter();
}

function PointsCollRemove(index, refresh) {
  pointsColl[index] = 0;
  for(i = index; i < pointsCollLen; i++) {
    if(i+1 >= pointsCollLen)
      pointsColl[i] = 0;
    else
      pointsColl[i] = pointsColl[i + 1];
      
    if((i == maxPoints-1) && (pointsColl[i])) {
      pointsColl[i].setHiddenPay(false, refresh);
    }
  }
  
  pointsCollLen--;
  
  UpdateActPointsCounter();
}

function UpdateActPointsCounter()
{
  var actPointsCounter = document.getElementById('actPointsCounter');
  if(actPointsCounter)
  {
    actPointsCounter.innerHTML = pointsCollLen;
  }
}

function UpdateMaxPointsCounter()
{
  var maxPointsCounter = document.getElementById('maxPointsCounter');
  if(maxPointsCounter)
  {
    maxPointsCounter.innerHTML = maxPoints;
  }
}

function UpdatePointsCounters()
{
  UpdateActPointsCounter();
  UpdateMaxPointsCounter();
}

function _createIcons()
{
  _createIcon(0, '../img/icons/empty.png', '../img/icons/shadow.png', 'Prázdné místo', '../img/icons/thumbs/empty.png');
  _createIcon(1, '../img/icons/accept.png', '../img/icons/shadow.png', 'OK', '../img/icons/thumbs/accept.png');
  _createIcon(2, '../img/icons/building.png', '../img/icons/shadow.png', 'Budova', '../img/icons/thumbs/building.png');
  _createIcon(3, '../img/icons/car.png', '../img/icons/shadow.png', 'Auto', '../img/icons/thumbs/car.png');
  _createIcon(4, '../img/icons/cart.png', '../img/icons/shadow.png', 'Nákupní vozík', '../img/icons/thumbs/cart.png');
  _createIcon(5, '../img/icons/cog.png', '../img/icons/shadow.png', 'Kolečko', '../img/icons/thumbs/cog.png');
  _createIcon(6, '../img/icons/computer.png', '../img/icons/shadow.png', 'Počítač', '../img/icons/thumbs/computer.png');
  _createIcon(7, '../img/icons/cup.png', '../img/icons/shadow.png', 'Občerstvení', '../img/icons/thumbs/cup.png');
  _createIcon(8, '../img/icons/emoticon_smile.png', '../img/icons/shadow.png', 'Úsměv', '../img/icons/thumbs/emoticon_smile.png');
  _createIcon(9, '../img/icons/emoticon_unhappy.png', '../img/icons/shadow.png', 'Zamračený', '../img/icons/thumbs/emoticon_unhappy.png');
  _createIcon(10, '../img/icons/flag_blue.png', '../img/icons/shadow.png', 'Vlaječka modrá', '../img/icons/thumbs/flag_blue.png');
  _createIcon(11, '../img/icons/flag_green.png', '../img/icons/shadow.png', 'Vlaječka zelená', '../img/icons/thumbs/flag_green.png');
  _createIcon(12, '../img/icons/flag_red.png', '../img/icons/shadow.png', 'Vlaječka červená', '../img/icons/thumbs/flag_red.png');
  _createIcon(13, '../img/icons/flag_yellow.png', '../img/icons/shadow.png', 'Vlaječka žlutá', '../img/icons/thumbs/flag_yellow.png');
  _createIcon(14, '../img/icons/heart.png', '../img/icons/shadow.png', 'Srdce', '../img/icons/thumbs/heart.png');
  _createIcon(15, '../img/icons/help.png', '../img/icons/shadow.png', 'Otazník', '../img/icons/thumbs/help.png');
  _createIcon(16, '../img/icons/house.png', '../img/icons/shadow.png', 'Domeček', '../img/icons/thumbs/house.png');
  _createIcon(17, '../img/icons/money_euro.png', '../img/icons/shadow.png', 'Euro', '../img/icons/thumbs/money_euro.png');
  _createIcon(18, '../img/icons/overlays.png', '../img/icons/shadow.png', 'Formulář', '../img/icons/thumbs/overlays.png');
  _createIcon(19, '../img/icons/sport_golf.png', '../img/icons/shadow.png', 'Golf', '../img/icons/thumbs/sport_golf.png');
  _createIcon(20, '../img/icons/sport_racquet.png', '../img/icons/shadow.png', 'Sportovní raketa', '../img/icons/thumbs/sport_racquet.png');
  _createIcon(21, '../img/icons/user.png', '../img/icons/shadow.png', 'Panáček', '../img/icons/thumbs/user.png');
  _createIcon(22, '../img/icons/user_female.png', '../img/icons/shadow.png', 'Panenka', '../img/icons/thumbs/user_female.png');
  _createIcon(100, '../img/icons/exclamation.png', '../img/icons/shadow.png', 'Vykřičník', '../img/icons/thumbs/exclamation.png');
}

function _createIcon(index, imgPath, shadowPath, desc, thumbPath)
{
  var icon = new GIcon(G_DEFAULT_ICON);
  icon.image = imgPath;
  icon.shadow = shadowPath;
  icon.iconSize = new GSize(22, 28);
  icon.shadowSize = new GSize(36, 28);
  icon.imageMap = [7,1,15,1,17,2,19,3,20,4,21,6,21,15,20,17,20,17,19,18,18,20,17,22,16,24,15,26,14,31,13,35,12,36,11,36,10,35,9,31,8,27,7,24,6,23,5,21,4,19,3,18,2,16,1,14,1,7,2,5,3,4,4,3,5,2];
  icon.iconAnchor = new GPoint(11, 28);
  icon.infoWindowAnchor = new GPoint(11, 28);
  icon.transparent = "../img/icons/transparentIcon.png";
  icon.desc = desc;
  icon.thumbnail = thumbPath;
  iconsColl[index] = icon;
}

function _copyIcon(oldIcon, newIcon)    // TODO: Delete: not used
{
//  oldIcon.image = newIcon.image;
}

// function Point(id, title, lat, lng, type, desc, url, urlTitle, address, validUntil, newpoint)
function Point(id, title, lat, lng, type, desc, url, urlTitle, address, validUntil, hiddenPay)
{
  this.id = id;
  this.title = title;
  this.lat = lat;
  this.lng = lng;
  this._type = type;
  this.desc = desc;
  this.url = url;
  this.urlTitle = urlTitle;
  this.address = address;
  this.validUntil = validUntil;
  this._hiddenPay = hiddenPay;
  
  this.setType = _m_pointSetType;
  this.setHiddenPay = _m_pointSetHiddenPay;
  this.updateMarker = _m_pointUpdateMarker;
  
  var resultType = this._type;
  if(this._hiddenPay)
    resultType += 100;

  var icon = iconsColl[resultType];
  this.marker = new GMarker(new GLatLng(this.lat, this.lng), icon);

//  this.setType(type);
//  this.setHiddenPay(hiddenPay);

//  this.marker = new GMarker(new GLatLng(lat, lng));
//  if (newpoint)
//  {  
//    // Create our "tiny" marker icon
//    var icon = new GIcon();
//    icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
//    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
//    icon.iconSize = new GSize(12, 20);
//    icon.shadowSize = new GSize(22, 20);
//    icon.iconAnchor = new GPoint(6, 20);
//    icon.infoWindowAnchor = new GPoint(5, 1);

//    // display icon
//    this.marker = new GMarker(new GLatLng(lat, lng), icon); 
//  }
//  else
//  {
//    // display point
//    this.marker = new GMarker(new GLatLng(lat, lng)); 
//  }
}

function _m_pointSetType(type, refresh)
{
  this._type = type;
  if(refresh)
    this.updateMarker();
}

function _m_pointSetHiddenPay(hiddenPay, refresh) {
  this._hiddenPay = hiddenPay;
  if(refresh)
    this.updateMarker();
}

function _m_pointUpdateMarker()
{
  var resultType = this._type;
  if(this._hiddenPay)
    resultType = 100;

  var icon = iconsColl[resultType];
//    var oldIcon = this.marker.getIcon();
//    copyIcon(oldIcon, icon);
  _removePoint(this);
  this.marker = new GMarker(new GLatLng(this.lat, this.lng), icon);

  addPageSpecificPointEvent(this);
  map.addOverlay(this.marker);
}



// Gets index of point with the specified ID
function _getIndex(id)
{
  for (var i = 0; i < pointsCollLen; i++)
  {
    if (pointsColl[i].id == id)
    {
      return i;
    }
  }
  
  return -1;
}

function showInfoWindowPoint(point)
{
  openingNew = true;        // closeinfowindow event is not processed
  
  if (point)
  {
    var desc = composeInfoWindow(point);
    if (desc == "")
      desc = point.title;
      
    map.openInfoWindowHtml(new GLatLng(point.lat, point.lng), desc);
    var infowindow = map.getInfoWindow();
    if (infowindow != null)
    {
      GEvent.addListener(infowindow, "closeclick", function()
      {
        closeInfoWindow();
      });
    }

/*    
    // set select to the selected point
    var selector = document.getElementById("select_point");
    if (selector)
    {
      for (var i = 0; i < selector.length; i++)
      {
        if (selector.options[i].value == id)
        {
          selector.selectedIndex = i;
          break;
        }
      }
    }
    */
  }
}

// Displays info window for the point with id
function showInfoWindow(id)
{
  openingNew = true;        // closeinfowindow event is not processed
  
  if (id != -1)
  {
    var index = _getIndex(id);
    if (index != -1)
    {
//      var desc = "<div class='pointTitle'>" + pointsColl[index].title + "</div>" + pointsColl[index].desc;
      var point = pointsColl[index];
      var desc = composeInfoWindow(point);
      if (desc == "")
        desc = point.title;
      map.openInfoWindowHtml(new GLatLng(point.lat, point.lng), desc);
      var infowindow = map.getInfoWindow();
      if (infowindow != null)
      {
        GEvent.addListener(infowindow, "closeclick", function()
        {
          closeInfoWindow();
        });
      }
    }
    
    // set select to the selected point
    var selector = document.getElementById("select_point");
    if (selector)
    {
      for (var i = 0; i < selector.length; i++)
      {
        if (selector.options[i].value == id)
        {
          selector.selectedIndex = i;
          break;
        }
      }
    }
  }
}

// Closes info window
function closeInfoWindow()
{
  map.closeInfoWindow();
}

function displayTemporaryPoint(point) {
  var marker = point.marker;
  map.addOverlay(marker);
}

function hideTemporaryPoint(point) {
  var marker = point.marker;
  map.removeOverlay(marker);
}

// Shows one point
//function displayPoint(id, title, lat, lng, type, desc)
function displayPoint(point)
{
  var marker = point.marker;
  addPageSpecificPointEvent(point);
  map.addOverlay(marker);
  
  // add to combobox
  var combo = document.getElementById("select_point");
  if (combo)
  {
    var eloption = document.createElement('option');
    eloption.text = decodeTextRender(point.title);
    eloption.value = point.id;
    point.selectOption = eloption;

    try {
      combo.add(eloption, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      combo.add(eloption); // IE only
    }
  }
}

function _removePoint(point)
{
  var marker = point.marker;
  map.removeOverlay(marker);
}

// Shows last point in the array
function displayLastPoint() {         // TODO: Delete? Not used
  var index = pointsCollLen - 1;
  if(index < 0)
    return false;
    
  var point = pointsColl[index];
//  displayPoint(point.id, point.title, point.lat, point.lng, point.type, point.desc);
  displayPoint(point);
}

// Show all points from the pointsColl array
function _showPoints()
{
  map.clearOverlays();
  for (var i = 0; i < pointsCollLen; i++)
  {
    var point = pointsColl[i];
//    displayPoint(point.id, point.title, point.lat, point.lng, point.type, point.desc);
    displayPoint(point);
    point.updateMarker();
  }
}

function _moveEnded()
{
  // TODO: AJAX code will be here
}

function _infoWindowOpened()
{
  openingNew = false;       // closeinfowindow event will be processed again
}

function _infoWindowClosed()
{
  if (openingNew == false)
  {
    var selector = document.getElementById("select_point");
    if(selector) {
      selector.selectedIndex = 0;
    }
  }
}

// externally called
function pointSelected()
{
  var selector = document.getElementById("select_point");
  if (selector)
  {
    var index = selector.selectedIndex;
    if (index > 1)
    {
      for(i = 0; i < pointsCollLen; i++) {
        if(!pointsColl[i]) {
          continue;
        }
        
        var point = pointsColl[i];
        if(point.id == selector.options[index].value) {
          GEvent.trigger(point.marker, 'click');
        }
      }
//      showInfoWindow(selector.options[index].value);
    }
  }
}

// externally called
function load() {
  if (GBrowserIsCompatible()) {
    // set size of map div
    setMapDiv();
    
    map = new GMap2(document.getElementById("map"));
    
    // enable double click to zoom map
//    map.enableDoubleClickZoom();
    map.enableContinuousZoom();

    // display controls
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    
    GEvent.addListener(map, "moveend", function() {
      _moveEnded();
    });
    GEvent.addListener(map, "infowindowopen", function() {
      _infoWindowOpened();
    });
    GEvent.addListener(map, "infowindowclose", function() {
      _infoWindowClosed();
    });
    
    _createIcons();
    
    // The following function must be implemented in HTML code (typically generated by the server)
    // Also variables initLat, initLng, initZoom can be set
    setPoints();
    
    // setMap
    setMap();
    
    // display all the points
    _showPoints();
    
    // sets page-specific events, etc.
    pageSpecificInit();
  }
}

function stripTags(oldText)
{
  var newText = oldText.replace(/</g, '&lt;');
  newText = newText.replace(/>/g, '&gt;');
  return newText;
}

function encodeText(oldText)
{
//  newText = new String(oldText);
  newText = stripTags(oldText);
  newText = newText.replace('\r', '');
  newText = newText.replace('\n', '{NL}');
  return newText;
}

function decodeTextEdit(oldText)
{
//  newText = new String(oldText);
  newText = stripTags(oldText);
  newText = newText.replace('\r', '');
  newText = newText.replace(/\{NL\}/g, '\n');
  return newText;
}

function decodeTextRender(oldText)
{
//  newText = new String(oldText);
  newText = stripTags(oldText);
  newText = newText.replace('\r', '');
  newText = newText.replace(/\{NL\}/g, '<br />');
  return newText;
}

