var ESTATE_SINGLE_ICON = null;
var ESTATE_MULTIPLE_ICON = null;
var ESTATE_SELECTED_ICON = null;
var LAT_METER = 0.000008995;
var LNG_METER = 0.000013148;

function global_init(){
  ESTATE_SINGLE_ICON = new GIcon();
  ESTATE_SINGLE_ICON.image = 'http://static2.datasrv.sikeres.hu/layout_right/map/marker_normal.png';
  ESTATE_SINGLE_ICON.shadow = '';
  ESTATE_SINGLE_ICON.iconSize = new GSize(15,19);
  ESTATE_SINGLE_ICON.iconAnchor = new GPoint(8,19);

  ESTATE_MULTIPLE_ICON = new GIcon();
  ESTATE_MULTIPLE_ICON.image = 'http://static2.datasrv.sikeres.hu/layout_right/map/marker_multi.png';
  ESTATE_MULTIPLE_ICON.shadow = '';
  ESTATE_MULTIPLE_ICON.iconSize = new GSize(20,24);
  ESTATE_MULTIPLE_ICON.iconAnchor = new GPoint(8,24);

  ESTATE_SELECTED_ICON = new GIcon(ESTATE_SINGLE_ICON, 'http://static2.datasrv.sikeres.hu/layout_right/map/marker_highlight.png');
}

var LabelJSON = Class.create({
  initialize: function(json)
  {
    this.ids = [];
    var items = this.getItems(json);
    this.itemCnt = items.length;
    this.label = Builder.node('div', {
      className: 'map_label_div',
      style: 'width: 340px;'
    }, [
    Builder.node('div' , {
      className: 'itemdiv',
      style: 'overflow:auto; '+this.getHeight()
    }, [items]) ]);
  },

  getHeight: function()
  {
    return (this.itemCnt*135>=460) ? 'height: 460px;' : '';
  },

  getItems: function(json)
  {
    var arr = [];
    json.each(function(el){
      this.ids.push(el.id);
      arr.push(
        Builder.node('div', {
          className: 'label_item',
          id: 'label_item_'+el.id
        }, [
        Builder.node('div', {
          style: 'float: left; width: 160px; text-align: center;'
        }, [
        Builder.node('a',{
          href: el.link,
          title: 'Részletes adatlap',
          target: '_blank'
        })

        ]),
        Builder.node('div', {
          style: 'float: left; width: 300px;'
        }, this.getLabelData(el) )
          ])
        );
    }.bind(this));
    return arr;
  },

  getLabelData: function(json)
  {
      var ret=[];
      json.bbank*=1;
      if(!json.bbank) {
          ret.push(this.getLabelSingleRowData(json.nev));
          ret.push(this.getLabelSingleRowData(json.regio));
          ret.push(this.getLabelSingleRowData(json.cim));
          ret.push(this.getLabelSingleRowData(json.tevekenyseg));
          var e=Builder.node('a', {
             href: json.link
            ,className: 'googlemaps_link'
            ,target: '_blank'
          },['Részletes adatlap']);
          ret.push(e);
      } else {
          ret.push(this.getLabelSingleRowData(json.nev));
          ret.push(this.getLabelSingleRowData(json.regio+', '+json.cim));
          ret.push(this.getLabelSingleRowData('Fax: '+json.phone));
          ret.push(this.getLabelSingleRowData('Nyitvatartás: '+json.text));
      }
	return ret;
  },

  getLabelRowData: function(key, value)
  {
    return Builder.node('div', {
      className: 'map_label_dataline'
    }, [
    Builder.node('div', {
      className: 'name'
    }, [key+':']),
    Builder.node('div', {
      className: 'value'
    }, [value])
    ]);
  },

  getLabelSingleRowData: function(value, classname)
  {
    var divclass = 'value';
    if(typeof classname != 'undefined'){
      divclass+=' '+classname;
    }
    return Builder.node('div', {
      className: 'map_label_dataline'
    }, [
    Builder.node('div', {
      className: divclass
    }, [value])
    ]);
  },

  getLabel: function()
  {
    return this.label;
  }
});

var FormLayer = Class.create({
  initialize: function(id, map)
  {
    this.formDiv = $(id);
    this.formDiv.show();
    this.map = map;
    this.buildLayer();
    this.map.getContainer().insert({
      top: this.showButton
    });
    this.map.getContainer().insert({
      top: this.divLayer
    });
    this.hide();
  },

  buildLayer: function()
  {
    var openbutton = new Element('img');
    openbutton.src = 'http://static2.datasrv.sikeres.hu/layout_right/map/searchbox_openbutton.png';
    openbutton.width = 40;
    openbutton.height = 208;
    var closebutton = new Element('img');
    closebutton.src='http://static2.datasrv.sikeres.hu/layout_right/map/mapsearch-closebutton.png';
    closebutton.width = 70;
    closebutton.height = 25;

    this.divLayer = Builder.node('div',{
      id: 'map_form_layer'
    },[
    Builder.node('div',{
      className: 'title'
    },[
    Builder.node('div',["Keresés a térképen"]).setStyle({
      width: '200px',
      height: '40px',
      position: 'absolute',
      left: '20px',
      top: '10px',
      zIndex: '1030',
      color: '#E31019',
      fontWeight: 'bold',
      fontSize: '14px'
      //cssFloat: 'left'
    }),
    Builder.node('div',{
      title: 'bezárás'
    },[closebutton]).setStyle({
      width: '70px',
      height: '25px',
      //cssFloat: 'right',
      position: 'absolute',
      top: '5px',
      right: '5px',
      cursor: 'pointer',
      zIndex: '1025',
      display: 'block'
    }).observe('click', function(e){
      this.hide()
    }.bind(this))]),
      this.formDiv
      ]).setStyle({
      position: 'absolute',
      top: '115px',
      right: '0px',
      zIndex: '1050',
      //width: '380px',
      width: '360px',
      //height: '270px',
      height: '345px',
      visibility: 'visible',
      //backgroundColor: 'white',
      //border: '1px solid',
      //padding: '10px 20px',
      display: 'none'
    });
    this.showButton = Builder.node('div',{
      id:'map_form_layer_showbutton'
    },[
    Builder.node('a',[openbutton]).setStyle({
      cursor: 'pointer',
      display: 'block'
    })
    ]).setStyle({
      position: 'absolute',
      top: '194px',
      right: '0px',
      zIndex: 1050,
      visibility: 'visible',
      display: 'none'
    });
    this.showButton.observe('click', function(e){
      this.show()
    }.bind(this));
  },

  show: function()
  {
    this.showButton.hide();
    this.divLayer.show();
  },

  hide: function()
  {
    this.divLayer.hide();
    this.showButton.show();
  }

});

var MapSearchButton = Class.create({
  initialize: function(map, toggle){
    this.map = map;
    this.buttonDiv=Builder.node('div',{
      id: 'search_button_div',
      style: 'display: none; position: absolute; z-index: 1000; top: 285px; right: 20px;'
    },[
    Builder.node('a',{
      style: 'display: block; cursor: pointer;'
    },[
    Builder.node('img',{
      src: 'http://static2.datasrv.sikeres.hu/layout_right/map/mapsearch-searchbutton.gif',
      width: '74px',
      height: '26px'
    })
    ]).observe('click',function(){
      document.fire('MyMap:searchButton');
    })
    ]);
    if(toggle){
      this.buttonDiv.show();
    }else{
      this.buttonDiv.hide();
    }
    this.map.getContainer().insert({
      top: this.buttonDiv
    });
  }
});

var DivLayer = Class.create({
  initialize: function(id, zindex)
  {
    this.processed = 0;
    this.buildLayer(id);
    this.divLayer.setStyle({
      position: 'absolute',
      top: '0px',
      left: '0px',
      zIndex: zindex,
      width: '100%',
      height: '100%',
      visibility: 'visible',
      backgroundColor: 'white',
      display: 'none'
    });
    document.observe('ProcessLayer:hide', this.hide.bindAsEventListener(this));
  },

  buildLayer: function(e_id)
  {
    this.title = new Element('div');
    this.content = new Element('div');

    this.divLayer = Builder.node('div',{
      id: e_id
    },[
    Builder.node('div',{
      id: 'processlayer_title'
    },[
    this.title
    ]).setStyle({
      margin: '30px auto 0px',
      textAlign: 'center'
    }),
    this.content
    ]);
  },

  setContent: function(content){
    this.title.update(content.title);
    this.content.update(content.content);
    return this;
  },

  showWait: function(){
    this.setContent({
      title: "Betöltés...",
      content: Builder.node('div').setStyle({
        margin: '150px auto 0px',
        background: 'url(http://static2.datasrv.sikeres.hu/layout_right/map/ajax-loader.gif)',
        width: '50px',
        height: '50px'
      } )
    })
  },

  getLayer: function(){
    return this.divLayer;
  },

  show: function(){
    this.divLayer.setOpacity(0);
    this.divLayer.show();
    new Effect.Opacity(this.divLayer, {
      from: 0,
      to: 0.7,
      duration: 0.2
    });
  },

  hide: function(){
    this.divLayer.setOpacity(0.7);
    this.divLayer.hide();
    new Effect.Opacity(this.divLayer, {
      from: 0.7,
      to: 0,
      duration: 0.2
    });
  }
});

var MyMapSearch = Class.create({

  prevZoomLevel: 0,

  haveData: false,

  initialize: function(div)
  {
    this.div = $(div);
    this.isAddressFound = false
    this.items = [];
    this.getOptions();
    this.initMap();
    this.divLayer = new DivLayer('mapDivLayer', 1100);
    this.divLayer.showWait();
    this.searchButton = new MapSearchButton(this.map, false);
    this.map.getContainer().insert({
      top: this.divLayer.getLayer()
    });
    this.formLayer = new FormLayer('map_form', this.map);
    this.helptext = $('map_help').innerHTML;
    this.start();
  },

  getOptions: function()
  {
    var options = location.hash.replace('#','').toQueryParams();
    this.setParameters(options);
  },

  initMap: function()
  {
    this.map = new GMap2(this.div);
    this.map.setCenter(new GLatLng(47.498333, 19.040833), 13);
    this.map.setUIToDefault();
    this.initListeners();
    this.markers = null;
    return this.map;
  },

  setParameters: function(options)
  {
    this.parameters = {};
    if(options.region){
      this.parameters.region = options.region;
      this.start = function(){
        document.fire('MyMap:zoom', 11);
      };
    }
    if(options.firm){
      this.parameters.firm = options.firm;
      this.start = function(){
        document.fire('MyMap:zoom', 11);
      };
    }
    if(options.activity){
      this.parameters.activity = options.activity;
      this.start = function(){
        document.fire('MyMap:zoom', 11);
      };
    }
    if(options.address){
      this.area = 2000;
      if(options.area)
      {
        this.area = options.area;
      }
      this.address = options.address;
      this.start = this.find;
    }
    if(!options.start){
      this.start = function(){
        this.formLayer.show();
        return true;
      };
    }
  },

  initListeners: function()
  {
    document.observe('MyMap:zoom', function(e){
      if(!this.haveData){
        this.divLayer.show();
        this.getPOIs();
      }
    }.bind(this));

    document.observe('MyMap:searchButton', function(){
      this.reset();
      var b = this.map.getGrid().getBoundaryWGS();
      var coords = {
        topleft: {
          latitude: b.dMaxX,
          longitude: b.dMinY
        },
        bottomright:{
          latitude: b.dMinX,
          longitude: b.dMaxY
        }
      };
      this.parameters.coords = Object.toJSON(coords);
      this.parameters.region = '';
      document.fire('MyMap:zoom', 10);
    }.bind(this));
  },

  toggleSearchButton: function(toggle)
  {
    if(toggle){
      this.helptext = $('map_help').innerHTML;
      $('map_help').update("Ezen a területen már nincs több találat. Kattintson a gombra a térkép bal oldalán a kereséshez ezen a környéken.");
      this.searchButton.buttonDiv.show();
    }else{
      if(this.helptext != ''){
        $('map_help').update(this.helptext)
      }
      this.searchButton.buttonDiv.hide();
    }

  },

  find: function()
  {
    this.isAddressFound = false;
    if(this.parameters.region && this.address)
    {
      var gc = new GClientGeocoder;
      gc.getLatLng('Magyarország, '+this.parameters.region+' '+this.address, this.foundAddress.bind(this));
    }
    return false;
  },

  foundAddress: function(point)
  {
    if (point==null) {
      this.isAddressFound = false;
      return false;
    }
    
    this.center = point;
    this.isAddressFound = true;
    
    var bound = new GLatLngBounds();
    bound.extend(point);
    bound.extend(new GLatLng(point.lat()+LAT_METER*this.area, point.lng()+LNG_METER*this.area));
    bound.extend(new GLatLng(point.lat()-LAT_METER*this.area, point.lng()-LNG_METER*this.area));
    var coords = {
      northeast: {
        latitude: bound.getNorthEast().lat(),
        longitude: bound.getNorthEast().lng()
      },
      southwest:{
        latitude: bound.getSouthWest().lat(),
        longitude: bound.getSouthWest().lng()
      }
    };
    this.parameters.coords = Object.toJSON(coords);
    document.fire('MyMap:zoom',13);
  },

  adjustMap: function(meta)
  {
    this.helptext = '';
    this.rect=new GLatLngBounds();
    if(meta.count > 0){
      this.rect.extend(new GLatLng(meta.weight.minX, meta.weight.maxY));
      this.rect.extend(new GLatLng(meta.weight.maxX, meta.weight.minY));
      var point = this.rect.getCenter();
      var radius = 1500;
      if(this.center){
        this.map.setCenter(this.center);
        if(this.isAddressFound){
          this.map.openInfoWindowHtml(this.center, 'Keresett utca: "'+this.address+'"');
        }
      }else{
        this.map.setCenter(point, this.map.getBoundsZoomLevel(this.rect));
      }
      if(meta.count > 1000){
        $('map_help').update("<span style='color: #FF402C;'>Több, mint 1000db találat.</span> - A zoomoláshoz használja az egérgörgőt, vagy a csúszkát a bal felső sarokban.");
      }else{
        $('map_help').update("<span style='color: #FF402C;'>"+meta.count+"db találat.</span> - A zoomoláshoz használja az egérgörgőt, vagy a csúszkát a bal felső sarokban.");
      }
    }else{
      $('map_help').update("Sajnos nincs találat. Állítson a keresési paramétereken.");
    }
    return true;
  },

  getMap: function()
  {
    return this.map;
  },

  getPOIs: function()
  {
    new Ajax.Request('/terkepes-kereso-talalatok', {
      method: 'post',
      parameters: this.parameters,
      onSuccess: function(resp){
        this.adjustMap(resp.responseJSON.meta);
        this.fromJSON(resp.responseJSON.data, this.divlayer);
        this.haveData = true;
        this.formLayer.hide();
        reload_all('12605352431051');
      }.bind(this)
    });
  },

  fromJSON: function(json)
  {
    var ms = [];
    var i = 1;
    $H(json).each(function(x){
      $H(x.value).each(function(y){
        if(typeof y.value.m == 'string'){
          switch(y.value.m){
            case '1':
              ms.push(this.createMarker(y.value.ld[0].latitude, y.value.ld[0].longitude, ESTATE_SINGLE_ICON, y.value.td, i));
              break;
            case '2':
              ms.push(this.createMarker(y.value.ld[0].latitude, y.value.ld[0].longitude, ESTATE_MULTIPLE_ICON, y.value.td, i));
              break;
            case '3':
              ms.push(this.createMarker(y.value.ld[0].latitude, y.value.ld[0].longitude, ESTATE_SELECTED_ICON, y.value.td, i));
              break;
          }
          this.items[i] = y.value.ld;
        }
        i++;
      }.bind(this));
    }.bind(this));
    
    this.markers = new MarkerClusterer(this.map, ms, {maxZoom: 16});
    document.fire('ProcessLayer:hide');
  },

  createMarker: function(lat,lng,image,title,sn)
  {
    var marker = new GMarker(new GLatLng(lat, lng),{icon: image});
    marker.sn = sn;
    marker.hovertitle = title;
    GEvent.addListener(marker, 'click', this.createLabel);
    GEvent.addListener(marker, 'mouseover', this.createTitle);
    return marker;
  },

  createTitle: function(p){
    var h = new HoverTitle(this, this.hovertitle, 4);
    map.map.addOverlay(h);
    h.show();
  },

  createLabel: function(p)
  {
    if(map.items.length != 0){
      var label = new LabelJSON(map.items[this.sn]);
      map.map.openInfoWindow(p, label.getLabel());
    }
  },
  
  reset: function()
  {
    this.haveData = false;
    if(this.markers !== null){
     this.markers.clearMarkers();
    }
    delete this.markers;
    this.markers = null;
  }
});

