// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$(function(){
  $('.disabled').hide().attr("disabled", "disabled");
  $('.focus:last').focus();

  $('a[rel*=facebox]').facebox();
  $('#expert_apply').live('click',function(){
    if($('#expert_form').is(':visible')){
      $('#expert_form').hide().attr("disabled", "disabled");
    }else{
      $('#expert_form').show().removeAttr('disabled');
    }
  });
  $('.fb').live('click',function(){
    if($(this).is(':checked'))
      fb_permissions($(this))
  });
  $('.cancel_goal').live('click',function(){
    $(this).closest('form').submit();
  });
  
  $('img.active_home').live('click',function(){
    mpmetrics.track_funnel("Goto Profile from Dashboard", 2, "Profile");
  });
  setup_slider();
  $(document).bind('reveal.facebox', function() { setup_slider(); })
  
  $('#progress_update_my_goal_id').live('change',function(){
    $('.progress_form').hide();
    $('#my_goal_'+$('#progress_update_my_goal_id').val()).show();
  });

  $(".feedcomment .content").focus(function(){
    //$(this).animate({"height": "85px",}, "fast" );
    $(this).closest('.feedcomment').find(".button_block").slideDown("fast");
    //$(this).focus();
    
    return false;
  });

  $('#new_goal_suggestion :submit').live('click',function(){
    var f = $(this).closest('form');
    $.post(f.attr("action"),f.serialize());
    $('#goal_suggestion_goal').val("");
    $('#suggestion_notify').show();
    return false;
  });
  
  $(".feedcomment .content").blur(function(){
    if(trim($(this).val()) == ""){
      //$(this).animate({"height": "20px",}, "fast" );
      $(this).closest('.feedcomment').find(".button_block").slideUp("fast");
      return false;
    }
  });
  
  $('.open_comment').live('click',function(e){
    $(this).closest('.feed_item').find(".feedcomment").show();
    e.preventDefault();
  });
  
  $('#new_product').validate({rules: {serial: {required:true}},messages: {serial: "Please select a book"}});
  $('#product_new .search').live('click',function(){
    if(trim($('#product_title').val()) != ""){
      populate_books();
    }
  });
  $('.require_user').live('click',function(){
    if(!LOGGED_IN){
      return false;
    }
  });
  $('.progress_update_toggle').toggle(function(){
    $(this).closest('.my_goal').find('.progress_update').show();
  },function(){
    $(this).closest('.my_goal').find('.progress_update').hide();
  });
  
  $('.toggles .option').live('click',function(){
     $(this).closest('.my_goal').find('.options .option').hide();
    $(this).closest('.my_goal').find('.options ' +$(this).attr('tab')).show();
  });
  $('.toggle').live('click',function(){
    $($(this).attr('q')).toggle();
    //$('#call_to_action').show();
  });
  $('.check_fb_perms').live('click',function(){
    check_fb_perms();
  });

  $('.require_user').each(function(){
    if(!LOGGED_IN){
      $(this).tooltip({showURL: false,delay:0});
    }
  }); 
  $('.choose_goal').live('click',function(){
    var me = $(this);
    //$.post('/users/add', {goal : me.attr('goal')});
    $('#enter_goals :text:[value=""]:eq(0)').val(trim(me.text()));
  });
  $('input.datepicker').live('click', function() {
    $(this).datepicker().focus();
  });
  $('.support').live('click',function(){
    if(!LOGGED_IN){
      $('#supporter_signup').show();
      return false;
    }
  });
  $('#facebox #new_my_goal :submit').live('click',function(){
    var f = $(this).closest('form');
    if($('[name=my_goal[status]]:checked') && $('[name=my_goal[status]]:checked').val() == "4"){
      $.post(f.attr("action"),f.serialize());
      $.facebox.close();
      $('#done').removeClass('hidden');
      return false;
    }
    if(f.attr('step')){
      $.post(f.attr("action"),f.serialize(),function(data){
        $.facebox(data);
        $('#facebox .footer').hide();
      });
      return false;
    }else{
      if(!f.attr('back')){
        if(f.attr('refresh')){
          $.ajax({ type: 'POST',url: f.attr("action"), data: f.serialize(), async: false});
          window.location = window.location.href;
        }else{
          $.post(f.attr("action"),f.serialize());
          $.facebox.close();
          $('#done').removeClass('hidden');
        }
        return false;
      }
    }


  });
  function setup_slider(){
    $(".slider").slider({
      min: 1,
      max:7,
      slide: function(event, ui) {
        $(this).closest('form').find('.measurement_display').html(ui.value);
      },
      change: function(event, ui){
        $(this).closest('form').find('.measurement').val(ui.value);
      }
    });
  }
  $('#tabs').tabs();
  tab = $(document).getUrlParam('tab');
  if(tab){
    $('#tabs').tabs('select',tab);
  }
  
  //$('#wysiwyg').wysiwyg();
  
  $('.remove_tip').live('click',function (){
    return confirm('Are you sure you want to remove this?');
  });
  $('.remove_goal').live('click',function (){
    return confirm('Are you sure you want to remove this goal? You\'ll lose your goal journal as well.');
  });
  $('#results .book').live('click',function(){
    $('#product_title').val($(this).attr('title'));
    $('#product_image_url').val($(this).attr('image'));
    $('#product_url').val($(this).attr('url'));
    $('#product_serial').val($(this).attr('isbn'));
    $('#product_new .hidden').show();
    
    $('.book').removeClass('selected');
    $(this).addClass('selected');
  });
  
  $('.add_goal').live('click',function(){
    var l = $(this).attr('href')
    $.facebox(function() { 
      $.get(l, function(data) {
        $.facebox(data);
        $('#facebox .footer').hide();
      })
    })
    return false;
  });
  
});

function populate_books(){
  if($('#product_title').val().length > 2){
    $.get('/home/amazon',{q : $('#product_title').val()},function(data){
      $('#book_options').html(data);
    });
  }
}

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});


function fb_permissions(){
  FB.Connect.requireSession(function(){  
    FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(has_perms) {
      if(has_perms) {
        return false;
      }else{
        FB.Connect.showPermissionDialog('publish_stream',function(result){
        });
        return true;
      }
    });
  });
  $.get('/settings/fb_login');
  
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
