// 
function PopupMessage(id) { 
  Popup("app_imex/help.asp?msg="+id,"msg",300,300);
  return false;
}

// 
function PopupHelp(id,anchor,w,h) { 
  var pop = new PopupWindow(); 
  if (typeof(w) == 'undefined') w = 400; 
  if (typeof(h) == 'undefined') h = 300; 
  pop.setSize(w,h); 
  pop.offsetX = -w-24; 
  pop.offsetY = 24;
  pop.autoHide();
  pop.setUrl("app_imex/help.asp?msg="+id);  
  pop.setWindowProperties("scrollbars=1")  
  pop.showPopup(anchor)
  return false;
}

// shows a template in a popup window
function PopupTpl(tpl,v1,v2,v3) { 
  var pop = new PopupWindow(); var w = 450; var h = 300; 
  pop.setSize(w,h); 
  off = getCenter(w,h);
  pop.offsetX = off.x;
  pop.offsetY = off.y;
  pop.autoHide();
  pop.setUrl("app_imex/popup.asp?mod=DS&tpl="+tpl+"&v1="+v1+"&v2="+v2+"&v3="+v3);  
  pop.setWindowProperties("scrollbars=1")  
  pop.showPopup("popupanchor")
}

//------------------------------------------------------------------------------
// toggle an element using scriptaculous Effects and store the actual state in a cookie
//------------------------------------------------------------------------------
var sauToggler = {
  init : function(id1,id2,on) {
    var btn = $(id1);
    var cnt = $(id2);
    on = typeof(on) == 'undefined' ? true : on;
    if (btn) { 
      btn.__target = cnt;
      btn.onclick = sauToggler.ontoggle; }
	  if (cnt) {
      var sta = Cookie.get('ToggleState'+id2);
    	sta = (sta != null && sta != '') ? sta : ((on) ? 'on' : 'off');
      if (sta == 'on') { cnt.style.display = 'block' } else { cnt.style.display = 'none' }
      Cookie.set('ToggleState'+cnt.id,sta);
		}
	  return false;
  },

  ontoggle : function() {
    var cnt = this.__target;
	  if (cnt) {
      if (cnt.style.display != 'none') { 
        try { Effect.Fade(cnt,{duration: 0.25, fps: 50}); } catch(e) { cnt.style.display = "none"; }
        Element.addClassName(this,'off');
        Element.removeClassName(this,'on');
        Cookie.set('ToggleState'+cnt.id,'off');
      } else { 
        try { Effect.Appear(cnt,{duration: 0.25, fps: 50}); } catch(e) { cnt.style.display = "block"; }
        Element.addClassName(this,'on');
        Element.removeClassName(this,'off');
        Cookie.set('ToggleState'+cnt.id,'on');
      }
	  }
	  return false;
  }
}

//------------------------------------------------------------------------------
// ajax functions
//------------------------------------------------------------------------------
window.onload = function() {
  document.onmousedown = mDown;
}

function mDown(e) {
  /* get the mouse button and coordinates */
  b = (document.all) ? event.button : e.which;
  x = (document.all) ? event.clientX : e.clientX;
  y = (document.all) ? event.clientY : e.clientY;
  if (b==1) { /* left mouse button was pressed */
    CtxPopup.click(x,y); 
  }
}

function getElementDimensions(id) {
  id = $(id);
  dx = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
  dy = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
  co = Position.cumulativeOffset(id);
  co[0] = co[0] || parseInt(Element.getStyle(id,'left'));
  co[1] = co[1] || parseInt(Element.getStyle(id,'top'));
  ro = Position.realOffset(id);
  dim = Element.getDimensions(id);
  return {left: co[0], top: co[1], 
          screenleft: co[0]-dx, screentop: co[1]-dy, 
          width: dim.width, height: dim.height, 
          dx: dx, dy: dy};
}

function setElementPosition(id,x,y) {
  id = $(id);
  ih = (window.innerHeight) ? window.innerHeight : document.body.clientHeight;
  iw = (window.innerWidth) ? window.innerWidth : document.body.clientWidth;
  id.style.left = -1000; id.style.top = -1000; id.style.display = "block"; // show the element
  var dim = getElementDimensions(id);
  id.style.display = "none"; // hide the element
  if (x+dim.width+15 <= iw) { id.style.left = (x+10+dim.dx)+"px"; } else { id.style.left = (x-dim.width-10+dim.dx)+"px"; }  
  if (y+dim.height <= ih) { id.style.top = (y+10+dim.dy)+"px"; } else { id.style.top = (y-dim.height-10+dim.dy)+"px"; }  
}  

/*----------------------------------------------------------------------------*/
var CtxPopup = {
  show: function(id,cnt,x,y) {
    id = $(id); el = $('ctxpopup');
    el.innerHTML = cnt;
    id.__content = cnt;
    setElementPosition(el,x,y);          
    Effect.Appear("ctxpopup",
      { afterUpdate: function(e) { $('ctxpopup').style.display = "block"; },
        duration: 0.4,
        fps: 50
      }
    );
  },
  hide: function() {
    el = $('ctxpopup');
    el.style.display = "none"; // hide the element    
  },
  showcached: function(id,x,y) {
    id = $(id); el = $('ctxpopup');
    if (id.__content) {
      CtxPopup.show(id,id.__content,x,y);
      return true;
    } else {
      return false;
    }  
  },
  click: function(x,y) {
    el = $('ctxpopup');
    dim = getElementDimensions(el);
    if (Element.visible(el) && 
        ((x < dim.screenleft) || 
         (x > (dim.screenleft+dim.width)) || 
         (y < dim.screentop) || 
         (y > (dim.screentop+dim.height)))) {
      el.innerHTML = "";
      el.style.display = "none"; 
    }
    el.style.__mouseleft = x; // store the mose coordinates in the element
    el.style.__mousetop = y;
  }
}  

/*----------------------------------------------------------------------------*/
function execAjax(cmd,para,frm,suc) {
  if (typeof(frm) != 'undefined') { // create the parameters from the forms fields
    p = Form.serialize(frm)
  }
  new Ajax.Request(
    "app_imex/xt_obj_ajax.asp?cmd="+cmd+"&"+para,
    {
      method: 'post',
      postBody: p,
      onSuccess: function(r) {
        if (typeof(suc) != 'undefined') alert(r.responseText+': '+suc); 
      },
      onFailure: function(r) {
        alert("execAjax failed\n\nCommand "+cmd+" returned code "+r.status+" ("+r.statusText+")");
      }
    }
  );
}

/*----------------------------------------------------------------------------*/
function getCalendar(id,yy,mm) {
  var dat = new Date();
  yy = typeof(yy) != 'undefined' && yy != '' ? yy : dat.getYear();
  mm = typeof(mm) != 'undefined' && mm != '' ? mm : dat.getMonth()+1;
  yy = yy < 1000 ? yy+1900 : yy;
  new Ajax.Updater(
    "ajaxCal",
    "app_imex/xt_obj_ajax.asp?cmd=GETCALENDAR&id="+id+"&year="+yy+"&month="+mm
  );
}
function updateCalendar(id,yy,mm) {
  getCalendar(id,yy,mm);
}
function selectDate(d) {
  $('dat_dsiStartDate').value = d; $('dat_dsiStartDate').form.submit();
}

/*----------------------------------------------------------------------------*/
function getPopCalendarExec(id,yy,mm) {
  var dat = new Date();
  var dim = getElementDimensions(id);
  yy = typeof(yy) != 'undefined' && yy != '' ? yy : dat.getYear();
  mm = typeof(mm) != 'undefined' && mm != '' ? mm : dat.getMonth()+1;
  yy = yy < 1000 ? yy+1900 : yy;
  new Ajax.Request(
    "app_imex/xt_obj_ajax.asp?cmd=GETPOPCALENDAR&id="+$(id).id+"&year="+yy+"&month="+mm,
    {
      method: 'get',
      onSuccess: function(r) {
        CtxPopup.show(id,r.responseText,dim.screenleft,dim.screentop+dim.height);
      }
    }
  );
}
function getPopCalendar(id,fld) {
  dat = ($(fld).value != '') ? parseDate($(fld).value,true) : new Date();
  id.id = "cal"+fld;
  id.__fldid = $(fld);
  yy = dat.getYear(); mm = dat.getMonth()+1;
  getPopCalendarExec(id.id,yy,mm);
}
function updatePopCalendar(id,yy,mm) {
  getPopCalendarExec(id,yy,mm);
}

/*----------------------------------------------------------------------------*/
function ac(fld,div,sql) {
  new Ajax.Autocompleter(
    fld,
    div,
    "app_imex/xt_obj_ajax.asp?cmd=AUTOCOMPLETE&fld="+fld+"&sql="+sql,
    {
      frequency: 0.1,
      choices: 10,
      ignoreCase: true,
      paramName: 'content'
    }
  );
}

//------------------------------------------------------------------------------
// toggle an element using scriptaculous Effects and store the actual state in a cookie
//------------------------------------------------------------------------------

function addScript(sURL) {
  var headID = document.getElementsByTagName("head")[0];         
  var newScript = document.createElement('script');
  newScript.type = 'text/javascript';
  newScript.src = sURL;
  headID.appendChild(newScript);
}

var imexMap = {
  lat: 0.0,
  lng: 0.0,
  zo: 16,
  markerType: 0,
  id: 'map',
  navid: 'mapnav',
  map: null,
  mgr: null,
  geocoder: null,
  marker: null,
  enablePopup: true,
  
  fldLat: null,
  fldLng: null,
  fldAcc: null,
  
  markers: null,
  setMarkers: null, // function to set markers
  updateMarker: null, // function to update marker position
  actID: new Object(),
  actCnt: 'CH',
  actTyp: 'all',
  actMod: '',
  actFlt: '',
  
  center: null,
  
  // load the map
  load : function() {
    if (document.getElementById(imexMap.id)) {
      if (GBrowserIsCompatible()) {
        if (!imexMap.map) { // create the map object
          imexMap.map = new GMap2(document.getElementById(imexMap.id));
          var size = imexMap.map.getSize();
          if (size.width <= 400) { // small map
            imexMap.map.addControl(new GSmallMapControl());
            imexMap.map.addControl(new GMapTypeControl());
          } else { // large map
            imexMap.map.addControl(new GLargeMapControl());
            imexMap.map.addControl(new GMapTypeControl());
            imexMap.map.addControl(new GOverviewMapControl(new GSize(150,150)));
          }
        }
        imexMap.map.enableDoubleClickZoom();

        imexMap.markers = new Array();
//        if (!imexMap.mgr) { // create the marker manager object
//          var mgrOptions = { borderPadding: 50, maxZoom: 10, trackMarkers: true };
//          imexMap.mgr = new GMarkerManager(imexMap.map);
//        }
        
//        if (imexMap.lat != 0.0 && imexMap.lng != 0.0) {
          var point = new GLatLng(imexMap.lat,imexMap.lng)
          try { imexMap.map.setCenter(point,imexMap.zo); } catch(e) { }
          imexMap.addMarker(point,imexMap.markerType,0,true,0,0);
          if (imexMap.setMarkers) imexMap.setMarkers();
//        }
      }
    }
  },
  
  unload : function() {
    if (imexMap.map) {
      imexMap.clearMarkers();
      // unload the map
      GUnload();
    }
  },
  
  initForm: function(idlat,idlng,idacc) {
    fldLat = document.getElementById(idlat);
    fldLng = document.getElementById(idlng);
    fldAcc = document.getElementById(idacc); 
  },

  getDistance: function(pnt) {
    if (imexMap.center) {
      lat1 = pnt.y/57.2958; lat2 = imexMap.center.y/57.2958;
      lng1 = pnt.x/57.2958; lng2 = imexMap.center.x/57.2958;
      dist = 6378.7*Math.acos(Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos(lng2-lng1));
      return dist*1000;
    }
  },
  
  createNavigator: function(cnt,typ,id) {
    var para = '';
    if (cnt) { para += 'cnt='+cnt; imexMap.actCnt = cnt; }
    if (typ) { para += '&typ='+typ; imexMap.actTyp = typ; }
    if (id) { para += '&id='+id; }
    GDownloadUrl(
      'app_imex/xt_obj_ajax.asp?cmd=GETBREADCRUMBS&'+para,
      function(dat,res) {  
        var arr = dat.split('&&')
        if (document.getElementById(imexMap.navid)) {
          document.getElementById(imexMap.navid).innerHTML = arr[0];
        }
        if (arr[1]) { // syncronize actID
          var arrID = arr[1].split(';')
          if (arrID[0]) imexMap.actID['reg'] = arrID[0]
          if (arrID[1]) imexMap.actID['zip'] = arrID[1]
          if (arrID[2]) imexMap.actID['obj'] = arrID[2]
        }
      }  
    )
  },
  
  createSmallIcon: function(icon,color) {
    icon.image = "app_imex/images/markers/mm_20_"+color+".png"; 
    icon.shadow = "app_imex/images/markers/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,2);
  },
  
  createBigIcon: function(icon,name) {
    icon.image = "app_imex/images/markers/"+name+".png"; 
    icon.shadow = "app_imex/images/markers/shadow50.png";    
    icon.iconSize = new GSize(20,34);
    icon.shadowSize = new GSize(37,34);
    icon.iconAnchor = new GPoint(10,34);
    icon.infoWindowAnchor = new GPoint(10,2);
  },
  
  createIcon: function(typ,styp1,styp2) {
    // create the icon for the marker
    var icon = new GIcon(); 
    switch (typ) {
      case '0':  imexMap.createSmallIcon(icon,'white'); break; // not defined

      case '10': imexMap.createSmallIcon(icon,'green'); break; // Schule
      case '11': imexMap.createSmallIcon(icon,'green'); break; // Kindergarten
      case '12': imexMap.createSmallIcon(icon,'green'); break; // Primarschule
      case '13': imexMap.createSmallIcon(icon,'green'); break; // Oberstufe

      case '20': imexMap.createSmallIcon(icon,'blue'); break; // Shopping

      case '30': imexMap.createSmallIcon(icon,'yellow'); break; // Verwaltung
      case '31': imexMap.createSmallIcon(icon,'yellow'); break; // Post

      case '40': imexMap.createSmallIcon(icon,'red'); break; // Verkehr
      case '41': imexMap.createSmallIcon(icon,'red'); break; // Bahnhof
      
      case 'reg': if (styp1>0 && styp2>0) { imexMap.createBigIcon(icon,'012_037'); break; }
                  if (styp1>0) { imexMap.createBigIcon(icon,'037'); break; }
                  if (styp2>0) { imexMap.createBigIcon(icon,'012'); break; }
                  imexMap.createBigIcon(icon,'216'); break; 
      case 'zip': if (styp1>0 && styp2>0) { imexMap.createBigIcon(icon,'012_037'); break; }
                  if (styp1>0) { imexMap.createBigIcon(icon,'037'); break; }
                  if (styp2>0) { imexMap.createBigIcon(icon,'012'); break; }
                  imexMap.createBigIcon(icon,'216'); break; 
      case 'obj': if (styp1>0 && styp2>0) { imexMap.createBigIcon(icon,'012_037'); break; }
                  if (styp1>0) { imexMap.createBigIcon(icon,'037'); break; }
                  if (styp2>0) { imexMap.createBigIcon(icon,'012'); break; }
                  imexMap.createBigIcon(icon,'216'); break; 
      
      default: imexMap.createSmallIcon(icon,'black'); break; 
    }
    return icon;
  },

  // remove all markers
  clearMarkers : function() {
    imexMap.map.closeInfoWindow();
    if (imexMap.markers) {
      // remove the markers
      while (imexMap.markers.length > 0) { 
        var marker = imexMap.markers.pop(); 
        GEvent.clearListeners(marker,"dragstart"); 
        GEvent.clearListeners(marker,"dragend"); 
        GEvent.clearListeners(marker,"click"); 
        GEvent.clearListeners(marker,"mouseover"); 
        GEvent.clearListeners(marker,"dblclick"); 
        marker = null;
      } 
      imexMap.map.clearOverlays(); 
    }
  },
    
  // load a set of markers
  loadMarkers: function(cnt,typ,id,mod,flt) {
    imexMap.center = null;
    var para = '';
    if (!cnt) { cnt = imexMap.actCnt; }
    if (!typ) { typ = imexMap.actTyp; }
    if (!id) { if (imexMap.actID[typ]) { id = imexMap.actID[typ]; }}
    if (!mod) { mod = imexMap.actMod; }
    if (!flt) { flt = imexMap.actFlt; }

    if (cnt) { para += 'cnt='+cnt; imexMap.actCnt = cnt; }
    if (typ) { para += '&typ='+typ; imexMap.actTyp = typ; }
    if (id) { para += '&id='+id; }
    if (mod) { para += '&mod='+mod; imexMap.actMod = mod; }
    if (flt) { para += '&flt='+flt; imexMap.actFlt = flt; }
    
    if (typ == 'obj' && window.name != 'objdet' && imexMap.enablePopup) { // open a popup window
      win = open('objectdetail.asp?id='+id,'objdet','width=800, height=600, scrollbars=yes');
      return;
    }
    imexMap.clearMarkers();
    
    GDownloadUrl(
      'app_imex/xt_obj_ajax.asp?cmd=GETMARKERSXML&'+para,
      function(dat,res) {  
        var xml = GXml.parse(dat);  
        var markers = xml.documentElement.getElementsByTagName("marker");  
        var bounds = new GLatLngBounds();
        
        // loop over all entries to get bounds and center
        for (var i = 0; i < markers.length; i++) {    
          var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),                            
                                  parseFloat(markers[i].getAttribute("lng")));    
          bounds.extend(point);
          if (markers[i].getAttribute("main") != '') { imexMap.center = point; }
        }

        // loop over all entries to define the markers
        for (var i = 0; i < markers.length; i++) {    
          var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),                            
                                  parseFloat(markers[i].getAttribute("lng")));    
          imexMap.addMarker(point,markers[i].getAttribute("typ"),
                                  markers[i].getAttribute("id"),
                                 (markers[i].getAttribute("mod") != ''),
                                  parseInt(markers[i].getAttribute("cntr")),
                                  parseInt(markers[i].getAttribute("cntb")));
        }
        imexMap.map.setZoom(imexMap.map.getBoundsZoomLevel(bounds));    
        if (imexMap.center) {
          try { imexMap.map.setCenter(imexMap.center); } catch(e) { }
        } else {
          try { imexMap.map.setCenter(bounds.getCenter()); } catch(e) { }
        }
        if (id) { imexMap.actID[typ] = id; }
        
        imexMap.createNavigator(cnt,typ,id);
        imexMap.loadTable(cnt,typ,id,flt);
      }
    );
  },

  // add a marker to the markers array
  addMarker: function(pnt,typ,id,drg,styp1,styp2) {
    // create the icon for the marker
    var icon = imexMap.createIcon(typ,styp1,styp2); 
    if (drg) { // create a draggable marker
      var marker = new GMarker(pnt,{icon: icon,draggable: true});
      // add events to the marker
      GEvent.addListener(marker,"dragstart",function() {
        imexMap.map.closeInfoWindow();
      });
      GEvent.addListener(marker,"dragend",function() {
        if (imexMap.updateMarker) {
          var point = marker.getPoint();
          imexMap.updateMarker(point,-1);
        }
//        fldLat.value = point.y;
//        fldLng.value = point.x;
//        fldAcc.value = -1;      
      });
    } else {
      var marker = new GMarker(pnt,{icon: icon});
//      GEvent.addListener(marker,"click",function() {
//        // get the data for the info window
//        GDownloadUrl(
//          'app_imex/xt_obj_ajax.asp?cmd=GETINFOWINDOW&typ='+typ+'&id='+id,
//          function(dat,res) {
//            if (marker.__distance) { dat += '<br>Distanz: '+marker.__distance }
//            if (typ == 'obj') { dat += '<br><a href="app_imex/xt_obj_ajax.asp?cmd=GETKML&typ='+typ+'&id='+id+'">Anzeige in Google Earth</a>' }
//            marker.openInfoWindowHtml(dat,{maxWidth: 400});      
//          }
//        );
//      });
      GEvent.addListener(marker,"mouseover",function() {
        // get the data for the info window
        GDownloadUrl(
          'app_imex/xt_obj_ajax.asp?cmd=GETINFOWINDOW&cnt='+imexMap.actCnt+'&typ='+typ+'&id='+id+'&flt='+imexMap.actFlt,
          function(dat,res) {
            if (marker.__distance) { dat += '<br>Distanz: '+marker.__distance }
            if (typ == 'obj') { dat += '<br><a href="app_imex/xt_obj_ajax.asp?cmd=GETKML&typ='+typ+'&id='+id+'">Anzeige in Google Earth</a>' }
            marker.openInfoWindowHtml(dat,{maxWidth: 400});      
          }
        );
        if ($('cell'+id)) { Element.addClassName('cell'+id,'active'); }
      });
      GEvent.addListener(marker,"mouseout",function() {
        if ($('cell'+id)) { Element.removeClassName('cell'+id,'active'); }
      });
    }        
    GEvent.addListener(marker,"click",function() {
      imexMap.loadMarkers('',typ,id);
    });
    var dist = imexMap.getDistance(pnt);
    if (dist && dist>0) { marker.__distance = dist.toFixed(0)+'m'; }
    imexMap.map.addOverlay(marker);
    imexMap.markers.push(marker);
  },
  
  // load the table of markers
  loadTable: function(cnt,typ,id,flt) {
    var para; para = 'cnt='+cnt+'&typ='+typ
    if (!id) { if (imexMap.actID[typ]) { id = imexMap.actID[typ]; }}
    if (id) { para += '&id='+id; }
    if (flt) { para += '&flt='+flt; }
    GDownloadUrl(
      'app_imex/xt_obj_ajax.asp?cmd=GETMARKERSTABLE&'+para,
      function(dat,res) {  
        if (document.getElementById('maptab')) {
          document.getElementById('maptab').innerHTML = dat;
        }
        if (document.getElementById('maptabdet')) {
          document.getElementById('maptabdet').innerHTML = dat;
        }
      }  
    );
  },
  
  getAccuracy: function(a) {
    switch (parseInt(a)) {
      case -1: return 'manuell'; break;
      case  0: return 'unbekannt'; break;
      case  1: return 'Land'; break;
      case  2: return 'Region'; break;
      case  3: return 'Bezirk'; break;
      case  4: return 'Stadt'; break;
      case  5: return 'Postleitzahl'; break;
      case  6: return 'Strasse'; break;
      case  7: return 'Kreuzung'; break;
      case  8: return 'Adresse'; break;
      default: return 'unbekannt'; break;
    }
  },
  
  // geocode a location
  geocode: function(adr) {
    if (!imexMap.geocoder) {
      imexMap.geocoder = new GClientGeocoder();
    }
    imexMap.geocoder.getLocations(
      adr, // + ', Switzerland',
      function(r) {
        if (!r || r.Status.code != 200) {    
          alert(adr + " wurde nicht gefunden");  
        } else {
          imexMap.clearMarkers();
          var place = r.Placemark[0];    
          var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);    
          try { imexMap.map.setCenter(point,imexMap.zo); } catch(e) { }
          imexMap.addMarker(point,imexMap.markerType,0,true,0,0);
          imexMap.lat = point.y;
          imexMap.lng = point.x;
          if (imexMap.updateMarker) {
            imexMap.updateMarker(point,place.AddressDetails.Accuracy);
          }
        }
      } 
    );    
  }
}

// register behaviour rules for drop shadows
var imexRules = {
//  '.dropshadow' : function(el) {
//    Shadower.shadow(el,{distance: 6, angle: 135, opacity: 0.7, nestedShadows: 6, color: '#000000'});
//  }
}
Behaviour.register(imexRules);
Behaviour.start();

