jQuery(function($) {
  initSearch();
  initClickable();
  initDatepickerProfil();
  initDatepickerEvent();
  initRepeatPassword();
  initConditionalFields();
  initExternalLinks();
  initGeolocationVerification();
});


/**
 * This function takes care of the String replacement in the search field.
 */ 
function initSearch()
{
  if (! $('#searchterm').length ) return;
  
  var searchterm = 'Suchbegriff';
  $('#searchterm').val(searchterm);
  $('#searchterm').focus(function()
  {
    if( $(this).val() == searchterm ) $(this).val('');
  });
  $('#searchterm').blur(function()
  {
    if( $(this).val() === '' ) $(this).val(searchterm);
  });
}


/**
 * This function makes blocks containing a link clickable. 
 */ 
function initClickable()
{
  if (! $('.clickable').length ) return;
  
  $('.clickable')
  .hover(
    function()
    {
      $(this).addClass('clickableHover');
    },
    
    function()
    {
      $(this).removeClass('clickableHover');
    }
  )
  .click(function()
  {
    window.location = $('a', this).attr('href');
  });
}


/**
 * This function adds a datepicker to the given date input fields 
 */ 
function initDatepickerProfil()
{
  if (! $('#Geburtsdatum').length ) return;
  
  $("#Geburtsdatum").datepicker({
    changeYear: true,
    changeMonth: true,
    dateFormat: 'd.m.yy',
    dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
    dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
    firstDay: 1,
    monthNames: ['Jänner','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
    monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
    yearRange: '1900:2010'
  });
}


/**
 * This function adds a datepicker to the given date input fields 
 */ 
function initDatepickerEvent()
{
  if (! $('#eventform #exp_date').length ) return;
  
  $("#eventform #exp_date").datepicker({
    changeYear: true,
    changeMonth: true,
    dateFormat: 'd.m.yy',
    dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
    dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
    firstDay: 1,
    monthNames: ['Jänner','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
    monthNamesShort: ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
    yearRange: '2010:2020'
  });
}


/**
 * This function reveals the password repeat field on password change 
 */ 
function initRepeatPassword()
{
  if (! $('#Password2').length ) return;
  
  $("#Password2").parent().addClass("hidden");
  
  $("#Password").change(function() {
    if ($(this).val().length > 0)
    {
      $("#Password2").parent().removeClass("hidden");
    }
    else
    {
      $("#Password2").parent().addClass("hidden");
    }
  });
}


/**
 * This function hides and reveals the conditional input fields 
 */ 
function initConditionalFields()
{
  if (! $('#mitgliedsdaten').length ) return;
  
  /* hide all divs that have the class "inactive", apart from the ones
    where the checkbox is checked */
  $(".changer").each(function()
  {
    if (!$(this).attr("checked"))
    {
      $(this).parent().next(".inactive").addClass("hidden");
      
      /* fix for IE not hiding the content properly */
      $(this).parent().next(".inactive").hide().show();
    }
  });
  
  /* add onlick handlers to the inputfields with class "changer" */
  $(".changer").click(function() {
    /* disable all options with the same name */
    inputName = $(this).attr("name");
    $('input[name="'+inputName+'"]').parent().next(".inactive").addClass("hidden");
    
    /* fix for IE not hiding the content properly */
    $('input[name="'+inputName+'"]').parent().next(".inactive").hide().show();
    
    
    if ($(this).attr("checked"))
    {
      $(this).parent().next(".inactive").removeClass("hidden");
    }
  });
  
  /* Disclosure of conditional fields for secondary address */
  if (  $("#Mitgliedsstatus").val() == "Pension" ||
        $("#Mitgliedsstatus").val() == "Ehrenmitglied" )
  {
    $('#secondary_address').hide();
  }
  /* If retired or honorary member, hide secondary address */
  $("#Mitgliedsstatus").change(function() {
    if ( $(this).val() == "Pension" || $(this).val() == "Ehrenmitglied")
    {
      $('#secondary_address').hide();
    }
    else
    {
      $('#secondary_address').show();
    }
  });
  
  /* Disclosure of conditional address field "Zustelladresse_Bezeichnung"*/
  if (  $("#Zustelladresse_Art").val() === "" ||
        $("#Zustelladresse_Art").val() == "Privat" )
  {
    $('#Zustelladresse_Bezeichnung').parent().hide();
  }
  $("#Zustelladresse_Art").change(function() {
    if ( $(this).val() === "" || $(this).val() == "Privat")
    {
      $('#Zustelladresse_Bezeichnung').parent().hide();
    }
    else
    {
      $('#Zustelladresse_Bezeichnung').parent().show();
    }
  });
  
  /* Disclosure of conditional address field "Zweitadresse_Bezeichnung"*/
  if (  $("#Zweitadresse_Art").val() === "" ||
        $("#Zweitadresse_Art").val() == "Privat" )
  {
    $('#Zweitadresse_Bezeichnung').parent().hide();
  }
  $("#Zweitadresse_Art").change(function() {
    if ( $(this).val() === "" || $(this).val() == "Privat")
    {
      $('#Zweitadresse_Bezeichnung').parent().hide();
    }
    else
    {
      $('#Zweitadresse_Bezeichnung').parent().show();
    }
  });
}


/* Force links with rel="extern" to open in a new window */
function initExternalLinks () {
  $('a[rel="extern"]').removeAttr('rel').attr('target', '_blank');
  $('a.relextern').removeClass('relextern').attr('target', '_blank');
}


/***************************************/
/* Address Verification when logged in */
/***************************************/
function initGeolocationVerification ()
{
  if (! $('#finderdaten').length) return;
  
  /* DOM Elements we need more often */
  var addressVerification = $('#addressVerification'),
      streetField = $('#adresse_anschrift'),
      zipField = $('#adresse_plz'),
      cityField = $('#adresse_ort'),
      addressVerifiedField = $('#adresse_bestaetigt'),
      searchPositionLat = $('#adresse_lat'),
      searchPositionLng = $('#adresse_long'),
      form = $('#finderdaten'),
      infoElement,
      addressVerifier,
      mapElement = addressVerification.append('<div id="map" style="width: 100%; height: 400px"></div>').children('#map');
  
  /* Variables */
  var mapOptions =
      {
        center: new google.maps.LatLng(47.353711, 13.458252),
        zoom: 6,
        mapTypeControl: true,
        mapTypeControlOptions:
        {
          style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        mapTypeId: google.maps.MapTypeId.ROADMAP
      },
      map,
      marker,
      geocoder = new google.maps.Geocoder();
  
  /* HTML Changes beforehand */
  addressVerification.prepend('<p id="info" class="notice">Position nicht bestätigt.</p><a id="verifyAddress" href="#">Position bestätigen</a><p class="small">Der rote Marker zeigt die Position Ihrer Ordination. Sie können durch Klicken die Position des Markers ändern.</p>');
  addressVerifier = $('#verifyAddress');
  infoElement = $('#info');
  
  /* Change Info if Position verified */
  if ( addressVerifiedField.val() == 1 )
  {
    toggleInfo(true, true);
  }
  
  addressVerifier.click(verifyAddress);
  
  initMap();
  
  function toggleInfo (state, initialyVerified)
  {
    var verified = infoElement.hasClass('info') ? 1 : 0;
    
    /* Exit if verified value already up-to-date */
    if ( (state === false && verified === 0) || (state === true && verified === 1) ) return;
    
    var text =  infoElement.text() == 'Position bestätigt.' ? 'Position nicht bestätigt.' : 'Position bestätigt.';
    infoElement
      .toggleClass('notice')
      .toggleClass('info')
      .text(text);
    
    addressVerifier.toggle();
    addressVerifiedField.val(Math.abs(verified-1));
  }
  
  function verifyAddress ()
  {
    toggleInfo(true);
    map.setCenter(marker.getPosition());
    return false;
  }
  
  function initMap ()
  {
    map = new google.maps.Map(mapElement.get(0), mapOptions);
    marker = new google.maps.Marker(
    {
      position: mapOptions.center,
      title: 'Ihr Standort',
      map: map
    });
    
    google.maps.event.addListener(map, 'click', function(e)
    {
      //map.setCenter(e.latLng);
      setTimeout( function() {
                    marker.setPosition(e.latLng)
                  },
                  300);
      searchPositionLat.val(e.latLng.lat());
      searchPositionLng.val(e.latLng.lng());
      toggleInfo(false);
    });
    
    // if   the Address is already verified set it to the verified positions
    // else geoCode the information in the Address fields
    if ( addressVerifiedField.val() == 1 )
    {
      map.setCenter(new google.maps.LatLng(searchPositionLat.val(), searchPositionLng.val()));
      map.setZoom(15);
      marker.setPosition(map.getCenter());
    }
    else
    {
      geoCode(getCurrentAddress());
    }
  }
  
  function getCurrentAddress()
  {
    return streetField.val() + ', ' + zipField.val() + ' ' + cityField.val();
  }
  
  function updateMap ()
  {
    geoCode(getCurrentAddress());
    toggleInfo(false);
    
    return false;
  }
  
  function geoCode (address)
  {
    geocoder.geocode( { 'address': address, 'region': 'AT' }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK)
      {
        map.setCenter(results[0].geometry.location);
        map.setZoom(15);
        setTimeout( function() {
                      marker.setPosition(results[0].geometry.location);
                    }, 300);
        searchPositionLat.val(map.getCenter().lat());
        searchPositionLng.val(map.getCenter().lng());
      }
    });
  }
}
