$(document).ready(function() {
  $('#top_usermenu .menu').uoWidgetListDropDown({  });
  $('#top_navmenu .menu').uoWidgetListDropDown({  });

  if($('#modalphoto').length)
  {
    new AjaxUpload('modalphoto', {
      action: $('#modalphoto').attr('href'),
      name: 'sf_guard_user_profile[avatar_file]',
      onComplete : function(file, response) {
        if (response.length > 0)
        {
        }
        else
        {
        src = $('#edit-avatar-thumb img').attr('src') + '?' + Math.random();
        $('#edit-avatar-thumb img').attr('src', src);
        }
      }
    });
  }

  if($('#galleryhome').length) {
    $('#galleryhome').galleryView({
      panel_width: 310,
      panel_height: 250,
      frame_width: 50,
      frame_height: 50
    });
  }

  if($('#gallerycategory').length) {
    $('#gallerycategory').galleryView({
      panel_width: 340,
      panel_height: 340,
      frame_width: 50,
      frame_height: 50,
      strip_height: 90
    });
  }

  if($('#sidebar-gallery').length) {
    $('#sidebar-gallery').galleryView({
      panel_width: 300,
      panel_height: 300,
      frame_width: 50,
      frame_height: 50,
      transition_interval: 8000
    });
  }

  $('#article-images ul li img').each(function() {
    $(this).hover(function() {
      var newSrc = $(this).attr('src');
      var newAlt = $(this).attr('alt');
      $('#article-main-image').attr('src', newSrc),
      $('#article-main-image').attr('alt', newAlt);
      $(this).parent().parent().children('li').removeClass('active');
      $(this).parent().addClass('active');
    });
    $(this).click(function() {
      return false;
    });
  });

  if($('#compose-receivers').length) {
    $('#compose-receivers').asmSelect({
    });
  }

  if($('#autocomplete_message_receiver_finder').length)
  {
    $('#autocomplete_message_receiver_finder').result(function(event, data, formatted) {
      var $option = $("<option></option>").text(data[0]).attr('value', data[1]).attr("selected", true);
      $('#compose-receivers').append($option).change();
      $('#autocomplete_message_receiver_finder').val('');
    });
  }

  $('.hidden-facet-block').dialog({
    autoOpen: false,
    height: 400,
    width: 650,
    modal: true,
    resizable: false,
    dialogClass: 'facet-dialog'
  });

  // Only display dialog links if js is available
  $('.facet-more').show();

  $('.facet-more').click(function() {
    facetId = '#' + $(this).attr('rel');
    $(facetId).dialog('open');
    return false;
  });

  $('.focusselect').focus(function() {
    if(this.value == this.defaultValue)
    {
      $(this).val('');
    }
  });

  $('.focusselect').blur(function() {
    if ('' == $(this).val()) {
      $(this).val(this.defaultValue);
    }
  });

  $('form.clear-default').submit(function () {
    $('form.clear-default input[type=text]').each(function() {
      if(this.value == this.defaultValue)
      {
        $(this).val('');
      }
    })
  });

  if ($('#proximity .item').size() > 0) {
    $("#proximity .item h4 a").each(function() {
      $(this).click(function() {
        var item = $(this).parent('h4').parent('.item').attr('id');
        $('#proximity .item .contentProximite').slideUp("normal");
        $('#'+item+' .contentProximite').slideDown("normal");
        return false;
      });
    });

    $("#proximity .item .contentProximite").each(function() {
      $(this).children('.rubrique').children('li').children('a').click(function() {
        var resultat = $(this).attr('class');
        $(this).parent('li').parent('.rubrique').children('li').removeClass('open');
        $(this).parent('li').addClass('open');
        $(this).parent('li').parent('.rubrique').parent('.contentProximite').children('.resultats').hide();
        $(this).parent('li').parent('.rubrique').parent('.contentProximite').children('.'+resultat).show();
        return false;
      });
    });
  }

  // Select all checkboxes
  $('#select-addresses').click(function() {
    $('input.select-address').attr('checked', $(this).attr('checked'));
  });

  // Delete addresses from list
  $('#delete-addresses').click(function() {
    $.post(
      $(this).attr('href'),
      $('input.select-address').serialize(),
      function(data) {
        $('#delete-addresses').html(data);
      }
    );

    return false;
  });

  // Add addresses to address book
  $('#add-addresses').click(function() {
    $.post(
      $(this).attr('href'),
      $('input.select-address').serialize(),
      function(data) {
        $('#add-addresses').html(data);
      }
    );

    return false;
  });

  // add to address book ajax link
  $('#add-to-address-book').click(function() {
    $.post(
      $(this).attr('href'),
      function(data) {
        $('#add-to-address-book').replaceWith(data);
      }
    );
    return false;
  });

  // Remove from address book ajax link
  $('#remove-from-address-book').click(function() {
    $.post(
      $(this).attr('href'),
      function(data) {
        $('#remove-from-address-book').replaceWith(data);
      }
    );
    return false;
  });

  /* The three next blocks should be refactored. Not enough time though */

  $('#friends_filter_criteria').change(function(data) {
    $.getJSON('/ajax/friends/search-parameters.json', { q: $(this).val() }, function(data) {
      $('#friends_filter_value').html('<option>-Please wait-</option>');
      var options = '<option>' + chooseAValue + '</option>';
      for (id in data)
      {
        options += '<option value="' + data[id] + '">' + data[id] + '</option>';
      }
      $('#friends_filter_value').html(options);
    });
  });

  $('#fof_filter_criteria').change(function(data) {
    $.getJSON('/ajax/fof/search-parameters.json', { q: $(this).val() }, function(data) {
      $('#friends_filter_value').html('<option>-Please wait-</option>');
      var options = '<option>' + chooseAValue + '</option>';
      for (id in data)
      {
        options += '<option value="' + data[id] + '">' + data[id] + '</option>';
      }
      $('#friends_filter_value').html(options);
    });
  });

  $('#member_filter_criteria').change(function(data) {
    $.getJSON('/ajax/member/search-parameters.json', { q: $(this).val(), memberId: $('#memberId').val() }, function(data) {
      $('#friends_filter_value').html('<option>-Please wait-</option>');
      var options = '<option>' + chooseAValue + '</option>';
      for (id in data)
      {
        options += '<option value="' + data[id] + '">' + data[id] + '</option>';
      }
      $('#friends_filter_value').html(options);
    });
  });

  $('#friends_filter_value').change(function(data) {
    $('#friends_filter_form').submit();
  });

  // Open a dialog to update friend group
  $('.friend-update-group').click(function() {
    var link = $(this);
    $('#friend-dialog').load($(this).attr('href')).dialog({
      modal: true,
      autoOpen: false,
      buttons: {
        Save: function() {
          $.ajax({
            type: 'POST',
            url: $(this).find('form').attr('action'),
            data: $(this).find('form').serialize(),
            success: function(data){
              link.html(data);
              $('#friend-dialog').dialog('close');
            }
          });
        },
				Cancel: function() {
					$(this).dialog('close');
				}
      },
      width: 400

    }).dialog('open');
    return false;
  });

  // Open a dialog to show contact data
  $('.friend-contact-data').click(function() {
    $('#friend-dialog').load($(this).attr('href')).dialog({
      modal: true,
      autoOpen: false,
      width: 400,
      buttons: {
        Close: function() {
          $(this).dialog('close');
        }
      }
    }).dialog('open');
    return false;
  });

  $('#addresses_filter_criteria').change(function(data) {
    $.getJSON('/ajax/addresses/search-parameters.json', { q: $(this).val() }, function(data) {
      $('#addresses_filter_value').html('<option>-Please wait-</option>');
      var options = '<option>' + chooseAValue + '</option>';
      for (id in data)
      {
        options += '<option value="' + data[id] + '">' + data[id] + '</option>';
      }
      $('#addresses_filter_value').html(options);
    });
  });

  $('#friends_addresses_filter_criteria').change(function(data) {
    $.getJSON('/ajax/friends-addresses/search-parameters.json', { q: $(this).val() }, function(data) {
      $('#addresses_filter_value').html('<option>-Please wait-</option>');
      var options = '<option>' + chooseAValue + '</option>';
      for (id in data)
      {
        options += '<option value="' + data[id] + '">' + data[id] + '</option>';
      }
      $('#addresses_filter_value').html(options);
    });
  });

  $('#addresses_filter_value').change(function(data) {
    $('#addresses_filter_form').submit();
  });
  //
  // Open a dialog to update address list
  $('.address_update_list').click(function() {
    var link = $(this);
    $('#address-dialog').load($(this).attr('href')).dialog({
      modal: true,
      autoOpen: false,
      buttons: {
        Save: function() {
          $.ajax({
            type: 'POST',
            url: $(this).find('form').attr('action'),
            data: $(this).find('form').serialize(),
            success: function(data){
              link.html(data);
              $('#address-dialog').dialog('close');
            }
          });
        },
				Cancel: function() {
					$(this).dialog('close');
				}
      },
      width: 400

    }).dialog('open');
    return false;
  });

  // Set article action name on icon hover
  $('#article-actions ul li a').hover(function() {
    $('#article-actions ul li a').removeClass('hover')
    $(this).addClass('hover').siblings();
    $('#article-actions span.action-name').html($(this).children('span').html());
  });

 // Open 'send to friends' dialog
  $('#send-to-friends').click(function() {
    $('#article-dialog').load($(this).attr('href')).dialog({
      modal: true,
      autoOpen: false,
      buttons: {
        Save: function() {
          $.ajax({
            type: 'POST',
            url: $(this).find('form').attr('action'),
            data: $(this).find('form').serialize(),
            success: function(data){
              $('#article-dialog').dialog('close');
            }
          });
        },
				Cancel: function() {
					$(this).dialog('close');
				}
      },
      width: 550,
      height: 450

    }).dialog('open');
    return false;
  });

  $('.accordion h2').click(function() {
    $(this).toggleClass('opened').next().toggle();
    return false;
  }).next().hide();

  $('.accordion h2.first').toggleClass('opened').next().show();

  $('li.action.favorite a').click(function() {
    $.post(
      $(this).attr('href'),
      function(data) {
        $('.action-name').html(data);
      }
    );
    return false;
  });

  $('a.colorbox').click(function() {
    $.fn.colorbox({
      href: $(this).attr('href'),
      iframe: true,
      modal: true,
      width: 900,
      height: 500
    });
    return false;
  });
})
