$(document).ready(function()
{

  
  var bg   = [ 8, 6, 6, 12, 14, 2, 2, 4, 4, 7, 9, 10, 3, 15, 9, 13, 11, 1, 11, 5, 8, 12, 14, 8 ];
  var d = new Date();
  
  $(document).bgStretcher(
  { images:      [ "/img/backgrounds/c21-backgrounds"
                   + bg[d.getHours()]
                   + ".jpg" ],
    imageWidth:  2100,
    imageHeight: 1200,
    slideShow:   false,
    resizeProportionally: true
  });
});

var global_xformsSubmitInProcess = new Array();

function checkXFormsSubmit(aForm)
{
   for (i = 0; i < global_xformsSubmitInProcess.length; i++)
   {
      if (global_xformsSubmitInProcess[i] == aForm.name)
      {
         return false;
      }
   }

   global_xformsSubmitInProcess[global_xformsSubmitInProcess.length]  = aForm.name;

   for (i = 0; i < aForm.length; i++)
   {
      switch (aForm.elements[i].type)
      {
         case "button":
         case "reset":
         case "submit":
            aForm.elements[i].disabled = true;
      }
   }

   return true;
}

function xformsActivateTab(container, tab, keyElement)
{
  $('#' + container + '>ul.tab>li.active').removeClass('active');
  $('#' + tab).addClass('active');
  
  $('#' + container + '>div.active-tab-content').addClass('tab-content');
  $('#' + container + '>div.active-tab-content').removeClass('active-tab-content');
  $('#' + tab + '-content').addClass('active-tab-content');
  $('#' + tab + '-content').removeClass('tab-content');

  keyElement.value = tab;
}

function submitForm(aForm, evalCode)
{
   if (aForm.onsubmit())
   {
      if (evalCode != null && evalCode != "")
         eval(evalCode);

      aForm.submit();
   }
}

$(document).ready(function()
{
  $(".xforms-wizard .focus:last").focus();
  //$(".xforms-wizard :input:visible:enabled:first").focus();
  //$(".xforms-wizard :text:first").focus();
});

$(document).ready(function()
{
  var kraj;
  
  kraj = $('#kraj').val();
  
  if (kraj != "")
    show_kraj_SK01(kraj);
});

function show_kraj_map_SK01(id, label, visibility)
{
  var e = $('#krajMap');

  if (visibility)
  {
    $('#krajLabel').text(id == $('#kraj').val()
                         ? "[ " + label + " ]"
                         : label);
    e.attr('src', '/img/SK01/map_region_' + id + '.gif');
  }
  else if($('#kraj').val() != "")
  {
    $('#krajLabel').text("[ " + $('#kraj_label').val() + " ]");
    e.attr('src', '/img/SK01/map_region_' + $('#kraj').val() + '.gif');
  }
  else
  {
    $('#krajLabel').text('');
    e.attr('src', '/img/SK01/map_region.gif');
  }
}

function show_kraj_SK01(id, label)
{
  $('#kraj').val(id);
  $('#kraj_label').val(label);
  
  $('#krajLabel').text("[ " + label + " ]");
  $('#krajMap').attr('src', '/img/SK01/map_region_' + id + '.gif');
}

var global_resizeMap = true, global_latLngBounds, global_marker = [], global_infoWindow, global_infoWindowMarker, global_activeLocality = 0;
var global_markerCluster;

function resizeMap(map, fitBounds)
{
  if (typeof google === 'undefined')
    return;

  google.maps.event.trigger(map, 'resize');

  if (fitBounds)
    map.fitBounds(global_latLngBounds);
}

function initAddressMap(container)
{
  var map, location;
  
  if (typeof google === 'undefined')
    return;

  if ($('#' + container).length == 0)
    return;
  
  global_latLngBounds = new google.maps.LatLngBounds();
  global_infoWindow   = new google.maps.InfoWindow( { disableAutoPan: true } );
  
  map = new google.maps.Map(document.getElementById(container),
                            {
                              zoom:         8,
                              center:       new google.maps.LatLng(48.669199, 19.598486),
                              mapTypeId:    google.maps.MapTypeId.ROADMAP,
                              scrollwheel:  false
                            });

  document.getElementById(container)._gmap = map;
  
  var styles = [
                {
                  url: 'http://mediaservice.force.sk/gmaps/markerclusterer/img/m1.png',
                  height: 52,
                  width: 53
                },
                {
                  url: 'http://mediaservice.force.sk/gmaps/markerclusterer/img/m2.png',
                  height: 56,
                  width: 55
                },
                {
                  url: 'http://mediaservice.force.sk/gmaps/markerclusterer/img/m3.png',
                  height: 66,
                  width: 65
                },
                {
                  url: 'http://mediaservice.force.sk/gmaps/markerclusterer/img/m4.png',
                  height: 78,
                  width: 77
                },
                {
                  url: 'http://mediaservice.force.sk/gmaps/markerclusterer/img/m5.png',
                  height: 90,
                  width: 89
                }
               ];
  
  global_markerCluster = new MarkerClusterer(map, [], { styles: styles });
  
  google.maps.event.addListener(global_markerCluster,
                                "clusterclick",
                                function(cluster)
                                {
                                  closeMarkerClusterInfoWindow(cluster);
                                });
  google.maps.event.addListener(global_markerCluster,
                                "clustermouseover",
                                function(cluster)
                                {
                                  openMarkerClusterInfoWindow(cluster);
                                });
}

function prevInfoWindowItem()
{
  var index = $('.marker-info-window-cluster .marker-info-window.active').index();
  var size  = $('.marker-info-window-cluster .marker-info-window').length;
  
  if (index > 0)
    activateInfoWindowItem(index - 1);
  else
    activateInfoWindowItem(size - 1);
}

function nextInfoWindowItem()
{
  var index = $('.marker-info-window-cluster .marker-info-window.active').index();
  var size  = $('.marker-info-window-cluster .marker-info-window').length;
  
  if (index + 1 < size)
    activateInfoWindowItem(index + 1);
  else
    activateInfoWindowItem(0);
}

function activateInfoWindowItem(index)
{
  var size  = $('.marker-info-window-cluster .marker-info-window').length;
  
  $('.marker-info-window-cluster .marker-info-window.active').removeClass('active');
  $('.marker-info-window-cluster .marker-info-window:eq(' + index + ')').addClass('active');
  
  $('.marker-info-window-cluster .nav-toolbar .desc').html((index + 1) + " / " + size);
  
  var id = $('.marker-info-window-cluster .marker-info-window:eq(' + index + ')')
           .attr('id')
           .substring("infoWindowItem-".length);
  
  showActiveMapItem(id);
}

function removeInfoWindowItem(id)
{
  var infoWindowItem = $('#infoWindowItem-' + id);

  if (infoWindowItem.length != 0)
  {
    var index    = infoWindowItem.index();
    var newIndex = index;
    var size     = $('.marker-info-window-cluster .marker-info-window').length;
    
    if (index + 1 < size)
      newIndex = index;
    else if (index > 0)
      newIndex = index - 1;

    infoWindowItem.remove();
    
    size = $('.marker-info-window-cluster .marker-info-window').length;
    
    if (size != 0)
    {
      activateInfoWindowItem(newIndex);
    }
    else
    {
      global_infoWindow.close();
      global_infoWindowMarker = null;
    }
  }
}

function findGlobalMarker(marker)
{
  for (var i = 0; i < global_marker.length; i++)
  {
    if (global_marker[i].marker == marker)
      return global_marker[i];
  }
  
  return null;
}

function findGlobalMarkerById(id)
{
  for (var i = 0; i < global_marker.length; i++)
  {
    if (global_marker[i].id == id)
      return global_marker[i];
  }
  
  return null;
}

function openInfoWindow(marker)
{
  global_infoWindowMarker = marker;
    
  global_infoWindow.close     ();
  global_infoWindow.setContent(paintInfoWindow(marker));
  global_infoWindow.open      (marker.getMap(), marker);
  
  showActiveMapItem(findGlobalMarker(marker).dataObj.id);
}

function openMarkerClusterInfoWindow(cluster, index)
{
  var markers = cluster.getMarkers();
  
  global_infoWindowMarker = null;
  
  global_infoWindow.close     ();
  global_infoWindow.setContent(paintMarkerClusterInfoWindow(markers));
  global_infoWindow.open      (cluster.getMap());
  global_infoWindow.setOptions( { position: new google.maps.LatLng(cluster.getCenter().lat(), cluster.getCenter().lng()),
                                  pixelOffset: new google.maps.Size(10, -10) });
  
  if (index == null)
    index = 0;
  
  activateInfoWindowItem(index);
  showActiveMapItem(findGlobalMarker(markers[index]).dataObj.id);
}

function closeMarkerClusterInfoWindow(cluster, index)
{
  global_infoWindowMarker = null;
  
  global_infoWindow.close();
}

function showItem(id, url)
{
  var openInfoWindowTimeout = 0;
  
  if (global_markerCluster != null && global_markerCluster.getMap().getZoom() != 18)
  {
    global_markerCluster.getMap()
                        .setZoom(18);

    openInfoWindowTimeout = 2000;
  }
  
  if ($('#page-content-header-map').hasClass('active'))
    showActiveMapItem(id);
  else
    showDetail(id);

  var globalMarker = findGlobalMarkerById(id);
  var marker       = globalMarker != null
                       ? globalMarker.marker
                       : null;

  if (marker != null)
  {
    global_markerCluster.getMap()
                        .setCenter(marker.getPosition());
  }

  setTimeout(function()
  {
    var cluster      = global_markerCluster != null
                        ? global_markerCluster.getMarkerCluster(marker)
                        : null;
    var markers      = cluster != null
                        ? cluster.getMarkers()
                        : null;
    
    if (marker != null)
    {
      if (markers == null || markers.length == 1)
      {
        openInfoWindow(marker);
      }
      else
      {
        openMarkerClusterInfoWindow(cluster, cluster.getMarkerIndex(marker));
      }
    }
  }, openInfoWindowTimeout);
}

function toggleSidebarVisibility(sidebar, mapContent, paginationBox, map)
{
  $('#' + sidebar)           .toggleClass('collapsed');
  $('#' + sidebar + '-frame').toggleClass('collapsed');
  $('#' + mapContent)        .toggleClass('collapsed');
  $('#' + paginationBox)     .toggleClass('collapsed');


  resizeMap(document.getElementById(map)._gmap, false);
}

var global_loadNextAmount = 0;
var global_MapItemsPanelSidebarLeft = 0;

$(document).ready(function()
{
  checkBackButton();

  // update localities
  
  initLocality();
  
  // show/hide property specific sidebar_content
  
  function checkSidebarContentVisibility()
  {
    $('#sidebar_tab_property_content .property-type input[name=propertyType]').each(
      function()
      {
        var obj          = $(this);
        var propertyType = obj.val();
        
        if (obj.is(':checked'))
          $('#sidebar_tab_property_content .sidebar_content_' + propertyType).show();
        else
          $('#sidebar_tab_property_content .sidebar_content_' + propertyType).hide();
      });
  }
  
  checkSidebarContentVisibility();
  
  $('#sidebar_tab_property_content .property-type input[name=propertyType]').click(checkSidebarContentVisibility);

  // land

  $("#landPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#landPriceValueRange').val().split(":").length - 1,
    values: [$('#landPriceLoIndex').val(), $('#landPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#landPriceLoIndex').val(ui.values[0]);
              $('#landPriceHiIndex').val(ui.values[1]);

              $('#landPriceLo').val($('#landPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#landPriceHi').val($('#landPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#landPriceValue').text($('#landPriceValueRange').val().split(":")[ui.values[0]]
                                        + ' - '
                                        + $('#landPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#landPriceValue').text($('#landPriceValueRange').val().split(":")[$("#landPrice .slider-control").slider("values", 0)]
                              + ' - '
                              + $('#landPriceValueRange').val().split(":")[$("#landPrice .slider-control").slider("values", 1)]);

  $("#landLeasingPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#landLeasingPriceValueRange').val().split(":").length - 1,
    values: [$('#landLeasingPriceLoIndex').val(), $('#landLeasingPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#landLeasingPriceLoIndex').val(ui.values[0]);
              $('#landLeasingPriceHiIndex').val(ui.values[1]);

              $('#landLeasingPriceLo').val($('#landLeasingPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#landLeasingPriceHi').val($('#landLeasingPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#landLeasingPriceValue').text($('#landLeasingPriceValueRange').val().split(":")[ui.values[0]]
                                               + ' - '
                                               + $('#landLeasingPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#landLeasingPriceValue').text($('#landLeasingPriceValueRange').val().split(":")[$("#landLeasingPrice .slider-control").slider("values", 0)]
                                     + ' - '
                                     + $('#landLeasingPriceValueRange').val().split(":")[$("#landLeasingPrice .slider-control").slider("values", 1)]);

  $("#landTotalArea .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#landTotalAreaRange').val().split(":").length - 1,
    values: [$('#landTotalAreaLo').val(), $('#landTotalAreaHi').val()],
    slide:  function(event, ui)
            {
              $('#landTotalAreaLo').val(ui.values[0]);
              $('#landTotalAreaHi').val(ui.values[1]);

              $('#landTotalAreaValue').text($('#landTotalAreaRange').val().split(":")[ui.values[0]]
                                            + ' - '
                                            + $('#landTotalAreaRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#landTotalAreaValue').text($('#landTotalAreaRange').val().split(":")[$("#landTotalArea .slider-control").slider("values", 0)]
                                  + ' - '
                                  + $('#landTotalAreaRange').val().split(":")[$("#landTotalArea .slider-control").slider("values", 1)]);

  // flat

  $("#flatPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#flatPriceValueRange').val().split(":").length - 1,
    values: [$('#flatPriceLoIndex').val(), $('#flatPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#flatPriceLoIndex').val(ui.values[0]);
              $('#flatPriceHiIndex').val(ui.values[1]);

              $('#flatPriceLo').val($('#flatPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#flatPriceHi').val($('#flatPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#flatPriceValue').text($('#flatPriceValueRange').val().split(":")[ui.values[0]]
                                        + ' - '
                                        + $('#flatPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#flatPriceValue').text($('#flatPriceValueRange').val().split(":")[$("#flatPrice .slider-control").slider("values", 0)]
                              + ' - '
                              + $('#flatPriceValueRange').val().split(":")[$("#flatPrice .slider-control").slider("values", 1)]);

  $("#flatLeasingPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#flatLeasingPriceValueRange').val().split(":").length - 1,
    values: [$('#flatLeasingPriceLoIndex').val(), $('#flatLeasingPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#flatLeasingPriceLoIndex').val(ui.values[0]);
              $('#flatLeasingPriceHiIndex').val(ui.values[1]);

              $('#flatLeasingPriceLo').val($('#flatLeasingPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#flatLeasingPriceHi').val($('#flatLeasingPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#flatLeasingPriceValue').text($('#flatLeasingPriceValueRange').val().split(":")[ui.values[0]]
                                               + ' - '
                                               + $('#flatLeasingPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#flatLeasingPriceValue').text($('#flatLeasingPriceValueRange').val().split(":")[$("#flatLeasingPrice .slider-control").slider("values", 0)]
                                     + ' - '
                                     + $('#flatLeasingPriceValueRange').val().split(":")[$("#flatLeasingPrice .slider-control").slider("values", 1)]);

  $("#flatFloorArea .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#flatFloorAreaRange').val().split(":").length - 1,
    values: [$('#flatFloorAreaLo').val(), $('#flatFloorAreaHi').val()],
    slide:  function(event, ui)
            {
              $('#flatFloorAreaLo').val(ui.values[0]);
              $('#flatFloorAreaHi').val(ui.values[1]);

              $('#flatFloorAreaValue').text($('#flatFloorAreaRange').val().split(":")[ui.values[0]]
                                            + ' - '
                                            + $('#flatFloorAreaRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#flatFloorAreaValue').text($('#flatFloorAreaRange').val().split(":")[$("#flatFloorArea .slider-control").slider("values", 0)]
                                  + ' - '
                                  + $('#flatFloorAreaRange').val().split(":")[$("#flatFloorArea .slider-control").slider("values", 1)]);





  // house

  $("#housePrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#housePriceValueRange').val().split(":").length - 1,
    values: [$('#housePriceLoIndex').val(), $('#housePriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#housePriceLoIndex').val(ui.values[0]);
              $('#housePriceHiIndex').val(ui.values[1]);

              $('#housePriceLo').val($('#housePriceKeyRange').val().split(":")[ui.values[0]]);
              $('#housePriceHi').val($('#housePriceKeyRange').val().split(":")[ui.values[1]]);

              $('#housePriceValue').text($('#housePriceValueRange').val().split(":")[ui.values[0]]
                                         + ' - '
                                         + $('#housePriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#housePriceValue').text($('#housePriceValueRange').val().split(":")[$("#housePrice .slider-control").slider("values", 0)]
                               + ' - '
                               + $('#housePriceValueRange').val().split(":")[$("#housePrice .slider-control").slider("values", 1)]);

  $("#houseLeasingPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#houseLeasingPriceValueRange').val().split(":").length - 1,
    values: [$('#houseLeasingPriceLoIndex').val(), $('#houseLeasingPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#houseLeasingPriceLoIndex').val(ui.values[0]);
              $('#houseLeasingPriceHiIndex').val(ui.values[1]);

              $('#houseLeasingPriceLo').val($('#houseLeasingPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#houseLeasingPriceHi').val($('#houseLeasingPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#houseLeasingPriceValue').text($('#houseLeasingPriceValueRange').val().split(":")[ui.values[0]]
                                                + ' - '
                                                + $('#houseLeasingPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#houseLeasingPriceValue').text($('#houseLeasingPriceValueRange').val().split(":")[$("#houseLeasingPrice .slider-control").slider("values", 0)]
                                      + ' - '
                                      + $('#houseLeasingPriceValueRange').val().split(":")[$("#houseLeasingPrice .slider-control").slider("values", 1)]);

  $("#houseUsableArea .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#houseUsableAreaRange').val().split(":").length - 1,
    values: [$('#houseUsableAreaLo').val(), $('#houseUsableAreaHi').val()],
    slide:  function(event, ui)
            {
              $('#houseUsableAreaLo').val(ui.values[0]);
              $('#houseUsableAreaHi').val(ui.values[1]);

              $('#houseUsableAreaValue').text($('#houseUsableAreaRange').val().split(":")[ui.values[0]]
                                              + ' - '
                                              + $('#houseUsableAreaRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#houseUsableAreaValue').text($('#houseUsableAreaRange').val().split(":")[$("#houseUsableArea .slider-control").slider("values", 0)]
                                    + ' - '
                                    + $('#houseUsableAreaRange').val().split(":")[$("#houseUsableArea .slider-control").slider("values", 1)]);

  // commercial

  $("#commercialPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#commercialPriceValueRange').val().split(":").length - 1,
    values: [$('#commercialPriceLoIndex').val(), $('#commercialPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#commercialPriceLoIndex').val(ui.values[0]);
              $('#commercialPriceHiIndex').val(ui.values[1]);

              $('#commercialPriceLo').val($('#commercialPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#commercialPriceHi').val($('#commercialPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#commercialPriceValue').text($('#commercialPriceValueRange').val().split(":")[ui.values[0]]
                                              + ' - '
                                              + $('#commercialPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#commercialPriceValue').text($('#commercialPriceValueRange').val().split(":")[$("#commercialPrice .slider-control").slider("values", 0)]
                                    + ' - '
                                    + $('#commercialPriceValueRange').val().split(":")[$("#commercialPrice .slider-control").slider("values", 1)]);

  $("#commercialLeasingPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#commercialLeasingPriceValueRange').val().split(":").length - 1,
    values: [$('#commercialLeasingPriceLoIndex').val(), $('#commercialLeasingPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#commercialLeasingPriceLoIndex').val(ui.values[0]);
              $('#commercialLeasingPriceHiIndex').val(ui.values[1]);

              $('#commercialLeasingPriceLo').val($('#commercialLeasingPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#commercialLeasingPriceHi').val($('#commercialLeasingPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#commercialLeasingPriceValue').text($('#commercialLeasingPriceValueRange').val().split(":")[ui.values[0]]
                                                     + ' - '
                                                     + $('#commercialLeasingPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#commercialLeasingPriceValue').text($('#commercialLeasingPriceValueRange').val().split(":")[$("#commercialLeasingPrice .slider-control").slider("values", 0)]
                                           + ' - '
                                           + $('#commercialLeasingPriceValueRange').val().split(":")[$("#commercialLeasingPrice .slider-control").slider("values", 1)]);

  $("#commercialOfficesArea .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#commercialOfficesAreaRange').val().split(":").length - 1,
    values: [$('#commercialOfficesAreaLo').val(), $('#commercialOfficesAreaHi').val()],
    slide:  function(event, ui)
            {
              $('#commercialOfficesAreaLo').val(ui.values[0]);
              $('#commercialOfficesAreaHi').val(ui.values[1]);

              $('#commercialOfficesAreaValue').text($('#commercialOfficesAreaRange').val().split(":")[ui.values[0]]
                                                    + ' - '
                                                    + $('#commercialOfficesAreaRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#commercialOfficesAreaValue').text($('#commercialOfficesAreaRange').val().split(":")[$("#commercialOfficesArea .slider-control").slider("values", 0)]
                                          + ' - '
                                          + $('#commercialOfficesAreaRange').val().split(":")[$("#commercialOfficesArea .slider-control").slider("values", 1)]);

  // other

  $("#otherPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#otherPriceValueRange').val().split(":").length - 1,
    values: [$('#otherPriceLoIndex').val(), $('#otherPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#otherPriceLoIndex').val(ui.values[0]);
              $('#otherPriceHiIndex').val(ui.values[1]);

              $('#otherPriceLo').val($('#otherPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#otherPriceHi').val($('#otherPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#otherPriceValue').text($('#otherPriceValueRange').val().split(":")[ui.values[0]]
                                         + ' - '
                                         + $('#otherPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#otherPriceValue').text($('#otherPriceValueRange').val().split(":")[$("#otherPrice .slider-control").slider("values", 0)]
                               + ' - '
                               + $('#otherPriceValueRange').val().split(":")[$("#otherPrice .slider-control").slider("values", 1)]);

  $("#otherLeasingPrice .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#otherLeasingPriceValueRange').val().split(":").length - 1,
    values: [$('#otherLeasingPriceLoIndex').val(), $('#otherLeasingPriceHiIndex').val()],
    slide:  function(event, ui)
            {
              $('#otherLeasingPriceLoIndex').val(ui.values[0]);
              $('#otherLeasingPriceHiIndex').val(ui.values[1]);

              $('#otherLeasingPriceLo').val($('#otherLeasingPriceKeyRange').val().split(":")[ui.values[0]]);
              $('#otherLeasingPriceHi').val($('#otherLeasingPriceKeyRange').val().split(":")[ui.values[1]]);

              $('#otherLeasingPriceValue').text($('#otherLeasingPriceValueRange').val().split(":")[ui.values[0]]
                                                + ' - '
                                                + $('#otherLeasingPriceValueRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#otherLeasingPriceValue').text($('#otherLeasingPriceValueRange').val().split(":")[$("#otherLeasingPrice .slider-control").slider("values", 0)]
                                      + ' - '
                                      + $('#otherLeasingPriceValueRange').val().split(":")[$("#otherLeasingPrice .slider-control").slider("values", 1)]);

  $("#otherOfficesArea .slider-control").slider({
    range:  true,
    min:    0,
    max:    $('#otherOfficesAreaRange').val().split(":").length - 1,
    values: [$('#otherOfficesAreaLo').val(), $('#otherOfficesAreaHi').val()],
    slide:  function(event, ui)
            {
              $('#otherOfficesAreaLo').val(ui.values[0]);
              $('#otherOfficesAreaHi').val(ui.values[1]);

              $('#otherOfficesAreaValue').text($('#otherOfficesAreaRange').val().split(":")[ui.values[0]]
                                               + ' - '
                                               + $('#otherOfficesAreaRange').val().split(":")[ui.values[1]]);
            }
    });
    
    $('#otherOfficesAreaValue').text($('#otherOfficesAreaRange').val().split(":")[$("#otherOfficesArea .slider-control").slider("values", 0)]
                                     + ' - '
                                     + $('#otherOfficesAreaRange').val().split(":")[$("#otherOfficesArea .slider-control").slider("values", 1)]);
});

function changeEventOffer()
{
  var offerVal = $('input[name=offer]:checked').val();
  
  if (offerVal == "LEASING")
  {
    $('#landLeasingPrice')      .removeClass('hide');
    $('#flatLeasingPrice')      .removeClass('hide');
    $('#houseLeasingPrice')     .removeClass('hide');
    $('#commercialLeasingPrice').removeClass('hide');
    $('#otherLeasingPrice')     .removeClass('hide');

    $('#landPrice')      .addClass('hide');
    $('#flatPrice')      .addClass('hide');
    $('#housePrice')     .addClass('hide');
    $('#commercialPrice').addClass('hide');
    $('#otherPrice')     .addClass('hide');
  }
  else
  {
    $('#landPrice')      .removeClass('hide');
    $('#flatPrice')      .removeClass('hide');
    $('#housePrice')     .removeClass('hide');
    $('#commercialPrice').removeClass('hide');
    $('#otherPrice')     .removeClass('hide');

    $('#landLeasingPrice')      .addClass('hide');
    $('#flatLeasingPrice')      .addClass('hide');
    $('#houseLeasingPrice')     .addClass('hide');
    $('#commercialLeasingPrice').addClass('hide');
    $('#otherLeasingPrice')     .addClass('hide');
  }
}

function loadNextPage()
{
  if (activityNotificationCheck("listPaginationNotification"))
    return;

//   if ($('#listPagination').length == 0 || $('#listPagination').hasClass('hide'))
//     return;

  activityNotificationStart("listPaginationNotification");

  $.ajax({
    url: '/property/list-next-page',
    type: 'POST',
    data: {},
    dataType: 'html',
    success: function(data, textStatus) {
      var propertyList, propertyMapList;
      var pageSize, size;
      var map;
      
      activityNotificationStop("listPaginationNotification");
      
//       if ($(data).attr('next-page') == "false")
//         $('#listPagination').addClass('hide');
      
      pageSize = $(data).attr('page-size');
      size     = $(data).attr('size');
      
//       $('#property-list-pagination-box .counter-box').html(pageSize + " / " + size);
      
//       propertyList = $('.property-list');
//       $(data).children('.item').each(function()
//       {
//         propertyList.append($(this));
//       });
      
      propertyMapList = $('#property-list-map-items-panel-sidebar-left');
      $(data).children('.map-item').each(function()
      {
        propertyMapList.append($(this));
      });
      
      map = document.getElementById('property-list-map')._gmap;
      
      $(data).children('.property').each(function()
      {
        createAddressMapMarker(map,
                               { id:       $(this).attr('id'),
                                 nice_url: $(this).children('.nice-url').text(),
                                 document: $(this).children('.document').text(),
                                 address:  $(this).children('.address').text(),
                                 offer:    { price: $(this).children('.offer').children('.price').text(),
                                             price_plain: $(this).children('.offer').children('.price').attr('price-plain'),
                                             currency: $(this).children('.offer').children('.currency').text(),
                                             unit: $(this).children('.offer').children('.unit').text(),
                                             unit_value: $(this).children('.offer').children('.unit').attr('value') },
                                 location: { latitude:  $(this).children('.location').children('.latitude').text(),
                                             longitude: $(this).children('.location').children('.longitude').text() }
                                });
      });
      
      global_loadNextAmount -= pageSize;
      
      if (global_loadNextAmount > 0)
        loadNextPage();
      else
        global_loadNextAmount = 0;
    },
    error: function(xhr, textStatus, errorThrown) {
      activityNotificationStop("listPaginationNotification");
    }
  });
}

function checkBackButton()
{
  if (window.location.href.indexOf("#") == -1 && getViewMode() != "list")
    changeView('list');
  else if (window.location.href.indexOf("#property-list-mark") != -1 && getViewMode() != "list")
    changeView('list');
//  else if (window.location.href.indexOf("#property-map-mark") != -1 && getViewMode() != "map")
//    changeView('map');
  else if (window.location.href.indexOf("#property-detail-mark") != -1 && getViewMode() != "detail")
    changeView('detail');
  
  setTimeout(checkBackButton, 500);
}

function changeView(mode)
{
  if (mode == "map")
  {
    $('#page-content-header-list')  .removeClass('active');
    $('#page-content-header-map')   .addClass('active');
    $('#page-content-header-detail').removeClass('active');

    $('#property-list-pagination-box').removeClass('list-mode');
    $('#property-list-pagination-box').addClass('map-mode');
    $('#property-list-pagination-box').removeClass('detail-mode');

    $('#property-list-map-sidebar-left').removeClass('list-mode');
    $('#property-list-map-sidebar-left').addClass('map-mode');
    $('#property-list-map-sidebar-left').removeClass('detail-mode');
    
    $('#property-list-sidebar-left').addClass('hide');
    $('#f-property-search-result')  .addClass('hide');
    $('#page-sidebar-right')        .addClass('hide');
    
    $('#property-list-map-sidebar-left').removeClass('hide');
    $('#property-map-search-result')    .removeClass('hide');
    
    $('#property-list-detail').addClass('hide');
    
    if (global_resizeMap)
    {
      global_resizeMap = false;
      resizeMap(document.getElementById('property-list-map')._gmap, true);
    }
  }
  else if (mode == "detail")
  {
    $('#page-content-header-list')  .removeClass('active');
    $('#page-content-header-map')   .removeClass('active');
    $('#page-content-header-detail').addClass('active');

    $('#property-list-pagination-box').removeClass('list-mode');
    $('#property-list-pagination-box').removeClass('map-mode');
    $('#property-list-pagination-box').addClass('detail-mode');

    $('#property-list-map-sidebar-left').removeClass('list-mode');
    $('#property-list-map-sidebar-left').removeClass('map-mode');
    $('#property-list-map-sidebar-left').addClass('detail-mode');
    
    $('#property-list-sidebar-left').addClass('hide');
    $('#f-property-search-result')  .addClass('hide');
    $('#page-sidebar-right')        .addClass('hide');
    
    $('#property-list-map-sidebar-left').removeClass('hide');
    $('#property-map-search-result')    .addClass('hide');
    
    $('#property-list-detail').removeClass('hide');
  }
  else
  {
    $('#page-content-header-list')  .addClass('active');
    $('#page-content-header-map')   .removeClass('active');
    $('#page-content-header-detail').removeClass('active');

    $('#property-list-pagination-box').addClass('list-mode');
    $('#property-list-pagination-box').removeClass('map-mode');
    $('#property-list-pagination-box').removeClass('detail-mode');

    $('#property-list-map-sidebar-left').addClass('list-mode');
    $('#property-list-map-sidebar-left').removeClass('map-mode');
    $('#property-list-map-sidebar-left').removeClass('detail-mode');
    
    $('#property-list-sidebar-left').removeClass('hide');
    $('#f-property-search-result')  .removeClass('hide');
    $('#page-sidebar-right')        .removeClass('hide');
    
    $('#property-list-map-sidebar-left').addClass('hide');
    $('#property-map-search-result')    .addClass('hide');
    
    $('#property-list-detail').addClass('hide');
  }
}

function getViewMode()
{
  if ($('#page-content-header-map').hasClass('active'))
    return "map";
  else if ($('#page-content-header-detail').hasClass('active'))
    return "detail";
  else
    return "list";
}

function moveListMapItems(direction)
{
  var top = $('#property-list-map-items-panel-sidebar-left').css('top');
  var n   = $('#property-list-map-items-panel-sidebar-left .map-item').length;
  var containerHeight = 601;
  var itemHeight = 86;
  var scrollByAmount = 7;
  
  top = parseInt(top.substring(0, top.length - 2));
  
  if (direction == "down")
  {
    if (Math.abs(top - scrollByAmount * itemHeight) <= n * itemHeight - containerHeight - 1)
      top -= scrollByAmount * itemHeight;
    else
      top = -1 * (n * itemHeight - containerHeight - 1);
  }
  else if (direction == "up")
  {
    if (top + scrollByAmount * itemHeight <= 0)
      top += scrollByAmount * itemHeight;
    else
      top = 0
  }
  else
  {
    var index = $('#propertyListMapItem-' + direction).index();
    
    top = -1
          * Math.floor(index / scrollByAmount)
          * itemHeight * scrollByAmount;
  }
  
  if (top != global_MapItemsPanelSidebarLeft)
  {
    global_MapItemsPanelSidebarLeft = top;
    
    $('#property-list-map-items-panel-sidebar-left').stop()
                                                    .animate({ top: top }, 1000);
  }
}

function createAddressMapMarker(map, property)
{
  var marker;
  var location, url;
  
  if (typeof google === 'undefined')
    return;
  
  if (property == null)
    return;
  
  location = new google.maps.LatLng(parseFloat(property.location.latitude),
                                    parseFloat(property.location.longitude));
                                    
  url      = "/nehnutelnost"
             + "/" + property.id
             + "/" + property.nice_url
             + ""
  
  global_latLngBounds.extend(location);
  
  marker = new google.maps.Marker({
                  position:   location,
                  draggable:  false
                });

  global_markerCluster.addMarker(marker);
  
  global_marker.push({ id: property.id, marker: marker, dataObj: property });

  google.maps.event.addListener(marker,
                                'mouseover',
                                function()
                                {
                                  openInfoWindow(marker);
                                });
  google.maps.event.addListener(marker,
                                'click',
                                new Function("showDetail(" + property.id + ");"));
}

function paintInfoWindow(marker, active)
{
  var property = findGlobalMarker(marker).dataObj;
  
  var content = "<div id='infoWindowItem-" + property.id + "' class='marker-info-window" + (active ? " active" : "") + "'>"
                  +"<a class='body' href='#property-detail-mark' onclick='showDetail(" + property.id + ");'>"
                  + "<div class='document'>"
                    + "<img src='" + property.document + "'/>"
                  + "</div>"
                  + "<div class='about'>"
                    + "<span class='address'>" + property.address + "</span>"
                    + "<br/>"
                    + "<span class='price'>"
                      + property.offer.price_plain
                      + " " + property.offer.currency
                      + (property.offer.unit_value != "BY_PROPERTY"
                        ? " (" + property.offer.unit + ")"
                        : "")
                      + "</span>"
                  + "</div>"
                  + "</a>"
                  + "<div class='toolbar'>"
                    + "<a href='javascript: removeItem(" + property.id + ");' title='Odstrániť zo zoznamu'><img src='/img/16x16/trash.png'/></a>"
                  + "</div>"
                + "</div>";

  return content;
}

function paintMarkerClusterInfoWindow(markers)
{
  var content = "";
  
  for (var i = 0; i < markers.length; i++)
    content = content + paintInfoWindow(markers[i], i == 0);
  
  content = "<div class='marker-info-window-cluster'>"
              + "<div class='nav-toolbar'>"
                + "<a href='javascript: prevInfoWindowItem();' class='prev' title='Predošlý záznam'><img src='/img/16x16/prev.png'/></a>"
                + "<div class='desc'>" + "1 / " + markers.length + "</div>"
                + "<a href='javascript: nextInfoWindowItem();' class='next' title='Ďalší záznam'><img src='/img/16x16/next.png'/></a>"
              + "</div>"
              + "<div class='group-frame'>"
                + content
              + "</div>"
            + "</div>";

  return content;
}

function removeItem(id)
{
  $('#propertyListItem-' + id).remove();
  $('#propertyListMapItem-' + id).remove();

  for (var i = 0; i < global_marker.length; i++)
  {
    if (global_marker[i].id == id)
    {
      if (global_infoWindowMarker != null && global_infoWindowMarker == global_marker[i].marker)
      {
        global_infoWindow.close();
        global_infoWindowMarker = null;
      }
      
      global_markerCluster.removeMarker(global_marker[i].marker);
      global_marker.splice(i, 1);
      
      removeInfoWindowItem(id);
      
      break;
    }
  }
}

function showDetail(id)
{
  showActiveMapItem(id);
  
  changeView("detail");
  
  $.ajax({
    url: '/property/detail-inline',
    type: 'POST',
    data: { id: id },
    dataType: 'html',
    success: function(data, textStatus) {
      var e = $('#property-list-detail');
      
      e.empty();
      e.append($(data));
    },
    error: function(xhr, textStatus, errorThrown) {
    }
  });
}

function showActiveMapItem(id)
{
  $('#property-list-map-items-panel-sidebar-left .map-item').removeClass('active');
  $('#propertyListMapItem-' + id).addClass('active');
  
  moveListMapItems(id);
}  

function addLocalitySK01()
{
 // do nothing, if #propertyCountry is empty
  var country = $('#propertyCountry_' + global_activeLocality).val();

  if (country == "" || country == "null")
  {
    $('#propertyKrajSK01').val("null");
    showLocalityPanelSK01();
    changeEventKraj_SK01();
    
    return;
  }

  // find first available locality and change global_activeLocality
  var i = 0;
  country = $('#propertyCountry_'  + i);
  while (country.length != 0)
  {
    if (country.val() == "")
    {
      global_activeLocality = i;

      $('#propertyKrajSK01').val("null");
      showLocalityPanelSK01();
      changeEventKraj_SK01();

      return;
    }
    
    i++;
    country = $('#propertyCountry_'  + i);
  }
}

function addLocalityCZ01()
{
 // do nothing, if #propertyCountry is empty
  var country = $('#propertyCountry_' + global_activeLocality).val();

  if (country == "" || country == "null")
  {
    $('#propertyKrajCZ01').val("null");
    showLocalityPanelCZ01();
    changeEventKraj_CZ01();
    
    return;
  }

  // find first available locality and change global_activeLocality
  var i = 0;
  country = $('#propertyCountry_'  + i);
  while (country.length != 0)
  {
    if (country.val() == "")
    {
      global_activeLocality = i;

      $('#propertyKrajCZ01').val("null");
      showLocalityPanelCZ01();
      changeEventKraj_CZ01();

      return;
    }
    
    i++;
    country = $('#propertyCountry_'  + i);
  }
}

function addLocalityXX01(countryStr)
{
  if (country == "")
    return;

  // find first available locality and change global_activeLocality
  var i = 0;
  var country = $('#propertyCountry_'  + i);
  while (country.length != 0)
  {
    if (country.val() == "")
    {
      global_activeLocality = i;

      refreshLocalityXX01(global_activeLocality, countryStr);

      return;
    }
    
    i++;
    country = $('#propertyCountry_'  + i);
  }
}

function removeLocality(i)
{
  var html;
  var j = i;

  // empty selected locality
  $('#propertyCountry_' + j)     .val("");
  $('#propertyCountryLabel_' + j).val("");
  $('#propertyKraj_' + j)        .val("");
  $('#propertyKrajLabel_' + j)   .val("");
  $('#propertyOkres_' + j)       .val("");
  $('#propertyOkresLabel_' + j)  .val("");
  $('#propertyObec_' + j)        .val("");
  $('#propertyObecLabel_' + j)   .val("");
  $('#property-locality-panel-label-' + j).html("");
  $('#property-locality-panel-' + j).addClass('hide');

  var k = j + 1;
  
  var nextCountry      = $('#propertyCountry_'      + k);
  var nextCountryLabel = $('#propertyCountryLabel_' + k);
  var nextKraj         = $('#propertyKraj_'         + k);
  var nextKrajLabel    = $('#propertyKrajLabel_'    + k);
  var nextOkres        = $('#propertyOkres_'        + k);
  var nextOkresLabel   = $('#propertyOkresLabel_'   + k);
  var nextObec         = $('#propertyObec_'         + k);
  var nextObecLabel    = $('#propertyObecLabel_'    + k);
  
  // replace selected locality width data from next (if such locality exists)
  while (nextCountry.length != 0)
  {
    $('#propertyCountry_'      + j).val(nextCountry     .val());
    $('#propertyCountryLabel_' + j).val(nextCountryLabel.val());
    $('#propertyKraj_'         + j).val(nextKraj        .val());
    $('#propertyKrajLabel_'    + j).val(nextKrajLabel   .val());
    $('#propertyOkres_'        + j).val(nextOkres       .val());
    $('#propertyOkresLabel_'   + j).val(nextOkresLabel  .val());
    $('#propertyObec_'         + j).val(nextObec        .val());
    $('#propertyObecLabel_'    + j).val(nextObecLabel   .val());
    
    html = $('#property-locality-panel-label-' + k).html();
    html = html.replace(/editLocality\(.*\)/, "editLocality(" + j + ")");
    
    $('#property-locality-panel-label-' + j).html(html);

    if ($('#propertyCountry_'  + j).val() != "")
      $('#property-locality-panel-' + j).removeClass('hide');
    else
      $('#property-locality-panel-' + j).addClass('hide');

    nextCountry     .val("");
    nextCountryLabel.val("");
    nextKraj        .val("");
    nextKrajLabel   .val("");
    nextOkres       .val("");
    nextOkresLabel  .val("");
    nextObec        .val("");
    nextObecLabel   .val("");
    $('#property-locality-panel-label-' + k).html("");
    $('#property-locality-panel-' + k).addClass('hide');

    j++;
    k = j + 1;  
    nextCountry      = $('#propertyCountry_'      + k);
    nextCountryLabel = $('#propertyCountryLabel_' + k);
    nextKraj         = $('#propertyKraj_'         + k);
    nextKrajLabel    = $('#propertyKrajLabel_'    + k);
    nextOkres        = $('#propertyOkres_'        + k);
    nextOkresLabel   = $('#propertyOkresLabel_'   + k);
    nextObec         = $('#propertyObec_'         + k);
    nextObecLabel    = $('#propertyObecLabel_'    + k);
  }

  // change global_activeLocality and fill #property?_? with new data
  if (i == global_activeLocality)
  {
    var country = $('#propertyCountry_' + i).val();
    var kraj    = $('#propertyKraj_'    + i).val();
    var okres   = $('#propertyOkres_'   + i).val();
    var obec    = $('#propertyObec_'    + i).val();

    if (country == "SLOVAKIA")
    {
      $('#propertyKrajSK01') .val(kraj  != "" ? kraj  : "null");
      $('#propertyOkresSK01').val(okres != "" ? okres : "null");
      $('#propertyObecSK01') .val(obec  != "" ? obec  : "null");

      showLocalityPanelSK01();
      
      loadObec_SK01 (okres, obec);
      loadOkres_SK01(kraj, okres);
      loadKraj_SK01 (kraj);
    }
    else if (country == "CZECH")
    {
      $('#propertyKrajCZ01') .val(kraj  != "" ? kraj  : "null");
      $('#propertyOkresCZ01').val(okres != "" ? okres : "null");
      $('#propertyObecCZ01') .val(obec  != "" ? obec  : "null");

      showLocalityPanelCZ01();
      
      loadObec_CZ01 (okres, obec);
      loadOkres_CZ01(kraj, okres);
      loadKraj_CZ01 (kraj);
    }
    else if (country != "")
    {
      hideLocalityPanels();
    }
  }
  else if (i < global_activeLocality)
  {
    global_activeLocality--;
  }
}

function editLocality(i)
{
  var option;

  global_activeLocality = i;

  var country = $('#propertyCountry_' + i).val();
  var kraj    = $('#propertyKraj_'    + i).val();
  var okres   = $('#propertyOkres_'   + i).val();
  var obec    = $('#propertyObec_'    + i).val();

  if (country == "SLOVAKIA" || country == "")
  {
    $('#propertyKrajSK01') .val(kraj  != "" ? kraj  : "null");
    $('#propertyOkresSK01').val(okres != "" ? okres : "null");
    $('#propertyObecSK01') .val(obec  != "" ? obec  : "null");

    showLocalityPanelSK01();
    
    loadObec_SK01 (okres, obec);
    loadOkres_SK01(kraj, okres);
    loadKraj_SK01 (kraj);
  }
  else if (country == "CZECH")
  {
    $('#propertyKrajCZ01') .val(kraj  != "" ? kraj  : "null");
    $('#propertyOkresCZ01').val(okres != "" ? okres : "null");
    $('#propertyObecCZ01') .val(obec  != "" ? obec  : "null");

    showLocalityPanelCZ01();
    
    loadObec_CZ01 (okres, obec);
    loadOkres_CZ01(kraj, okres);
    loadKraj_CZ01 (kraj);
  }
}

function refreshLocalitySK01(i)
{
  var kraj       = $('#propertyKrajSK01').val();
  var krajLabel  = $('#propertyKrajSK01 option:selected').text();
  var okres      = $('#propertyOkresSK01').val();
  var okresLabel = $('#propertyOkresSK01 option:selected').text();
  var obec       = $('#propertyObecSK01').val();
  var obecLabel  = $('#propertyObecSK01 option:selected').text();
  
  if (kraj == "null")
  {
    kraj       = "";
    krajLabel  = "";
  }
  if (okres == "null")
  {
    okres      = "";
    okresLabel = "";
  }
  if (obec == "null")
  {
    obec       = "";
    obecLabel  = "";
  }
  
  var countryObj = findCountryByCountry("SLOVAKIA");
  var label      = countryObj.isoCode.toUpperCase() + ":";

  $('#propertyCountry_'      + i).val(countryObj.country);
  $('#propertyCountryLabel_' + i).val(countryObj.name);
  $('#propertyKraj_'         + i).val(kraj);
  $('#propertyKrajLabel_'    + i).val(krajLabel);
  $('#propertyOkres_'        + i).val(okres);
  $('#propertyOkresLabel_'   + i).val(okresLabel);
  $('#propertyObec_'         + i).val(obec);
  $('#propertyObecLabel_'    + i).val(obecLabel);
  
  if (obec != "")
    label = label + " " + obecLabel;
  else if (okres != "")
    label = label + " " + okresLabel;
  else if (kraj != "")
    label = label + " " + krajLabel;
  
  $('#property-locality-panel-label-' + i).html("<a href='#' onclick='editLocality(" + i + ");'>" + label + "</a>");
  

    $('#property-locality-panel-' + i).removeClass('hide');


}

function refreshLocalityCZ01(i)
{
  var kraj       = $('#propertyKrajCZ01').val();
  var krajLabel  = $('#propertyKrajCZ01 option:selected').text();
  var okres      = $('#propertyOkresCZ01').val();
  var okresLabel = $('#propertyOkresCZ01 option:selected').text();
  var obec       = $('#propertyObecCZ01').val();
  var obecLabel  = $('#propertyObecCZ01 option:selected').text();
  
  if (kraj == "null")
  {
    kraj       = "";
    krajLabel  = "";
  }
  if (okres == "null")
  {
    okres      = "";
    okresLabel = "";
  }
  if (obec == "null")
  {
    obec       = "";
    obecLabel  = "";
  }

  var countryObj = findCountryByCountry("CZECH");
  var label      = countryObj.isoCode.toUpperCase() + ":";
  
  $('#propertyCountry_'      + i).val(countryObj.country);
  $('#propertyCountryLabel_' + i).val(countryObj.name);
  $('#propertyKraj_'         + i).val(kraj);
  $('#propertyKrajLabel_'    + i).val(krajLabel);
  $('#propertyOkres_'        + i).val(okres);
  $('#propertyOkresLabel_'   + i).val(okresLabel);
  $('#propertyObec_'         + i).val(obec);
  $('#propertyObecLabel_'    + i).val(obecLabel);
  
  if (obec != "")
    label = label + " " + obecLabel;
  else if (okres != "")
    label = label + " " + okresLabel;
  else if (kraj != "")
    label = label + " " + krajLabel;
  
  $('#property-locality-panel-label-' + i).html("<a href='#' onclick='editLocality(" + i + ");'>" + label + "</a>");
  

    $('#property-locality-panel-' + i).removeClass('hide');


}

function refreshLocalityXX01(i, country)
{
  var countryObj = findCountryByCountry(country);
  
  var label = countryObj.name;

  $('#propertyCountry_'      + i).val(countryObj.country);
  $('#propertyCountryLabel_' + i).val(countryObj.name);
  
  $('#property-locality-panel-label-' + i).html(label);
  
  $('#property-locality-panel-' + i).removeClass('hide');
}

function initLocality()
{
  var i = 0;
  var country = $('#propertyCountry_'  + i);
  while (country.length != 0)
  {
        country      = $('#propertyCountry_'      + i).val();
    var countryLabel = $('#propertyCountryLabel_' + i).val();
    var krajLabel    = $('#propertyKrajLabel_'    + i).val();
    var okresLabel   = $('#propertyOkresLabel_'   + i).val();
    var obecLabel    = $('#propertyObecLabel_'    + i).val();
    
    var label      = "";
    var countryObj = null;
    
    if (country == "SLOVAKIA" || country == "CZECH")
    {
      countryObj = findCountryByCountry(country);
      label      = countryObj.isoCode.toUpperCase() + ":";
      
      if (obecLabel != "")
        label = label + " " + obecLabel;
      else if (okresLabel != "")
        label = label + " " + okresLabel;
      else if (krajLabel != "")
        label = label + " " + krajLabel;
    }
    else if (country != "")
    {
      label = countryLabel;
    }
    
    $('#property-locality-panel-label-' + i).html("<a href='#' onclick='editLocality(" + i + ");'>" + label + "</a>");
    
    if (country != "")
      $('#property-locality-panel-' + i).removeClass('hide');
    else
      $('#property-locality-panel-' + i).addClass('hide');

    i++;
    country = $('#propertyCountry_' + i).val();
  }

  // find first available locality and change global_activeLocality

  i = 0;
  country = $('#propertyCountry_'  + i);
  while (country.length != 0)
  {
    if (country.val() == "")
    {
      global_activeLocality = (i == 0 )
                              ? i
                              : i - 1;




      editLocality(global_activeLocality);

      return;
    }
    
    i++;
    country = $('#propertyCountry_'  + i);
  }
  
  global_activeLocality = i - 1;
  editLocality(global_activeLocality);
}

function showLocalityPanelSK01()
{
  $('#property-locality-panel-SK01').removeClass('hide');
  $('#property-locality-panel-CZ01').addClass('hide');
}

function showLocalityPanelCZ01()
{
  $('#property-locality-panel-SK01').addClass('hide');
  $('#property-locality-panel-CZ01').removeClass('hide');
}

function hideLocalityPanels()
{
  $('#property-locality-panel-SK01').addClass('hide');
  $('#property-locality-panel-CZ01').addClass('hide');
}

function updateKraj_SK01(trigger)
{
  var kraj, okresVal;
  var ajaxData;
  var option;
  
  kraj = $('#propertyKrajSK01');
  kraj.empty();
  kraj.append($("<option></option>").attr("value", "null")
                                                .text("Načítavam ...")); 
  
  okresVal  = $('#propertyOkresSK01').val();
  
  if (trigger == "okres"  && okresVal  != "" && okresVal  != "null")
  {
    if (trigger == "okres")
      ajaxData = { okres: okresVal };

    $.ajax({
      url: '/xml/domain/sk/kraj',
      type: 'POST',
      data: ajaxData,
      dataType: 'xml',
      success: function(data, textStatus) {
        var kraj, list;

        kraj = $('#propertyKrajSK01');
        kraj.empty();
        kraj.append($("<option></option>").attr("value", "null")
                                                      .text("<Vybrať>")); 
        
        list = $(data).children('kraj-list');
        $(list).children('kraj').each(
          function()
          {
            kraj.append($("<option></option>").attr("value", $(this).attr('kod'))
                                                          .text($(this).children('kraj').text())); 
          });
        
        if ($('#propertyOkresSK01').val() != null)
          $('#propertyKrajSK01').val( $('#propertyOkresSK01 option:selected').attr('kraj-kod') );

        if ($('#propertyKrajSK01 option').length == 2)
          $('#propertyKrajSK01 option:eq(1)').attr("selected", "selected");
        
        changeEventKraj_SK01();
      }
    });
  }
  else
  {
    kraj.empty();
    kraj.append($("<option></option>").attr("value", "null")
                                                  .text("<Vybrať>")); 
    
    changeEventKraj_SK01();
  }
}

function updateOkres_SK01(trigger)
{
  var okres, krajVal, obecVal;
  var ajaxData;
  var option;
  
  okres = $('#propertyOkresSK01');
  okres.empty();
  okres.append($("<option></option>").attr("value", "null")
                                                 .text("Načítavam ...")); 
  
  krajVal = $('#propertyKrajSK01').val();
  obecVal = $('#propertyObecSK01').val();
  
  if (
         (trigger == "kraj" && krajVal != "" && krajVal != "null")
      || (trigger == "obec" && obecVal != "" && obecVal != "null")
     )
  {
    if (trigger == "kraj")
      ajaxData = { kraj: krajVal };
    else if (trigger == "obec")
      ajaxData = { obec: obecVal };

    $.ajax({
      url: '/xml/domain/sk/okres',
      type: 'POST',
      data: ajaxData,
      dataType: 'xml',
      success: function(data, textStatus) {
        var okres, list;

        okres = $('#propertyOkresSK01');
        okres.empty();
        okres.append($("<option></option>").attr("value", "null")
                                                       .text("<Vybrať>")); 
        
        list = $(data).children('okres-list');
        $(list).children('okres').each(
          function()
          {
            okres.append($("<option></option>").attr("value",    $(this).attr('kod'))
                                                           .attr("kraj-kod", $(this).children('kraj').attr('kod'))
                                                           .text($(this).children('okres').text())); 
          });
        
        if ($('#propertyObecSK01').val() != null)
          $('#propertyOkresSK01').val( $('#propertyObecSK01 option:selected').attr('okres-kod') );

        if ($('#propertyOkresSK01 option').length == 2)
          $('#propertyOkresSK01 option:eq(1)').attr("selected", "selected");
        
        changeEventOkres_SK01();
      }
    });
  }
  else
  {
    okres.empty();
    okres.append($("<option></option>").attr("value", "null")
                                                   .text("<Vybrať>")); 
    
    changeEventOkres_SK01();
  }
}

function updateObec_SK01(trigger, obecStr)
{
  var obec, okresVal, map;
  var ajaxData;
  var option;
  
  obec = $('#propertyObecSK01');
  obec.empty();
  obec.append($("<option></option>").attr("value", "null")
                                                .text("Načítavam ...")); 
  
  okresVal = $('#propertyOkresSK01').val();
  
  if (trigger == "okres"    && okresVal != "" && okresVal != "null")
  {
    if (trigger == "okres")
      ajaxData = { okres: okresVal };

    $.ajax({
      url: '/xml/domain/sk/obec',
      type: 'POST',
      data: ajaxData,
      dataType: 'xml',
      success: function(data, textStatus) {
        var obec, list;

        obec = $('#propertyObecSK01');
        obec.empty();
        obec.append($("<option></option>").attr("value", "null")
                                                      .text("<Vybrať>")); 
        
        list = $(data).children('obec-list');
        $(list).children('obec').each(
          function()
          {
            obec.append($("<option></option>").attr("value",     $(this).attr('kod'))
                                                          .attr("okres-kod", $(this).children('okres').attr('kod'))
                                                          .text($(this).children('obec').text())); 
          });

        if ($('#propertyObecSK01 option').length == 2)
          $('#propertyObecSK01 option:eq(1)').attr("selected", "selected");
        
        changeEventObec_SK01(true);
      }
    });
  }
  else
  {
    obec.empty();
    obec.append($("<option></option>").attr("value", "null")
                                                  .text("<Vybrať>")); 
    
    changeEventObec_SK01(true);
  }
}

function loadKraj_SK01(krajKod)
{
  var kraj;
  
  kraj = $('#propertyKrajSK01');
  kraj.empty();

  kraj.append($("<option></option>").attr("value", "null")
                                                .text("Načítavam ...")); 
  
  $.ajax({
    url: '/xml/domain/sk/kraj',
    type: 'POST',
    dataType: 'xml',
    success: function(data, textStatus) {
      var kraj, list, option;

      kraj = $('#propertyKrajSK01');
      kraj.empty();
      kraj.append($("<option></option>").attr("value", "null")
                                                    .text("<Vybrať>")); 
      
      list = $(data).children('kraj-list');
      $(list).children('kraj').each(function()
      {
        kraj.append($("<option></option>").attr("value", $(this).attr('kod'))
                                                      .text($(this).children('kraj').text())); 

      });
      
      $('#propertyKrajSK01 option[value=' + krajKod + ']').attr("selected", "selected");
    }
  });
}

function loadOkres_SK01(krajKod, okresKod)
{
  var okres;
  
  okres = $('#propertyOkresSK01');
  okres.empty();
  
  if (krajKod == "" || krajKod == "null")
  {
    okres.append($("<option></option>").attr("value", "null")
                                                   .text("<Vybrať>")); 
  }
  else
  {
    okres.append($("<option></option>").attr("value", "null")
                                                   .text("Načítavam ...")); 
    
    $.ajax({
      url: '/xml/domain/sk/okres',
      type: 'POST',
      data: { kraj: krajKod },
      dataType: 'xml',
      success: function(data, textStatus) {
        var okres, list, option;

        okres = $('#propertyOkresSK01');
        okres.empty();
        okres.append($("<option></option>").attr("value", "null")
                                                       .text("<Vybrať>")); 
        
        list = $(data).children('okres-list');
        $(list).children('okres').each(function()
        {
          okres.append($("<option></option>").attr("value",    $(this).attr('kod'))
                                                         .attr("kraj-kod", $(this).children('kraj').attr('kod'))
                                                         .text($(this).children('okres').text())); 
        });
        
        $('#propertyOkresSK01 option[value=' + okresKod + ']').attr("selected", "selected");
      }
    });
  }
}

function loadObec_SK01(okresKod, obecKod)
{
  var obec;
  
  obec = $('#propertyObecSK01');
  obec.empty();
  
  if (okresKod == "" || okresKod == "null")
  {
    obec.append($("<option></option>").attr("value", "null")
                                                  .text("<Vybrať>")); 
  }
  else
  {
    obec.append($("<option></option>").attr("value", "null")
                                                  .text("Načítavam ...")); 
    
    $.ajax({
      url: '/xml/domain/sk/obec',
      type: 'POST',
      data: { okres: okresKod },
      dataType: 'xml',
      success: function(data, textStatus) {
        var obec, list, option;

        obec = $('#propertyObecSK01');
        obec.empty();
        obec.append($("<option></option>").attr("value", "null")
                                                      .text("<Vybrať>")); 
        
        list = $(data).children('obec-list');
        $(list).children('obec').each(function()
        {
          obec.append($("<option></option>").attr("value",     $(this).attr('kod'))
                                                        .attr("okres-kod", $(this).children('okres').attr('kod'))
                                                        .text($(this).children('obec').text())); 
        });

        $('#propertyObecSK01 option[value=' + obecKod + ']').attr("selected", "selected");
      }
    });
  }
}

function changeEventKraj_SK01()
{
  refreshLocalitySK01(global_activeLocality);
  
  if ($('#propertyOkresSK01').val() == null || $('#propertyOkresSK01 option:selected').attr('kraj-kod') != $('#propertyKrajSK01').val())
    updateOkres_SK01("kraj");
}

function changeEventOkres_SK01()
{
  refreshLocalitySK01(global_activeLocality);
  
  if ($('#propertyOkresSK01 option:selected').val() != "null" && $('#propertyKrajSK01').val() != $('#propertyOkresSK01 option:selected').attr('kraj-kod'))
    updateKraj_SK01("okres");
  
  if ($('#propertyObecSK01').val() == null || $('#propertyObecSK01 option:selected').attr('okres-kod') != $('#propertyOkresSK01').val())
    updateObec_SK01("okres");
}

function changeEventObec_SK01()
{
  refreshLocalitySK01(global_activeLocality);
  
  if ($('#propertyObecSK01 option:selected').val() != "null" && $('#propertyOkresSK01').val() != $('#propertyObecSK01 option:selected').attr('okres-kod'))
    updateOkres_SK01("obec");
  

}





function updateKraj_CZ01(trigger)
{
  var kraj, okresVal;
  var ajaxData;
  var option;
  
  kraj = $('#propertyKrajCZ01');
  kraj.empty();
  kraj.append($("<option></option>").attr("value", "null")
                                                .text("Načítavam ...")); 
  
  okresVal  = $('#propertyOkresCZ01').val();
  
  if (trigger == "okres"  && okresVal  != "" && okresVal  != "null")
  {
    if (trigger == "okres")
      ajaxData = { okres: okresVal };

    $.ajax({
      url: '/xml/domain/cz/kraj',
      type: 'POST',
      data: ajaxData,
      dataType: 'xml',
      success: function(data, textStatus) {
        var kraj, list;

        kraj = $('#propertyKrajCZ01');
        kraj.empty();
        kraj.append($("<option></option>").attr("value", "null")
                                                      .text("<Vybrať>")); 
        
        list = $(data).children('kraj-list');
        $(list).children('kraj').each(
          function()
          {
            kraj.append($("<option></option>").attr("value", $(this).attr('kod'))
                                                          .text($(this).children('kraj').text())); 
          });
        
        if ($('#propertyOkresCZ01').val() != null)
          $('#propertyKrajCZ01').val( $('#propertyOkresCZ01 option:selected').attr('kraj-kod') );

        if ($('#propertyKrajCZ01 option').length == 2)
          $('#propertyKrajCZ01 option:eq(1)').attr("selected", "selected");
        
        changeEventKraj_CZ01();
      }
    });
  }
  else
  {
    kraj.empty();
    kraj.append($("<option></option>").attr("value", "null")
                                                  .text("<Vybrať>")); 
    
    changeEventKraj_CZ01();
  }
}

function updateOkres_CZ01(trigger)
{
  var okres, krajVal, obecVal;
  var ajaxData;
  var option;
  
  okres = $('#propertyOkresCZ01');
  okres.empty();
  okres.append($("<option></option>").attr("value", "null")
                                                 .text("Načítavam ...")); 
  
  krajVal = $('#propertyKrajCZ01').val();
  obecVal = $('#propertyObecCZ01').val();
  
  if (
         (trigger == "kraj" && krajVal != "" && krajVal != "null")
      || (trigger == "obec" && obecVal != "" && obecVal != "null")
     )
  {
    if (trigger == "kraj")
      ajaxData = { kraj: krajVal };
    else if (trigger == "obec")
      ajaxData = { obec: obecVal };

    $.ajax({
      url: '/xml/domain/cz/okres',
      type: 'POST',
      data: ajaxData,
      dataType: 'xml',
      success: function(data, textStatus) {
        var okres, list;

        okres = $('#propertyOkresCZ01');
        okres.empty();
        okres.append($("<option></option>").attr("value", "null")
                                                       .text("<Vybrať>")); 
        
        list = $(data).children('okres-list');
        $(list).children('okres').each(
          function()
          {
            okres.append($("<option></option>").attr("value",    $(this).attr('kod'))
                                                           .attr("kraj-kod", $(this).children('kraj').attr('kod'))
                                                           .text($(this).children('okres').text())); 
          });
        
        if ($('#propertyObecCZ01').val() != null)
          $('#propertyOkresCZ01').val( $('#propertyObecCZ01 option:selected').attr('okres-kod') );

        if ($('#propertyOkresCZ01 option').length == 2)
          $('#propertyOkresCZ01 option:eq(1)').attr("selected", "selected");
        
        changeEventOkres_CZ01();
      }
    });
  }
  else
  {
    okres.empty();
    okres.append($("<option></option>").attr("value", "null")
                                                    .text("<Vybrať>")); 
    
    changeEventOkres_CZ01();
  }
}

function updateObec_CZ01(trigger, obecStr)
{
  var obec, okresVal, map;
  var ajaxData;
  var option;
  
  obec = $('#propertyObecCZ01');
  obec.empty();
  obec.append($("<option></option>").attr("value", "null")
                                                .text("Načítavam ...")); 
  
  okresVal = $('#propertyOkresCZ01').val();
  
  if (trigger == "okres"    && okresVal != "" && okresVal != "null")
  {
    if (trigger == "okres")
      ajaxData = { okres: okresVal };

    $.ajax({
      url: '/xml/domain/cz/obec',
      type: 'POST',
      data: ajaxData,
      dataType: 'xml',
      success: function(data, textStatus) {
        var obec, list;

        obec = $('#propertyObecCZ01');
        obec.empty();
        obec.append($("<option></option>").attr("value", "null")
                                                      .text("<Vybrať>")); 
        
        list = $(data).children('obec-list');
        $(list).children('obec').each(
          function()
          {
            obec.append($("<option></option>").attr("value",     $(this).attr('kod'))
                                                          .attr("okres-kod", $(this).children('okres').attr('kod'))
                                                          .text($(this).children('obec').text())); 
          });

        if ($('#propertyObecCZ01 option').length == 2)
          $('#propertyObecCZ01 option:eq(1)').attr("selected", "selected");
        
        changeEventObec_CZ01(true);
      }
    });
  }
  else
  {
    obec.empty();
    obec.append($("<option></option>").attr("value", "null")
                                                  .text("<Vybrať>")); 
    
    changeEventObec_CZ01(true);
  }
}

function loadKraj_CZ01(krajKod)
{
  var kraj;
  
  kraj = $('#propertyKrajCZ01');
  kraj.empty();

  kraj.append($("<option></option>").attr("value", "null")
                                                .text("Načítavam ...")); 
  
  $.ajax({
    url: '/xml/domain/cz/kraj',
    type: 'POST',
    dataType: 'xml',
    success: function(data, textStatus) {
      var kraj, list, option;

      kraj = $('#propertyKrajCZ01');
      kraj.empty();
      kraj.append($("<option></option>").attr("value", "null")
                                                    .text("<Vybrať>")); 
      
      list = $(data).children('kraj-list');
      $(list).children('kraj').each(function()
      {
        kraj.append($("<option></option>").attr("value", $(this).attr('kod'))
                                                      .text($(this).children('kraj').text())); 
      });
      
      $('#propertyKrajCZ01 option[value=' + krajKod + ']').attr("selected", "selected");
    }
  });
}

function loadOkres_CZ01(krajKod, okresKod)
{
  var okres;
  
  okres = $('#propertyOkresCZ01');
  okres.empty();
  
  if (krajKod == "" || krajKod == "null")
  {
    okres.append($("<option></option>").attr("value", "null")
                                                   .text("<Vybrať>")); 
  }
  else
  {
    okres.append($("<option></option>").attr("value", "null")
                                                   .text("Načítavam ...")); 
    
    $.ajax({
      url: '/xml/domain/cz/okres',
      type: 'POST',
      data: { kraj: krajKod },
      dataType: 'xml',
      success: function(data, textStatus) {
        var okres, list, option;

        okres = $('#propertyOkresCZ01');
        okres.empty();
        okres.append($("<option></option>").attr("value", "null")
                                                       .text("<Vybrať>")); 
        
        list = $(data).children('okres-list');
        $(list).children('okres').each(function()
        {
          okres.append($("<option></option>").attr("value",    $(this).attr('kod'))
                                                         .attr("kraj-kod", $(this).children('kraj').attr('kod'))
                                                         .text($(this).children('okres').text())); 
        });
        
        $('#propertyOkresCZ01 option[value=' + okresKod + ']').attr("selected", "selected");
      }
    });
  }
}

function loadObec_CZ01(okresKod, obecKod)
{
  var obec;
  
  obec = $('#propertyObecCZ01');
  obec.empty();
  
  if (okresKod == "" || okresKod == "null")
  {
    obec.append($("<option></option>").attr("value", "null")
                                                  .text("<Vybrať>")); 
  }
  else
  {
    obec.append($("<option></option>").attr("value", "null")
                                                  .text("Načítavam ...")); 
    
    $.ajax({
      url: '/xml/domain/cz/obec',
      type: 'POST',
      data: { okres: okresKod },
      dataType: 'xml',
      success: function(data, textStatus) {
        var obec, list, option;

        obec = $('#propertyObecCZ01');
        obec.empty();
        obec.append($("<option></option>").attr("value", "null")
                                                      .text("<Vybrať>")); 
        
        list = $(data).children('obec-list');
        $(list).children('obec').each(function()
        {
          obec.append($("<option></option>").attr("value",     $(this).attr('kod'))
                                                        .attr("okres-kod", $(this).children('okres').attr('kod'))
                                                        .text($(this).children('obec').text())); 
        });

        $('#propertyObecCZ01 option[value=' + obecKod + ']').attr("selected", "selected");
      }
    });
  }
}

function changeEventKraj_CZ01()
{
  refreshLocalityCZ01(global_activeLocality);
  
  if ($('#propertyOkresCZ01').val() == null || $('#propertyOkresCZ01 option:selected').attr('kraj-kod') != $('#propertyKrajCZ01').val())
    updateOkres_CZ01("kraj");
}

function changeEventOkres_CZ01()
{
  refreshLocalityCZ01(global_activeLocality);
  
  if ($('#propertyOkresCZ01 option:selected').val() != "null" && $('#propertyKrajCZ01').val() != $('#propertyOkresCZ01 option:selected').attr('kraj-kod'))
    updateKraj_CZ01("okres");
  
  if ($('#propertyObecCZ01').val() == null || $('#propertyObecCZ01 option:selected').attr('okres-kod') != $('#propertyOkresCZ01').val())
    updateObec_CZ01("okres");
}

function changeEventObec_CZ01()
{
  refreshLocalityCZ01(global_activeLocality);
  
  if ($('#propertyObecCZ01 option:selected').val() != "null" && $('#propertyOkresCZ01').val() != $('#propertyObecCZ01 option:selected').attr('okres-kod'))
    updateOkres_CZ01("obec");
  

}





function changeEventCountry_XX01()
{
  refreshLocalityXX01(global_activeLocality);
}

