/** (c) Kazan Daemon's Code http://www.kazandaemon.ru */

jQuery(document).ready(function() {

  var LabeledMarker =function(options){
    this.position = options.position;
    this.label = options.label;
    this.title = options.title;
    this.labelClass = "markerLabel";
    this.div_ = document.createElement("div");
    this.setMap(options.map);
  };

  LabeledMarker.prototype = new google.maps.OverlayView();

  LabeledMarker.prototype.addClass = function(className) {
    jQuery(this.div_).addClass(className);
  };

  LabeledMarker.prototype.removeClass = function(className) {
    jQuery(this.div_).removeClass(className);
  };

  LabeledMarker.prototype.onAdd = function() { 
    jQuery(this.div_).addClass(this.labelClass).attr('title', this.title).text(this.label);
    this.div_.style.position = "absolute";
    var panes = this.getPanes();
    panes.overlayImage.appendChild(this.div_);
  };

  LabeledMarker.prototype.draw = function() {
    var overlayProjection = this.getProjection();
    var point = overlayProjection.fromLatLngToDivPixel(this.position);
    var div = this.div_;
    div.style.left = String(point.x-8)+'px';
    div.style.top = String(point.y - jQuery(div).height() + 4)+'px';
  };

  LabeledMarker.prototype.remove = function() {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
  };

  LabeledMarker.prototype.hover = function(hoverin, hoverout) {
    jQuery(this.div_).hover(hoverin, hoverout);
  };

  LabeledMarker.prototype.click = function(handler) {
    jQuery(this.div_).click(handler);
  };

  KD_USER_APPLICATION = function() {
    var inst = this;
    this.routeColors = new Array();
    this.routeColors.push('#13A413');
    this.routeColors.push('#6F769D');
    this.routeColors.push('#1314FC');
    this.routeColors.push('#BD2CBB');
    this.selfMarker = new google.maps.Marker({
      draggable: false
    });
    this.directions = new Array();
    var mapOptions = {
      minZoom: 10,
      maxZoom: 18,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      streetViewControl: false
    }
    this.bounds = null;
    this.hovered = null;
    this.selected = null;
    this.mapGoogle = new google.maps.Map(jQuery('#kdlh20110126_103_page .incity .map').get(0), mapOptions);
    this.markers = new Array();
    this.places = kdlh20110126_103_places.places;
    this.ucountry = kdlh20110126_103_places.whoiscountry;
    this.ucity = kdlh20110126_103_places.whoiscity;
    this.tree = new Object();
    this.tree.listCountries = new Array();
    this.tree.append = function(place) {
      if (!this[place.country]) {
        this[place.country] = {
          internet: new Array(),
          cities: new Object(),
          listCities: new Array(),
          minDist: null
          };
        this.listCountries.push(place.country);
        this.listCountries.sort();
      }
      if (place.city == '') {
        this[place.country].internet.push(place);
      } else {
        if (!this[place.country].cities[place.city]) {
          this[place.country].cities[place.city] = new Array();
          this[place.country].listCities.push(place.city);
          this[place.country].listCities.sort();
          place.dist = false;
          if ((inst.geoloc != false) && (Number(place.citylat) != 0) && (Number(place.citylng) != 0)) {
            place.dist = google.maps.geometry.spherical.computeDistanceBetween(inst.geoloc, new google.maps.LatLng(Number(place.citylat), Number(place.citylng)));
            if ((this[place.country].minDist == null) || (this[place.country].minDist.dist > place.dist)) {
              this[place.country].minDist = place;
            }
          }
        }
        this[place.country].cities[place.city].push(place);
      }
    };
    jQuery(document.body).addClass('kdlh20110126_103_page');
    this.geoloc = false;
    if (this.ucity) {
      var geocoder = new google.maps.Geocoder();
      geocoder.geocode( {
        'address': this.ucountry+', '+this.ucity, region: this.ucountry
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          inst.geoloc = results[0].geometry.location;
        }
        inst.init();
      });
    } else {
      this.init();
    }
    jQuery('#kdlh20110126_103_page .typeselect .city').click(function() {
      jQuery('#kdlh20110126_103_page .typeselect .internet').removeClass('typehighlighted');
      jQuery('#kdlh20110126_103_page .typeselect .city').addClass('typehighlighted');
      jQuery('#kdlh20110126_103_page .ininternet').hide();
      jQuery('#kdlh20110126_103_page .incity').show();
      var waitshow = function() {
        if (jQuery('#kdlh20110126_103_page .incity .map').height() == 0) {
          window.setTimeout(waitshow, 0);
        } else {
          google.maps.event.trigger(inst.mapGoogle, 'resize');
          inst.mapGoogle.fitBounds(inst.bounds);
        }
      };
      waitshow();
      return false;
    });
    jQuery('#kdlh20110126_103_page .typeselect .internet').click(function() {
      jQuery('#kdlh20110126_103_page .typeselect .internet').addClass('typehighlighted');
      jQuery('#kdlh20110126_103_page .typeselect .city').removeClass('typehighlighted');
      jQuery('#kdlh20110126_103_page .ininternet').show();
      jQuery('#kdlh20110126_103_page .incity').hide();
      return false;
    });
    jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .routeaddr').focus(function() {
      if (jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .routeaddr').hasClass('empty')) {
        jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .routeaddr').removeClass('empty').val('');
      }
    }).blur(function() {
      if (jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .routeaddr').val() == '') {
        jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .routeaddr').addClass('empty').val('улица, дом');
      }
    }).keyup(function(e) {
      if(e.keyCode == 13) {
        jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .makeroute').click();
      }
    });
  };

  KD_USER_APPLICATION.prototype = {
    init: function() {
      var inst=this;
      var i;
      for (i=0; i<this.places.length; i++) {
        this.tree.append(this.places[i]);
      }
      if (this.tree['UA'] && (this.tree['UA'].minDist == null) && this.tree['UA'].cities['Киев']) {
        this.tree['UA'].minDist = this.tree['UA'].cities['Киев'][0];
      }
      var tr = jQuery('#kdlh20110126_103_page .dlocation table tr');
      for (i=0; i<this.tree.listCountries.length; i++) {
        var td = jQuery('<td />');
        if (i>0) {
          td.addClass('next');
        }
        var title=(this.tree.listCountries[i]=='BY')?'Беларусь':(this.tree.listCountries[i]=='RU')?'Россия':'Украина';
        td.append(jQuery('<a />').addClass('country').attr('href', '#').text(title).click((function(country) {return function() {inst.selectCountry(country);inst.dlocation.dialog("close");return false;}})(this.tree.listCountries[i])));
        for (var j=0; j<this.tree[this.tree.listCountries[i]].listCities.length; j++) {
          td.append(jQuery('<a />').addClass('city').attr('href', '#').text(this.tree[this.tree.listCountries[i]].listCities[j]).click((function(country, city) {return function() {inst.displayCity(country, city);inst.dlocation.dialog("close");return false;}})(this.tree.listCountries[i], this.tree[this.tree.listCountries[i]].listCities[j])));
        }
        tr.append(td);
      }
      this.dlocation = jQuery('#kdlh20110126_103_page .dlocation').dialog({
        modal: true,
        autoOpen: false,
        resizeable: false,
        width: 'auto'
      });
      jQuery('#kdlh20110126_103_page .location a').click(function(){
        inst.dlocation.dialog("open");
        return false;
      });
      if ((this.ucountry != '') && this.tree[this.ucountry]) {
        this.selectCountry(this.ucountry);
      } else {
        this.selectCountry('UA');
      }
    },
    
    selectCountry: function(country) {
      if (this.tree[country].listCities.length>0) {
        if (this.tree[country].minDist != null) {
          this.displayCity(country, this.tree[country].minDist.city);
        } else {
          this.displayCity(country, this.tree[country].listCities[0]);
        }
      } else {
        this.displayCity(country, '');
      }
    },

    displayCity: function(country, city) {
      var inst = this;
      var i, tr, td, data;
      var forMap = new Array();
      var makehoverin = function(obj) {return function() {
            if (inst.hovered) {inst.hovered.marker.removeClass('hovered');inst.hovered.tr.removeClass('hovered');}
             inst.hovered=obj;
             obj.marker.addClass('hovered');
             obj.tr.addClass('hovered');
          };
          };
      var hoverout = function(){if (inst.hovered) {inst.hovered.marker.removeClass('hovered');inst.hovered.tr.removeClass('hovered');inst.hovered=null;}};
      var makeclick = function(obj, doScroll) {return function() {
              var setSelected = true;
              if (jQuery(this).hasClass('selected')) {
                setSelected = false;
              }
              if (inst.selected) {inst.selected.marker.removeClass('selected');inst.selected.tr.removeClass('selected');}
              if (setSelected) {
                inst.mapGoogle.setCenter(obj.marker.position);
                inst.mapGoogle.setZoom(15);
                inst.selected = obj;
                inst.selected.marker.addClass('selected');inst.selected.tr.addClass('selected');
                if (doScroll) {jQuery('#kdlh20110126_103_page .map').get(0).scrollIntoView(false);}
              } else {
                inst.mapGoogle.fitBounds(inst.bounds);
              }
          };
          };
      var locationname = (country=="BY")?"Беларуси":(country=="RU")?"России":"Украине";
      this.selfMarker.setMap(null);
      for (i=0; i<this.directions.length; i++) {
        this.directions[i].setMap(null);
      }
      this.directions = new Array();
      if (this.tree[country].internet.length) {
        jQuery('#kdlh20110126_103_page .ininternet ol li').remove();
        jQuery('#kdlh20110126_103_page .ininternet').show();
        this.tree[country].internet.sort(function(x1, x2) {
          if (x1.title < x2.title) {
            return -1;
          } else if (x1.title > x2.title) {
            return 1;
          } else {
            return 0;
          }
        });
        for (i=0; i<this.tree[country].internet.length; i++) {
          data = this.tree[country].internet[i].site.split('@@');
          jQuery('#kdlh20110126_103_page .ininternet ol').append(jQuery('<li />').text(this.tree[country].internet[i].title+' - ').append(jQuery('<a />').attr('href', data[0]).attr('target', 'blank').text((data.length>1)?data[1]:data[0])));
        }
      } else {
        jQuery('#kdlh20110126_103_page .ininternet').hide();
      }
      if (this.tree[country].cities[city] && this.tree[country].cities[city].length) {
        locationname += ", город "+city;
        jQuery('#kdlh20110126_103_page .incity table tr').remove();
        this.tree[country].cities[city].sort(function(x1, x2) {
          if (x1.title < x2.title) {
            return -1;
          } else if (x1.title > x2.title) {
            return 1;
          } else {
            return 0;
          }
        });
      for (i=0; i<this.tree[country].cities[city].length; i++) {
        jQuery('#kdlh20110126_103_page .incity table').append(tr = jQuery('<tr />').append(jQuery('<td />').text(String(i+1)).addClass('num')).append(td = jQuery('<td />').addClass('opt').append(jQuery('<h4 />').text(this.tree[country].cities[city][i].title))));
        if (this.tree[country].cities[city][i].address) {
          td.append(jQuery('<div />').append(jQuery('<b>Адрес:</b>')).append(' '+this.tree[country].cities[city][i].address));
        }
        if (this.tree[country].cities[city][i].phone) {
          td.append(jQuery('<div />').append(jQuery('<b>Телефон:</b>')).append(' '+this.tree[country].cities[city][i].phone));
        }
        if (this.tree[country].cities[city][i].site) {
          data = this.tree[country].cities[city][i].site.split('@@');
          td.append(jQuery('<div />').append(jQuery('<b>Сайт:</b>')).append(' ').append(jQuery('<a />').attr('href', data[0]).attr('target', 'blank').text((data.length>1)?data[1]:data[0])));
        }
        if (this.tree[country].cities[city][i].other) {
          td.append(jQuery('<div />').addClass('other').append(this.tree[country].cities[city][i].other));
        }
        if (Number(this.tree[country].cities[city][i].map)>0) {
          var obj = {
            num: (i+1),
            place: this.tree[country].cities[city][i],
            marker: null,
            tr: tr
          };
          forMap.push(obj);
          tr.hover(makehoverin(obj), hoverout);
          tr.click(makeclick(obj, true));
        }
      }
      jQuery('#kdlh20110126_103_page .incity .map').hide();
      jQuery('#kdlh20110126_103_page .incity').show();
      if (forMap.length > 0) {
        for (i=0; i<this.markers.length; i++) {
          this.markers[i].setMap(null);
        }
        this.markers = new Array();
        this.bounds = new google.maps.LatLngBounds();
        this.mapGoogle.setCenter(new google.maps.LatLng(0,0),0);
        for (i=0; i<forMap.length; i++) {
          var marker = new LabeledMarker({
            map: this.mapGoogle,
            position: new google.maps.LatLng(forMap[i].place.lat, forMap[i].place.lng),
            title: forMap[i].place.title,
            label: String(forMap[i].num)
          });
          forMap[i].marker = marker;
          marker.hover(makehoverin(forMap[i]), hoverout);
          marker.click(makeclick(forMap[i], false));
          this.bounds.extend(new google.maps.LatLng(forMap[i].place.lat, forMap[i].place.lng));
          this.markers.push(marker);
        }
        jQuery('#kdlh20110126_103_page .incity .map').show();
        jQuery('#kdlh20110126_103_page .incity .routecontrol').show();
        jQuery('#kdlh20110126_103_page .incity .routecontrol a.hideroute').hide();
        jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute').show();
        jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .routeaddr').val('улица, дом').addClass('empty');
        jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .makeroute').unbind('click').click(function(){
          var addr = jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute .routeaddr').val();
          if (!addr) {
            return false;
          }
          var geocoder = new google.maps.Geocoder();
          geocoder.geocode( {
            'address': country+', '+city+', '+addr, region: country
          }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              inst.selfMarker.setMap(inst.mapGoogle);
              inst.selfMarker.setPosition(results[0].geometry.location);
              inst.bounds.extend(results[0].geometry.location);
              inst.mapGoogle.fitBounds(inst.bounds);
              jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute').hide();
              jQuery('#kdlh20110126_103_page .incity .routecontrol a.hideroute').show();
              var ds = new google.maps.DirectionsService();
              for (var i=0; i<forMap.length; i++) {
                ds.route({
                    destination:new google.maps.LatLng(forMap[i].place.lat, forMap[i].place.lng),
                    origin: results[0].geometry.location,
                    travelMode: google.maps.DirectionsTravelMode.DRIVING
                  }, (function (i) {return function(dres, dstatus) {
                    if (dstatus == google.maps.DirectionsStatus.OK) {
                      var dd = new google.maps.DirectionsRenderer({suppressMarkers: true, preserveViewport: true, polylineOptions: {strokeColor: inst.routeColors[i % inst.routeColors.length], strokeOpacity: 0.9}});
                      dd.setMap(inst.mapGoogle);
                      dd.setDirections(dres);
                      inst.directions.push(dd);
                    }
                };})(i));
              }
            } else {
              alert("Не удалось определить местоположение по введенному адресу");
            }
          });
          return false;
        });
        jQuery('#kdlh20110126_103_page .incity .routecontrol a.hideroute').unbind('click').click(function(){
          var i;
          jQuery('#kdlh20110126_103_page .incity .routecontrol a.hideroute').hide();
          jQuery('#kdlh20110126_103_page .incity .routecontrol .showroute').show();
          inst.bounds = new google.maps.LatLngBounds();
          for (i=0; i<forMap.length; i++) {
            inst.bounds.extend(new google.maps.LatLng(forMap[i].place.lat, forMap[i].place.lng));
          }
          inst.mapGoogle.fitBounds(inst.bounds);
          for (i=0; i<inst.directions.length; i++) {
            inst.directions[i].setMap(null);
          }
          inst.directions = new Array();
          return false;
        });
        var waitshow = function() {
          if (jQuery('#kdlh20110126_103_page .incity .map').height() == 0) {
            window.setTimeout(waitshow, 0);
          } else {
            google.maps.event.trigger(inst.mapGoogle, 'resize');
            inst.mapGoogle.fitBounds(inst.bounds);
          }
        };
        waitshow();
      } else {
        jQuery('#kdlh20110126_103_page .incity .map').hide();
        jQuery('#kdlh20110126_103_page .incity .routecontrol').hide();
      }
    } else {
      jQuery('#kdlh20110126_103_page .incity').hide();
    }
    jQuery('#kdlh20110126_103_page .location span').text(locationname);
    if (this.tree[country].internet.length && this.tree[country].cities[city] && this.tree[country].cities[city].length) {
      jQuery('#kdlh20110126_103_page .typeselect').show();
      jQuery('#kdlh20110126_103_page .ininternet').addClass('typehighlighted');
      jQuery('#kdlh20110126_103_page .incity').addClass('typehighlighted');
      if (jQuery('#kdlh20110126_103_page .typeselect .internet').hasClass('typehighlighted')) {
        jQuery('#kdlh20110126_103_page .typeselect .internet').click();
      } else {
        jQuery('#kdlh20110126_103_page .typeselect .city').click();
      }
    } else {
      jQuery('#kdlh20110126_103_page .typeselect').hide();
      jQuery('#kdlh20110126_103_page .ininternet').removeClass('typehighlighted');
      jQuery('#kdlh20110126_103_page .incity').removeClass('typehighlighted');
    }
  }
};

  if (jQuery('#kdlh20110126_103_page').length > 0) {
    new KD_USER_APPLICATION();
  }
  });
