﻿var SiteMode;

function LTrim(value) {
  var re = /\s*((\S+\s*)*)/;
  return value.replace(re, "$1");
}
function RTrim(value) {
  var re = /((\s*\S+)*)\s*/;
  return value.replace(re, "$1");
}
function trim(value) {
  return LTrim(RTrim(value));
}

function LoadMap() {
  if ('undefined' != typeof (GBrowserIsCompatible)) {
    if (GBrowserIsCompatible()) {
      map = new GMap2(document.getElementById("MapPanel"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(55.15000001, 61.40000001), 2);
      map.setMapType(G_HYBRID_MAP);
    }
  }
}

function CreateIcon(AMarker, AMarkerShadow) {
  var ico = new GIcon();
  ico.iconSize = new GSize(20, 33);
  ico.iconAnchor = new GPoint(10, 34);
  ico.infoWindowAnchor = new GPoint(10, 0);
  ico.shadowSize = new GSize(37, 34);
  ico.image = AMarker;
  ico.shadow = AMarkerShadow;
  return ico;
}

function CreateMarker(APoint, AIcon, AInfoTabs) {
  var marker = new GMarker(APoint, { icon: AIcon });
  GEvent.addListener(marker, 'click', function() { marker.openInfoWindowTabsHtml(AInfoTabs) });
  return marker;
}

function Content(APartner, APartnersCount) {
  if (APartnersCount > 2) {
    APartnersCount = APartnersCount * 120;
  } else {
    APartnersCount = 300;
  }
  var content = "<table style='width: " + APartnersCount + "px;'><tr><td align='left'>";
  content += "Город: <b>" + APartner[6] + "</b><br/>";
  if (APartner[0].indexOf('DIRECTUM') != -1) {
    content += APartner[0] + "<br/>";
  } else {
    content += "Партнер: <b>" + APartner[0] + "</b><br/>";
  }
  if (SiteMode == '10') {
    for (var i = 0; i < APartner[10].length; i++) {
      if (APartner[9][i] == '0') {
        content += "Офис: ";
      }
      if (APartner[9][i] == '100') {
        content += "Место проведения: ";
      }
      content += APartner[10][i] + "<br/>";
    }
  }
  content += "Тел./факс: " + APartner[1].replace('|', '<br/>') + "<br/>";
  var Em = APartner[3].split('|');
  content += "Email: ";
  for (var i = 0; i < Em.length; i++) {
    content += "<a href='malto:" + Em[i] + "' title='Отправить письмо' style='font-size:13px'>" + Em[i] + "</a>";
    if (i < Em.length - 1) {
      content += ", <br/>Доп.: ";
    }
  }
  content += "<br/><a href='" + APartner[4] + "' target='_blank' style='font-size:13px'>" + APartner[4] + "</a><br />";
  content += "</div></td></tr><tr><td valign='top' align='left'>";
  if (SiteMode == '10') {
    content += "<a href='Register.aspx?c=" + escape(APartner[6]) + "&p=" + escape(APartner[0]) + "' style='font-size:13px'>Принять участие</a>";
  }
  content += "</td></tr></table>";
  return content;
}

function TitleTab(AName, ANewLen) {
  var newname = AName;
  if (AName.length > ANewLen) {
    newname = newname.substr(0, ANewLen);
    newname += "...";
  }
  return newname;
}

function MapProcessing() {
  if (map != null) {
    map.clearOverlays();
    for (var i = 0; i < thePartnersCity.length; i++) {
      var InfoTab = new Array();
      var point = 0;
      for (var j = 0; j < thePartnersCity[i][1].length; j++) {
        point = new GLatLng(thePartnersCity[i][1][j][7], thePartnersCity[i][1][j][8]);
        InfoTab[j] = new GInfoWindowTab(TitleTab(thePartnersCity[i][1][j][0], 6), Content(thePartnersCity[i][1][j], j));
      }
      if (point != 0) {
        var icon = CreateIcon('Images\\Markers\\partner1.png', 'Images\\Markers\\shadow.png');
        var marker = CreateMarker(point, icon, InfoTab);
        for (var j = 0; j < thePartnersCity[i][1].length; j++) {
          thePartnersCity[i][1][j][11] = marker;
          thePartnersCity[i][1][j][12] = InfoTab;
        }
        map.setCenter(new GLatLng(55.15000001, 61.40000001), 2);
        map.addOverlay(marker);
      }
    }
  }
}
function CompareLoc(a, b) {
  return a['d'] - b['d'];
}
function FindCityInParners(c) {
  var f = -1;
  for (var i = 0; i < thePartnersCity.length; i++) {
    if (thePartnersCity[i][0] == c) {
      f = i;
      break;
    }
  }
  return f;
}
function SetCurrentCity(el, city, callback) {
  var geocoder = new GClientGeocoder();
  var place;
  var filladr;
  var cityIndex;
  var cityInRus;
  geocoder.getLocations(city, function(response) {
    if (response != null && response.Status.code == 200) {
      cityIndex = -1;
      var i = 0;
      var MaxI = response.Placemark.length;
      while (cityIndex == -1 && i < MaxI) {
        place = response.Placemark[i];
        i++;
        filladr = place.address;
        cityIndex = filladr.indexOf(', город');
      }

      if (cityIndex == -1) {
        cityInRus = city;
      } else {
        cityInRus = filladr.substr(cityIndex + 8);
      }
      if ('undefined' != typeof (el)) {
        el.value = cityInRus;
        if (callback != null) {
          callback(cityInRus);
        }
      }
    }
  });
}
function FillUserAndNearlyLocations(ULel, NLel, city, latitude, longitude, RegInCityText) {
  var geocoder = new GClientGeocoder();
  var place;
  var filladr;
  var cityIndex;
  var cityInRus;
  var tbl;
  geocoder.getLocations(city, function(response) {
    if (response != null && response.Status.code == 200) {

      cityIndex = -1;
      var i = 0;
      var MaxI = response.Placemark.length;
      while (cityIndex == -1 && i < MaxI) {
        place = response.Placemark[i];
        i++;
        filladr = place.address;
        cityIndex = filladr.indexOf(', город');
      }

      if (cityIndex == -1) {
        cityInRus = city;
      } else {
        cityInRus = filladr.substr(cityIndex + 8);
      }
      var f = FindCityInParners(cityInRus);
      if (f != -1) {
        tbl = 'Вы находитесь в городе <a href="#" onclick="OpenMarker(\'' + thePartnersCity[f][0] + '\');return false;">' + thePartnersCity[f][0] + '</a> ';
        if (SiteMode == '10') {
          tbl += '<a href="Register.aspx?c=' + escape(thePartnersCity[f][0]) + '">' + RegInCityText + '</a>';
        }
        ULel.innerHTML = tbl;
      } else {
        ULel.innerHTML = 'Вы находитесь в городе <a href="#" onclick="SetMapCenter(\'' + latitude + '\',\'' + longitude + '\');return false;">' + cityInRus + '</a>';
        var UserLoc = new GLatLng(latitude, longitude)
        var polyline;
        var NearLoc = new Array();

        var marker = new GMarker(UserLoc);
        GEvent.addListener(marker, 'click', function() { marker.openInfoWindow('Вы находитесь тут') });
        map.addOverlay(marker);

        for (var i = 0; i < thePartnersCity.length; i++) {
          polyline = new GPolyline([UserLoc, new GLatLng(thePartnersCity[i][1][0][7], thePartnersCity[i][1][0][8])], "#ff0000", 8, 1, { geodesic: true });
          NearLoc.push({ 'd': (polyline.getLength() / 1000), 'c': thePartnersCity[i], 'p': polyline });
        }
        NearLoc.sort(CompareLoc);

        var tr_class;
        tbl = '<table cellpadding="0" cellspacing="0" class="UsersTable">';
        tbl += '<tr>';
        if (SiteMode == '10') {
          tbl += '<th colspan="3" style="padding-left:15px;text-align:left!important;">Ближайшие к вам мероприятия</th>';
        } else {
          tbl += '<th colspan="2" style="padding-left:15px;text-align:left!important;">Ближайшие к вам мероприятия</th>';
        }
        tbl += '</tr>';
        for (i = 0; i < 3 && i < NearLoc.length; i++) {
          if (i % 2 == 0) { tr_class = 'odd'; } else { tr_class = "even"; }
          tbl += '<tr class="' + tr_class + '">';
          tbl += '<td><a href="#" onclick="OpenMarker(\'' + NearLoc[i]['c'][0] + '\'); return false;">' + NearLoc[i]['c'][0] + '</a></td>';
          tbl += '<td>' + (Math.round(NearLoc[i]['d'] * 1000) / 1000) + ' км.</td>';
          if (SiteMode == '10') {
            tbl += '<td class="last"><a href="Register.aspx?c=' + escape(NearLoc[i]['c'][0]) + '">Участвовать</a></td>';
          }
          tbl += '</tr>';
          map.addOverlay(NearLoc[i]['p']);
        }
        tbl += '<tr class="last"><td colspan="3">&nbsp;</td></tr>';
        tbl += '</table><br/>';
        NLel.innerHTML = tbl;
        NLel.style.display = 'block';
      }
      SetMapCenter(latitude, longitude);
    }
  });
}
function OpenMarker(City) {
  if ('undefined' != typeof (thePartnersCity)) {
    var f = FindCityInParners(City);
    if (f > -1) {
      var marker = thePartnersCity[f][1][0][11];
      var point = marker.getPoint();
      SetMapCenter(point.lat(), point.lng());
      //marker.openInfoWindowTabsHtml(thePartnersCity[f][1][0][12]);
    }
  } else {
    //window.location.href = 'default.aspx?c=' + escape(City);
  }
}
function SetMapCenter(latitude, longitude) {
  map.setCenter(new GLatLng(latitude, longitude), 5);
}

var Cities;
function OnChangeCity(el, PartnersID) {
  var p_el = document.getElementById(PartnersID);
  var old_p = p_el.value;
  // Delete all
  while (p_el.options.length > 0) {
    if (p_el.remove) p_el.remove(0);
    else if (p_el.options.remove) p_el.options.remove(0);
  }

  var newopt = '';
  var v = el.value;
  if (Cities[v] != null) {
    for (var i = 0; i < Cities[v].length; i++) {
      p_el.options[i] = new Option(Cities[v][i], Cities[v][i]);
    }
  } else {
    p_el.options[0] = new Option('Выберите партнера', '0');
    var k = 1;
    for (c in Cities) {
      for (var i = 0; i < Cities[c].length; i++) {
        p_el.options[k] = new Option(Cities[c][i], Cities[c][i]);
        k++;
      }
    }
  }
  p_el.value = old_p;
}
function OnChangePartner(el, CityID) {
  var f = '';
  var v = el.value;
  for (c in Cities) {
    for (var i = 0; i < Cities[c].length; i++) {
      if (Cities[c][i] == v) {
        f = c;
        break;
      }
    }
    if (f != '') break;
  }
  var c_el = document.getElementById(CityID);
  if (f != '' && c_el.value == '0') {
    c_el.value = f;
    c_el.onchange();
  }
}
function ShowUserList(el, UserListContID) {
  var v = el.value;
  var ul_el = document.getElementById(UserListContID);
  var ul = '';
  if (UserInCities[v] != null) {
    ul += '<table cellpadding="0" cellspacing="0" class="UsersTable">';
    ul += '<tr>';
    ul += '<th>Компания</th>';
    ul += '<th>Должность</th>';
    ul += '<th>ФИО</th>';
    ul += '<th>Партнер</th>';
    ul += '</tr>';
    for (var i = 0; i < UserInCities[v].length; i++) {
      if (i % 2 == 0) { tr_class = 'odd'; } else { tr_class = "even"; }
      ul += '<tr class="' + tr_class + '">';
      ul += '<td valign="top">' + UserInCities[v][i]['Company'] + '';
      ul += '<div style="padding-top:5px;">';
      ul += '<b>Отрасль:</b>&nbsp;' + UserInCities[v][i]['Industry'] + '<br/>';
      ul += '<b>День:</b>&nbsp;' + UserInCities[v][i]['Day'];
      ul += '</div>';
      ul += '</td>';

      ul += '<td valign="top">' + UserInCities[v][i]['Job'] + '</td>';
      ul += '<td valign="top">' + UserInCities[v][i]['FIO'] + '</td>';
      ul += '<td valign="top" align="center">' + UserInCities[v][i]['Partner'];
      ul += '</td>';
      ul += '</tr>';
    }
    ul += '<tr class="last"><td colspan="7">&nbsp;</td></tr>';
    ul += '</table><br/>';
    ul += '<div class="UsersChooseCity" style="text-align:right;">Всего участников: ' + (UserInCities[v].length) + '</div>';
  }
  ul_el.innerHTML = ul;
}

function ShowInfoCity(InfoID) {
  var Info = document.getElementById(InfoID);
  Info.style.display = 'block';
  setTimeout(function() {
    window['InfoID'] = InfoID;
  }, 200);
}
function HideInfoCity(InfoID) {
  if (InfoID == null) {
    if ('undefined' != typeof (window['InfoID'])) {
      InfoID = window['InfoID'];
    }
  }
  if (InfoID != null) {
    var Info = document.getElementById(InfoID);
    Info.style.display = 'none';
    window['InfoID'] = null;
  }
}

function HighlightCity() {
  var ofset = [0, -1, 1, 2, 3];
  var MSK = 3;
  var CURRENT = -(new Date()).getTimezoneOffset() / 60;
  var f = null;
  for (var i = 0; i < 5; i++) {
    if (ofset[i] == (CURRENT - MSK)) {
      f = $('#city' + i);
      break;
    }
  }
  if (f != null) {
    f.parent().addClass('HighlightCity');
  }
}

function ProgramByCity(n) {
  var ob = $('#CityTZ');
  if (ob.length == 0) {
    location.href = 'About.aspx?c=' + n;
  } else {
    SelectCityTZ(n);
  }
}
function ShowTimeZone(z) {
  if (z == -1) z = "M1";
  $('div[id*="MSK"]').hide();
  $('div[id="MSK' + z + '"]').show();
  if (z == 100) {
    $('#Base').removeClass('ProgramZone').addClass('ProgramZoneSel');
    $('#CityTZ').val('100');
  } else {
    $('#Base').removeClass('ProgramZoneSel').addClass('ProgramZone');
  }
}
function ProgramZone(z, el) {
  ShowTimeZone(z);
}
function ChangeCityTZ(el) {
  var t = ['13:00', '14:00', '13:30', '14:30', '14:00'];
  var z = parseInt(el.value);
  if (z == 100) {
    $('span.day').html('&nbsp;');
  } else {
    var tStr = t[z + 1];
    $('span.day').html('<h3 style="display:inline;">в ' + tStr + '</h3>');
  }
}
function SelectCityTZ(Name) {
  $.each($('#CityTZ').find('option'), function() {
    var self = $(this);
    if (self.text() == Name) {
      self.attr('selected', true);
    }
  });
  ChangeCityTZ($('#CityTZ').get(0));
}
