var map, geocoder, marker, infowindow, position, satellite, country;
var satellites = Array();
var footprints = Array();

var recommended_satellites = {
  'AM': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'AT': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'AZ': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'BA': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'BE': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'BG': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'BY': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'CH': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'CZ': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'DE': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'DK': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'DZ': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'EE': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'ES': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'FI': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'FR': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'GB': {name: 'ASTRA 2A', display: '28.2E: ASTRA 2A'},
  'GE': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'GR': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'HR': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'HU': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'IE': {name: 'ASTRA 2A', display: '28.2E: ASTRA 2A'},
  'IQ': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'IT': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'LB': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'LT': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'LU': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'LV': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'MA': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'MD': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'MK': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'MS': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'NL': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'NO': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'PL': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'RO': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'RU': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'SC': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'SE': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'},
  'SI': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'SK': {name: 'ASTRA 3B', display: '23.5E: ASTRA 3B'},
  'SY': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'TN': {name: 'ASTRA 1M', display: '19.2E: ASTRA 1M'},
  'TR': {name: 'ASTRA 1G', display: '31.E: ASTRA 1G'},
  'UA': {name: 'ASTRA 4A', display: '5.0E: ASTRA 4A'}
};

function initialize() {
  map = new google.maps.Map(document.getElementById("installation_map"), {
    scrollwheel: false,
    disableDefaultUI: true,
    navigationControl: true,
    zoom: 3,
    center: new google.maps.LatLng(56.89, 32.58),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // create draggable marker
  marker = new google.maps.Marker({ map: map, draggable: true, icon: configuration.google_map_marker });
  google.maps.event.addListener(marker, 'dragstart', function() {
    infowindow.close();
    update_infowindow_for_address('');
  });
  google.maps.event.addListener(marker, 'dragend', function() {
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        detect_country(results[0]);
        update_infowindow_for_address(results[0].formatted_address);
        $('#infowindow_recommended_satellite').text('');
        $('#infowindow_elevation').text("-");
        $('#infowindow_azimuth_mag').text("-");
        $('#infowindow_azimuth_true').text("-");
      }
    });
    position_changed_callback(marker.getPosition());
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map, marker);
  });

  // create geocoder and infowindow
  geocoder = new google.maps.Geocoder();
  infowindow = new google.maps.InfoWindow({content: document.getElementById('infowindow')});
}

function detect_country(geocoder_result) {
  $.each(geocoder_result.address_components, function(i, n) {
    if(n.types[0] == "country") { country = n.short_name; }
  });
}

function geocode(address) {
  geocoder.geocode( { 'address': address }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      detect_country(results[0]);
      position_changed_callback(results[0].geometry.location);
    }
  });
};

function update_infowindow_for_address(address) {
  $('#infowindow_address').text(address);
  $('#address').val(address)
}

function update_infowindow_for_position() {
  $('#infowindow_latitude').text(position.lat().toFixed(4));
  $('#infowindow_longitude').text(position.lng().toFixed(4));

  $('#infowindow_satellite_select').hide();
  $('#infowindow_loading').show();

  // update satellite selection
  $('#infowindow_loading').show();
  $.getJSON("http://ws.dishpointer.com/sesDataJSON1.1.php?callback=?", {lat: position.lat(), lng: position.lng()}, function(data) {
    satellites = data.dishpointer.sat;
    $('#infowindow_satellite_select').load(infowindow_path, {satellites: JSON.stringify(satellites), authenticity_token: configuration.authenticity_token}, function() {
      $('#infowindow_satellite_select').show();
      $('#infowindow_loading').hide();
      var recommended_satellite = recommended_satellites[country];
      if(recommended_satellite && no_satellites_in_area == false) {
        $('select#satellite').val(recommended_satellite.name);
        $('#infowindow_recommended_satellite').text(recommended_satellite.display);
      }
      if($('select#satellite').val()) {
        satellite_changed_callback($('select#satellite').val());
      }
    });
  });
}

function update_infowindow_for_satellite() {
  $('#infowindow_elevation').html(satellite.elevation.toFixed(2)+"&deg;");
  $('#infowindow_azimuth_mag').html(satellite.azimuth_mag.toFixed(2)+"&deg;");
  $('#infowindow_azimuth_true').html(satellite.azimuth_true.toFixed(2)+"&deg;");
}

function reset_footprints() {
  $("#infowindow_footprints li").remove();
  $.each(footprints, function(key, value) { value.setMap(null); });
}

function update_footprints_for_satellite() {
  footprints = Array();
  $.each(satellite.footprints, function(key, value) {
    if(value.size > 0) {
      var footprint = new google.maps.KmlLayer(value.fpurl, {map: map, preserveViewport: true, suppressInfoWindows: true});
      footprints.push(footprint);
      $('#infowindow_footprints ul').append('<li>'+value.fpname+'</li>');
    }
  });
}

function position_changed_callback(new_position) {
  position = new_position;
  map.setCenter(position);
  marker.setPosition(position);
  infowindow.setPosition(position);
  infowindow.open(map, marker);
  reset_footprints();
  update_infowindow_for_position();
}

function satellite_changed_callback(name) {
  var data = $.grep(satellites, function(s, i) { return s.name == name; });
  if(data[0]) {
    satellite = data[0];
  } else {
    satellite = satellites[0];
  }

  $.post(remember_satellite_path, {
    satellite: JSON.stringify(satellite),
    latitude: position.lat(),
    longitude: position.lng(),
    authenticity_token: configuration.authenticity_token
  }, function(result) {
    if(result == "0") {
      $('a#view_channels').hide();
    } else {
      $('a#view_channels').show();
    }
  });

  update_infowindow_for_satellite();
  reset_footprints();
  update_footprints_for_satellite();

  // re-initialize fancybox
  $("a#view_channels").fancybox({
    ajax : { type: "GET" }
  });
}

function initialize_slider_for_channel_overlay() {
  var widthGrid = 0;
  $('div.install_equip_item').each(
    function() {
      var widthGrid = $(this).children('div.slider_grey').prevAll('.grid_view').children('ul').children('li').size() * 103 - 800
    $(this).children('div.js_debug').text(widthGrid);
    if(widthGrid > 820) {
      $(this).children('div.slider_grey').slider({
        range: 'min',
        min: 0,
        max: widthGrid,
        animate: true,
        change: function handleChange(e, ui) {$(this).prevAll('div.grid_view').animate({scrollLeft: ui.value}, 1000);},
        slide: function handleSlide(e, ui) {$(this).prevAll('div.grid_view').attr({scrollLeft: ui.value});}
      });
    }
    widthGrid = 0;
  });
}