// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


// http://ozmm.org/posts/jquery_and_respond_to.html
// jQuery.ajaxSetup({ 
//   'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
// });


/*
 * Override a few of the autocomplete defaults
 */

$.Autocompleter.defaults.matchSubset = false;
$.Autocompleter.defaults.displayNotFound = true;
$.Autocompleter.defaults.displayNotFoundText = 'No se puede encontrar';
$.Autocompleter.defaults.max = 18;

//  FROM http://henrik.nyh.se/2008/05/rails-authenticity-token-with-jquery
/*
$(document).ajaxSend(function(event, request, settings) {
  if (typeof(AUTH_TOKEN) == "undefined") return;
  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});
*/ 

  $.fn.toogle_companies = function() {
  	this.each(function(){
  		this.initial_value = $(this).val();
  		$(this).click(function(e){
  		  $("ul.applicationTabs li").removeClass("active");
  		  $(this).parent().addClass("active");
  		  $(".infobox").hide();
  		  $("#more_" + this.id).show();
  		});
  	});
  };

  
  function setupAutoCompleter(fieldId, listPath, options ) {
    var opts = {};
    $.extend(opts, { 
        matchContains: true, 
        mustMatch: true, 
        minChars: 2,
        cacheLength: 1
      }, options);
    $(fieldId).autocomplete(listPath, opts);
    /*   .result(function(event, data, formatted) {
      $(this).next().val(data[1]);
    }); */
  }
  
  function setupCountryProvinceFields(selector, spain_id) {
    $(selector).livequery('change', function(event) {
      if($(this).val() == spain_id) {
        $('#spanish_province').show().change();
        $('#candidate_province').hide();
      } else {
        $('#spanish_province').hide();
        $('#candidate_province').show();
      }
    }).change();
        
    $('#spanish_province').livequery('change', function(event) { 
      $('#candidate_province').val($(this).val());
    });
  }
  
  
    /*
     * Autocompleters used on Search forms!
     */
    var Autocompleters = {
    init: function() {
      //
      // Universities
      //
      $('input.autocomplete.universities').autocomplete('/autocomplete/universities', {
        matchContains: true,
        selectFirst: true, 
        delay: 200,
        minChars: 2,
        cacheLength: 1
      }).result(function(event, data, formatted) {
        $(this).val(data[1]);
        $(this).parents('form').find('input.autocomplete.university_degrees').val('');
        $(this).change().blur();
        $(this).parents('form').change();
      }).noResult(function(event, data, formatted) {
        $(this).parents('form').find('input.autocomplete.university_degrees').val('');
      });
    
      //
      // University Degrees
      //
      $('input.autocomplete.university_degrees').autocomplete('/autocomplete/university_degrees', {
        matchContains: true,
        selectFirst: true,
        delay: 200,
        minChars: 2,
        cacheLength: 1,
        extraParams: {
          university_display_name: function() { 
            return this.parents('form').find('input.autocomplete.universities').val(); }
        }
      }).result(function(event, data, formatted) {
        $(this).change().blur();
        $(this).parents('form').change(); 
      });
      
      //
      // MastersInstitutes
      //
      $('input.autocomplete.masters_institutes').autocomplete('/autocomplete/masters_institutes', {
        matchContains: true,
        selectFirst: true,   
        delay: 200,
        minChars: 2,
        cacheLength: 1
      }).result(function(event, data, formatted) {
        $(this).parents('form').find('input.autocomplete.masters_degrees').val('');
        $(this).change().blur();
        $(this).parents('form').change();
      }).noResult(function(event, data, formatted) {
        $(this).parents('form').find('input.autocomplete.masters_degrees').val('');
      });
    
      //
      // MastersDegrees
      //
      $('input.autocomplete.masters_degrees').autocomplete('/autocomplete/masters_degrees', {
        matchContains: true,
        delay: 200,
        minChars: 2,
        cacheLength: 1,
        extraParams: {
          masters_institute_display_name: function() { return this.parents('form').find('input.autocomplete.masters_institutes').val(); }
        }
      }).result(function(event, data, formatted) {
        $(this).change().blur();
        $(this).parents('form').change();
      });
      
      //
      // Exchanges
      //
      $('input.autocomplete.exchange').focus( function() { this.select(); } );
    
      $('input.autocomplete.exchange').autocomplete('/autocomplete/universities', {
              matchContains: true, 
              minChars: 2,
              cacheLength: 1,
              extraParams: {
                country_id: function() { return $('#exchange_country_id').val(); }
              }
      }).result(function(event, data, formatted) {
        $(this).next().val(data[1]);
      }).noResult(function() {
         $(this).next().val(''); 
      });

  
      //
      // Employers
      //
      $('input.autocomplete.employers').autocomplete('/autocomplete/employers', {
        matchContains: true,
        delay: 200,
        minChars: 2,
        cacheLength: 1
      }).result(function(event, data, formatted) {
        $(this).change().blur();
        $(this).parents('form').change();
      });      
    }
    
  };

  var Searchfields = {
    init: function() {
      $('input.resettable').livequery( function() {
        $(this).wrap('<div class="searchfield"></div>')
               .after('<span class="right_end"></span>')
              .before('<span class="left_end"></span>')
              .after('<div class="reset">X</div>');
      
        if($(this).val() == '') {
          $(this).siblings('.reset').hide();
        }
              
      });  
      
      $('input.resettable').livequery('keypress', function() {
        var $this = $(this);
        if($this.val() == '') {
          $this.siblings('.reset').hide();
        } else {
          $this.siblings('.reset').show();
        }
      });
        
      $('div.searchfield .reset').click(function() {
        $(this).siblings('input.resettable').val('').parents('form').change();
        $(this).hide();
      });

    }
  };


/*
 * THINGS TO DO WHEN THE DOCUMENT IS READY!
 */
$(document).ready( function() {
  
  $("ul.applicationTabs li a" ).toogle_companies();

  // Spinners

  $('ul.options').livequery(function() {
    $(this).append("<li class='spinner'></li>").find('li.spinner').hide();
  });
  
  $('form').livequery('form:beforeSend', function(r, s, e) {
    var $list =  $(this).find('ul.options');
    $list.find('li.spinner').show();
    $list.find('li:not(.spinner)').hide();
  });
  
  $('form').livequery('form:complete', function() {
    var $list =  $(this).parents('ul.options');
    $list.find('li.spinner').hide();    
    $list.find('li:not(.spinner)').show();    
  });

  $('form').livequery('form:complete', function() {
    var $list =  $(this).find('ul.options');
    $list.find('li.spinner').hide();    
    $list.find('li:not(.spinner)').show();    
  });

    
  $('ul.options li a').livequery('link:beforeSend', function() {
    var $list =  $(this).parents('ul.options');
    $list.find('li.spinner').show();    
    $list.find('li:not(.spinner)').hide();    
  });
  
  $('ul.options li a').livequery('link:complete', function() {
    var $list =  $(this).parents('ul.options');
    $list.find('li.spinner').hide();    
    $list.find('li:not(.spinner)').show();    
  });
  

  
  $('.messageLink').click(function(e){
    $(this).next('.messageBody').toggle();
    if(!$(this).hasClass('read')) {
      var id = $(this).find('input#id').val();
      $(this).addClass('read');
      $.ajax({dataType:'script', type:'put', url:'/messages/'+id, data: {"message[read]": true}});
    }
  });

  $('.messageBody .reply_message').click(function(e){
    $(this).parents('ul.options').hide();
    $(this).parents('.messageBody').find('form.messageReply').toggle();
    return false;
  });

  $('.messageBody form.messageReply li.cancel a').click(function(e){
    $(this).parents('.messageBody ul.options(:first)').show();
    $(this).parents('form.messageReply').hide();
    return false;
  });
  
});


// Profile section
// Date
$('.inlineText #employment_end_date_2i').livequery( function() {
  $(this).change(function() {
    if ($(this).val() == '') {
      $(this).next().prepend('<option value=""></option>');
      $(this).next().hide();

      $(this).prev().val('');
      $(this).next().val('');
    } else {
      $(this).next().find('option:first').remove();
      $(this).next().show();
    }  
  });
  
  $(this).change();
  $(this).find('option:first').html('actualmente');
});



$('.autodisable').live("click",function(event){
  if ($(this).attr('disabled') == false ) {
    $(this).closest('form').submit();
    $(this).text( $(this).text()+'...');
    $(this).attr('disabled','disabled');
  } else {
    return false;
  }
  
});

// ListItemManager
// Enhance an unordered list of items, allowing for the addition
// or removal of new items based on a template item li.new_item_template
// The template item is removed from the list when the ListItemManager is inited
// TOOD: Make it more general. e.g.:
// $('ul.list').manageList({template_selector: '.new_item_template', remove_label: 'remove item', add_label: 'add an item'})
// $('ul.list').manageList({template_selector: '<li>A new item goes here</li>'})
// TODO: Make markup a bit more flexible, especially the linkAdder?
// TODO: Remove livequery dependency?

var ListItemManager = {
  init: function(){
    $('ul.job_categories').livequery(function(){
      var $list = $(this);

      var $template = $list.find('li.new_item_template');
      $list.data('new_item_template', $template);
      $template.remove();

      $list.find('li').each(function () {
        if ($(this).prevAll().length > 0) {
          $(this).append('<a class="delete" href="#">quitar</a>').find('a').click(function (event) {
            event.preventDefault();

            $(this).closest('li').remove();
          });
        }
        $(this).find('select').splitOptGroups();
      });

      $add_link = $('<a>'); 
      $add_link.append('añadir otra').attr('href', '#').click(function(event) {
        event.preventDefault();

        var list = $(this).parent().prev('ul');

        var item = list.data('new_item_template').clone();
        list.append(item);

        item.append('<a class="delete" href="#">quitar</a>').find('a').click(function (event) {
           event.preventDefault();
           $(this).closest('li').remove();
         });

         item.find('select').splitOptGroups();

      });
      $list.after($('<div>').addClass('list-item-manager').append($add_link));
      
    });
  }
};

var Facebook = {
  connect: function() {
    var session = FB.getSession();
    if(session) {
      var redirect_url = "/profile/connect?fb_access_token=" + session.access_token + '&fb_id=' + session.uid;
      window.location.href = redirect_url;
    }
  },
  signup: function() {
    var session = FB.getSession();
    if(session) {
      var redirect_url = "/signup/new?fb_access_token=" + session.access_token + '&fb_id=' + session.uid;
      window.location.href = redirect_url;
    }
  }
};