var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
var mapInfoObj = null;
//var ajaxurl = "http://dev001.iplatz.de/geo/ajax.php";
var ajaxurl_root = "http://prod.cochera-andina.com";
var ajaxurl_base_rel = "/geo/ajax.php";
var ajaxurl_base = "http://prod.cochera-andina.com/geo/ajax.php";
var ajaxurl = "http://prod.cochera-andina.com/geo/ajax.php?L=1&country_id=0";
var InfoDivId = 'routenDetail';
var CtyCode = 'bz';
var LangId = '0';
var info_page = 0;
var LegendeDivId ='legende';
var UwDivId ='unterwegs';

var map = null;
var currentShape=null;

var notOver=true;
var mShapeID = new Array();
var mCityID = new Array();
      
if (!isIE) {
  HTMLElement.prototype.__defineGetter__("innerText", function(){return this.textContent;});
  HTMLElement.prototype.__defineSetter__("innerText", function(v){this.textContent=v;});
}

String.prototype.request=request
String.prototype.getAllKey=getAllKey

function HTMLDecode(strEncodeHTML)
{
  var div = document.createElement('div');

  div.innerHTML = strEncodeHTML;
  return div.innerText;
}

function ShowObj(){

//alert('send request:'+ajaxurl);
  new Ajax.Request(ajaxurl, {
    method:"get",
      onSuccess:function(response){
        //alert('success');

        var jsonObjPattern = /<!-- json object data begin -->(.*)<!-- json object data end -->/;

          if (jsonObjPattern.test(response.responseText)) {
            response.responseText = RegExp.$1;  	
          }

          //alert(response.responseText );
        mapInfoObj = eval('('+ response.responseText +')');

        //load();
      //alert(eval('obj.mpoint[1].lat'));
    }
  })
}

function GetMPointNum() {
  num = eval('mapInfoObj.mpoint_size');
  return num;
}

function GetCityNum() {
  num = eval('mapInfoObj.city_size');
  return num;
}

function GetDetail(index) {
  detail = eval('mapInfoObj.routine[' + index + '].detail');
  return detail;
}

      function deleteAllShapes() {
      
        for(i=0; i < mShapeID.length; i++ ) {
          shape = map.GetShapeByID(mShapeID[i]);
          map.DeleteShape(shape);
        }      

        for(i=0; i < mCityID.length; i++ ) {
          shape = map.GetShapeByID(mCityID[i]);
          map.DeleteShape(shape);
        }      
      }

      function setCenterLatLong(cty_code) {
      
          switch (cty_code) {
            case 'ar':
              lat_init = -34.6086277798816;
              long_init = -58.372421264648445;
              info_page = 22;
              break; 
            case 'bz':
              lat_init = 17.49633381376243;
              long_init = -88.1827350531479;
              info_page = 32;
              break; 
            case 'bo':
              lat_init = -16.49139854629262;
              long_init = -68.14682006835939;
              info_page = 38;
              break; 
            case 'cl':
              lat_init = -33.43373345341701;
              long_init = -70.57205200195312;
              info_page = 30;
              break; 
            case 'ec':
              lat_init = -0.18539396359662488;
              long_init = -78.49594116210939;
              info_page = 31;
              break; 
            case 'gt':
              lat_init = 14.632752640484234;
              long_init = -90.52734375000001;
              info_page = 41;
              break; 
            case 'pa':
              lat_init = 8.954262512389393;
              long_init = -79.53998565673828;
              info_page = 42;
              break; 
            case 'pe':
              lat_init = -12.037977469134600;
              long_init = -77.04025268554680;
              info_page = 37;
              break; 
            case 'py':
              lat_init = -25.30057913410351;
              long_init = -57.628784179687486;
              info_page = 44;
              break; 
            case 'uy':
              lat_init = -34.92422301690589;
              long_init = -56.151123046875014;
              info_page = 43;
              break;
            case 've':
              lat_init = 10.49625144406409;
              long_init = -66.91995620727539;
              info_page = 29;
              break; 
            case 'br':
              lat_init = -23.528736617422026;
              long_init = -46.630096435546875;
              info_page = 33;
              break; 
            case 'cr':
              lat_init = 9.928271373823964;
              long_init = -84.07905578613284;
              info_page = 40;
              break; 
            case 'hn':
              lat_init = 14.0951226326868669;
              long_init = -87.20672607421878;
              info_page = 39;
              break; 
            case 'sv':
              lat_init = 13.701279736653926;
              long_init = -89.20271873474121;
              info_page = 35;
              break; 
            case 'mx':
              lat_init = 19.421915889653373;
              long_init = -99.14543151855469;
              info_page = 34;
              break; 
            case 'ni':
              lat_init = 12.148423991281625;
              long_init = -86.2704849243164;
              info_page = 36;
              break; 
            default:
              lat_init = -34.6086277798816;
              long_init = -58.372421264648445;
              info_page = 22;
              break;
          }      
      
      }
      
      function load() {
//        alert('load called');
        if (map == null) {
          map=new VEMap('myMap');

          setCenterLatLong(CtyCode);
       
          mapCenter = new VELatLong(lat_init, long_init);
          map.LoadMap();

//        map.SetMapStyle(VEMapStyle.Shaded);
          map.SetMouseWheelZoomToCenter(false);
          map.SetCenterAndZoom(mapCenter,9);

          map.ClearInfoBoxStyles();

          map.AttachEvent("onmouseover",mouseOverHandler);
          map.AttachEvent("onmouseout",mouseOutHandler);
          map.AttachEvent("onendzoom",EndZoomHandler);
          map.AttachEvent("onclick",mouseClickHandler);

        } else {
        
          map.Clear();
          //deleteAllShapes();
        
          currentShape=null;
          notOver=true;
          mShapeID = new Array();
          mCityID = new Array();
          
          //map.DeleteAllShapes();
          //map.DeleteAllShapeLayers();

          setCenterLatLong(CtyCode);

          mapCenter = new VELatLong(lat_init, long_init);
          map.SetCenterAndZoom(mapCenter,9);

        }

        mpoint_num = GetMPointNum();
//        alert(mpoint_num);
       
        for(i=0; i< mpoint_num; i++) {

          //alert(i);
          //alert(eval('mapInfoObj.mpoint[' + (i) +'].lat'));
          mpoint_lat = eval('mapInfoObj.mpoint[' + (i) +'].lat');
          mpoint_long = eval('mapInfoObj.mpoint[' + (i) +'].long');
          
          if (mpoint_lat == '')  mpoint_lat = '0';
          if (mpoint_long == '')  mpoint_long = '0';        
        
          var point_cd = new VELatLong(mpoint_lat, mpoint_long);
          var mShape = new VEShape(VEShapeType.Pushpin, point_cd);
          
          mShape.SetTitle('');
          mShape.SetCustomIcon("<div class='auto" + eval('mapInfoObj.mpoint[' + (i) +'].road_type') + "Zm02' id='auto_" + i + "'></div>");
          mShape.SetDescription(eval('mapInfoObj.mpoint[' + (i) +'].roads'));

          map.AddShape(mShape);
          mShapeID[i] = mShape.GetID();

          //if (i == 0)
          //document.getElementById(InfoDivId).innerHTML = "add" + i + " " + mShapeID[i] + "" + eval('mapInfoObj.mpoint[' + (i) +'].roads');
          
        }
        //alert('mpoints added.');

        city_num = GetCityNum();
       
        //debug_city = 'mpoints added. <br />';
        
        for(i=0; i< city_num; i++) {

          //document.getElementById(InfoDivId).innerHTML = eval('mapInfoObj.city[' + (i) +'].name') + "<br/ >"
          //                                             + eval('mapInfoObj.city[' + (i) +'].lat') + "<br/ >"
          //                                             + eval('mapInfoObj.city[' + (i) +'].long') + "<br />"
          //                                             + eval('mapInfoObj.city[' + (i) +'].roads');
        
          //alert(eval('mapInfoObj.city[' + (i) +'].name'));
          city_lat = eval('mapInfoObj.city[' + (i) +'].lat');
          city_long = eval('mapInfoObj.city[' + (i) +'].long');
          
          if (city_lat == '')  city_lat = '0';
          if (city_long == '')  city_lat = '0';
          
          var point_cd = new VELatLong(city_lat, city_long);
          
          var mShape = new VEShape(VEShapeType.Pushpin, point_cd);
          
          mShape.SetTitle(eval('mapInfoObj.city[' + (i) +'].name'));
          mShape.SetCustomIcon("<div class='cityNormal' id='city_" + i + "'></div>");
          mShape.SetDescription(eval('mapInfoObj.city[' + (i) +'].roads'));

          map.AddShape(mShape);
          mCityID[i] = mShape.GetID();
          
          
          //debug_city += eval('mapInfoObj.city[' + (i) +'].name') + "<br />";

        }
        //alert('cities added.');
        //document.getElementById(InfoDivId).innerHTML = debug_city;
        //document.getElementById(InfoDivId).innerHTML =  eval('mapInfoObj.cty_id');
     }

     function shapeGetIconID(iconStr) {
        /* ... id='' ....    */
        beg = iconStr.search("id='");
        if (beg >= 0 ) {
          subIconStr = iconStr.substring(beg+4, iconStr.length);
          
          index = subIconStr.indexOf("'"); 
          if (index > 0) {
            idStr = subIconStr.substring(0, index);
            //alert(idStr);
            return idStr;
          }
        }
        return '';
     }
     
     function isAutoIcon(idStr) {
       if (idStr.indexOf("auto_") >= 0) {
         return true;
       }
       return false;
     }
     
     function shapeGetIndex(idStr) {
       idStr = idStr.replace("auto_", "");
       idStr = idStr.replace("city_", "");
       return idStr;
     }

     function mouseOverHandler(e) {
       if(e.elementID&&notOver) {
         mouseOverSidebarItem(e.elementID)
         notOver=false;
       }
     }

     function mouseOutHandler(e) {
       if(e.elementID&&!notOver) {
         mouseOutSidebarItem(e.elementID)
         notOver=true;
       }
     }
     
     function mouseClickHandler(e) {
       if(e.elementID) {
         currentShape=map.GetShapeByID(e.elementID);
         currentIcon=currentShape.GetCustomIcon();
         icon_id = shapeGetIconID(currentIcon);
         if (isAutoIcon(icon_id)) {
           i = shapeGetIndex(icon_id);
           //alert(i);
           document.getElementById(InfoDivId).innerHTML = GetDetail(i);
         }
       }    
     }
     
     
     function mouseOverSidebarItem(markerId) {
      
       //document.getElementById(InfoDivId).innerHTML = markerId;
     
       currentShape=map.GetShapeByID(markerId);
       currentIcon=currentShape.GetCustomIcon();
       //alert(currentIcon);
       icon_id = shapeGetIconID(currentIcon);
       //alert(icon_id);
       currentShape.SetCustomIcon(currentIcon.replace('Normal','Hover'));
       currentIcon=currentShape.GetCustomIcon();
       currentShape.SetCustomIcon(currentIcon.replace('Zm01','Zm02'));
       map.ShowInfoBox(currentShape);
       
       //alert(icon_id);
         if (isAutoIcon(icon_id)) {
           i = shapeGetIndex(icon_id);
           start_city_index = eval('mapInfoObj.mpoint[' + (i) +'].start_city');
           sShape=map.GetShapeByID(mCityID[start_city_index]);
           sIcon=sShape.GetCustomIcon();
           sShape.SetCustomIcon(sIcon.replace('Normal','Hover'));
           
           end_city_index = eval('mapInfoObj.mpoint[' + (i) + '].end_city');
           eShape=map.GetShapeByID(mCityID[end_city_index]);
           eIcon=eShape.GetCustomIcon();
           eShape.SetCustomIcon(eIcon.replace('Normal','Hover'));

           //document.getElementById(InfoDivId).innerHTML = icon_id + " Auto Icon Index:" + i + "start: " + start_city_index + "end:" + end_city_index;

         }
     }
    
     function mouseOutSidebarItem(markerId) {
       currentShape=map.GetShapeByID(markerId);
       currentIcon=currentShape.GetCustomIcon();
       icon_id = shapeGetIconID(currentIcon);
       currentShape.SetCustomIcon(currentIcon.replace('Hover','Normal'));
//       map.HideInfoBox(currentShape);

         if (isAutoIcon(icon_id)) {
           i = shapeGetIndex(icon_id);
           start_city_index = eval('mapInfoObj.mpoint[' + (i) +'].start_city');
           sShape=map.GetShapeByID(mCityID[start_city_index]);
           sIcon=sShape.GetCustomIcon();
           sShape.SetCustomIcon(sIcon.replace('Hover', 'Normal'));
           
           end_city_index = eval('mapInfoObj.mpoint[' + (i) +'].end_city');
           eShape=map.GetShapeByID(mCityID[end_city_index]);
           eIcon=eShape.GetCustomIcon();
           eShape.SetCustomIcon(eIcon.replace('Hover', 'Normal'));
           
         }
      }
      
      function EndZoomHandler(e)
      {
         var z = map.GetZoomLevel();
         //document.getElementById(InfoDivId).innerHTML = z;

         if (z <= 7) {
           for (i=0; i< mShapeID.length; i++) {
             shape = map.GetShapeByID(mShapeID[i])
             currentIcon = shape.GetCustomIcon();
             shape.SetCustomIcon(currentIcon.replace('Zm02','Zm01'));
             currentIcon = shape.GetCustomIcon();
             shape.SetCustomIcon(currentIcon.replace('Hover','Normal'));
           }
         } else {
           for (i=0; i< mShapeID.length; i++) {
             shape = map.GetShapeByID(mShapeID[i])
             currentIcon = shape.GetCustomIcon();
             shape.SetCustomIcon(currentIcon.replace('Zm01','Zm02'));
           }
         }
         
      }      
      
      function ShowDetail(detail_index) {
        document.getElementById(InfoDivId).innerHTML = GetDetail(detail_index); 
      
      }   
      
      function request(key)
      {
        if(typeof(this)=="undefined") return false;
        
        if(this.length>0)
        {
          var s = this.split("&");
          //for(var i in s)
          for (i=0; i < s.length; i++)
          {
            if (s[i]) {
              var sp=s[i].split("=")
              if(sp[0]==key)return(sp[1]);
            }
          }
          return false;
        }
        else return false
      }

      function getAllKey()
      {
        if(typeof(this)=="undefined")return false;
        var arr=new Array;
        if(this.length>0)
        {
          var s = this.split("&");
          //for(var i in s)
          for (i=0; i < s.length; i++)
          {
            var sp=s[i].split("=");
            arr.push(sp[0]);
          }
          return arr;
        }
        else return false
      }

      function loadMapInfo(cty_code, cty_name) {
        var this_url=location.search.substr(1);
        mapInfoObj = null;

        if (cty_code == '0') {
          document.getElementById(LegendeDivId).style.display = "none";
          document.getElementById(UwDivId).style.display = "none"; 
          ShowBlankMap();
          return;
        }
        
        document.getElementById(LegendeDivId).style.display = "block";
        
        //alert(this_url);
        if (cty_code == '')
        {
          CtyCode = this_url.request('cty');
          
          if (CtyCode == '')
          {
            CtyCode = 'bz'; 
          }
        }
        else 
        {
          CtyCode = cty_code;
        }
        
        setCenterLatLong(CtyCode);
        
        LangId = this_url.request('L');
        
        if (!LangId) {
          //retrieve url de/ en/ es/
          thisUrl = document.URL;
          
          foundLang = thisUrl.search("/en/");
          if (foundLang >= 0) {
            LangId = '1';
          } else {
            foundLang = thisUrl.search("/es/");
            
            if (foundLang >= 0) {
              LangId = '3';
            } else {
              LangId = '0';
            }
          }
          
        } 
        
        ajaxurl_root = "http://" + document.domain;
        //alert(ajaxurl_root);
        ajaxurl_base = ajaxurl_root + ajaxurl_base_rel;        
        ajaxurl = ajaxurl_base + '?' + 'cty_code=' + CtyCode + '&' + 'L=' + LangId;// + '&timestamp=' + new Date();
        //alert(ajaxurl);
        info_page_url = 'index.php?id='+ info_page +'&' + 'L=' + LangId;
        
        if (LangId == '0') {
          //info_page_title = 'Auto fahren in ' + cty_name;
          info_page_title = '<img alt="" id="autoLand" src="/fileadmin/images/autoFahren_de.gif" />';
        } else if (LangId == '1') {
          //info_page_title = 'Driving in ' + cty_name;
          info_page_title = '<img alt="" id="autoLand" src="/fileadmin/images/autoFahren_en.gif" />';
        } else if (LangId == '3') {
          //info_page_title = 'Viajando en coche en ' + cty_name;
          info_page_title = '<img alt="" id="autoLand" src="/fileadmin/images/autoFahren_es.gif" />';
        }
        
        //info_page_title = info_page_title.toUpperCase();
        
        //info_page_link = '<div id="drive"><a href=\"' + info_page_url + '\">' + info_page_title + '</a></div>';
        info_page_link = '<a href=\"' + info_page_url + '\">' + info_page_title + '</a>';
        //alert(info_page_link);

        document.getElementById(UwDivId).innerHTML = info_page_link;
        document.getElementById(UwDivId).style.display = "block";

        ShowObj();
        
        setTimeout('tryLoadMap()', 250);
      }
      
      function tryLoadMap() {
        if (mapInfoObj == null) {
          setTimeout('tryLoadMap()', 250);
        }
        else {
          load();
        }
      }        

      function SetSelDefault(sele_id, sele_val) {
        objSelect = document.getElementById(sele_id);
        for (var i = 0; i < objSelect.options.length; i++)  {
          //alert(objSelect.options[i].value);         
          if (objSelect.options[i].value == sele_val) { 
            objSelect.options[i].selected = true;        
            break;        
          }        
        }                  
      }

      function SetSelDefaultFromUrl(sele_id){
        var this_url=location.search.substr(1);
        sele_val = this_url.request('cty');
        SetSelDefault(sele_id, sele_val);
        if (sele_val == '') {
          ShowBlankMap();
        } else {
          objSelect = document.getElementById(sele_id);
          loadMapInfo(sele_val, objSelect.options[objSelect.selectedIndex].text);
        }
      }
      
      function ShowBlankMap() {
      
        map=new VEMap('myMap');

        lat_init = -20;
        long_init = -70.5;
      
        mapCenter = new VELatLong(lat_init, long_init);
        map.LoadMap();

//      map.SetMapStyle(VEMapStyle.Shaded);
        map.SetMouseWheelZoomToCenter(false);
        map.SetCenterAndZoom(mapCenter,3);

        map.ClearInfoBoxStyles();

        map.AttachEvent("onmouseover",mouseOverHandler);
        map.AttachEvent("onmouseout",mouseOutHandler);
        map.AttachEvent("onendzoom",EndZoomHandler);
        map.AttachEvent("onclick",mouseClickHandler);
        
      }
     
     
     function zeige(karte){
       if(karte == 'microsoft') {
         document.getElementById("imagemap").style.display = "none";
     //    document.getElementById("myMap").style.display = "block";
     document.getElementById("myMap").style.position = "relative";
     document.getElementById("myMap").style.left = "0";
       }
     }
     
