// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function pledge_awesomeness( total_points ) {
  var current_awesomeness_level;
  $('.awesomeness .score').hide().each( function() { 
    $('.awesomeness .statcontentbottombg').removeClass( 'score-' + $(this).attr('data-level'));
    if( new Number( $(this).attr('data-threshold') ) <= total_points ) { 
      current_awesomeness_level = $(this).attr('data-level');
    }
  } );

  if ( current_awesomeness_level !== undefined ) {
    //$(current_awesomeness_level).show();
    $('.awesomeness .statcontentbottombg').addClass( 'score-' + current_awesomeness_level );
  }
}
function pledge_scoring() {
      var total = 5;
      var total_points = 0;

      $('.mode_of_transport .pledge_size:checked').each(function() {
        if( new Number( $(this).val() ) >  0 ) { total = total - new Number($(this).val()); }
        total_points += new Number( $(this).attr('data-points'));
      });
      pledge_awesomeness.call(this, total_points );

      $('.mode_of_transport').each( function() {
        var row_value = $('.pledge_size:checked', this ).val() || 0;    
        for( i = 0; i <= 5; i++ ) {
          $('.days_block', this).removeClass('days_' + i );
        }
        $('.days_block', this).addClass('days_' + row_value);
        if( row_value > 0 ) {
          $('.days_block_start', this).addClass('days_block_start_active');
        } else {
          $('.days_block_start', this).removeClass('days_block_start_active');
        }
        var limit = new Number( row_value ) + ( total );

        $('.pledge_size', this).each( function() { 
          var item_value = new Number( $(this).val());
          if( item_value > limit ) {
            $(this).attr('disabled', true );
            $(this).parent('.pledge_size_container').addClass('disabled');
          } else {
            $(this).attr('disabled', 0 );
            $(this).parent('.pledge_size_container').removeClass('disabled');
          }
          if( item_value <= row_value && item_value != 0 ) { 
            $(this).parent('.pledge_size_container').addClass('active');
          } else {
            $(this).parent('.pledge_size_container').removeClass('active');
          }
        });
      });
}

/**
 * Put a cookie on the user's browser.
 * 
 * @param {String} name Cookie name.
 * @param {String} value Value to store.
 * @param {Int} days Optional - how long until it expires.
 */
create_cookie = function(name, value, days) {

  // if a number of days has been included in the call, calculate the expiration,
  // otherwise no expiration.
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    var expires = "; expires=" + date.toGMTString();
  } else {
    var expires = "";
  }
  document.cookie = name + "=" + value + expires + "; path=/";
};

/**
 * Looks for param name in browser cookies and returns value if present; null if not.
 *
 * @param {String} name Key to value to return.
 * @returns {String} or {null} Depending on success
 */
read_cookie = function(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for (var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') {
      c = c.substring(1,c.length);
    }
    if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length,c.length);
    }
  }
  return null;
}

function do_facebook_connect(user) {
  //window.location = window.facebook_authenticate_location;
  // $("#facebook_connect").load(window.facebook_authenticate_location);
  $("#facebook_connect").html("<fb:profile-pic facebook-logo='true' size='square' uid='" + user + "'>" +
                              "</fb:profile-pic>");
}

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
  FB.ensureInit(function() {
    FB.Connect.showFeedDialog(form_bundle_id, template_data);
    //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);
    
    // hide the "Loading feed story ..." div
    // ge('feed_loading').style.visibility = "hidden";
  });
}


/*
 * Ensure Facebook app is initialized and call callback afterward
 *
 */
function ensure_init(callback) {
  if(!window.api_key) {
    window.alert("api_key is not set");
  }

  if(window.is_initialized) {
    callback();
  } else {
    FB_RequireFeatures(["XFBML", "CanvasUtil"], function() {
        FB.FBDebug.logLevel = 4;
        FB.FBDebug.isEnabled = true;
        // xd_receiver.php is a relative path here, because The Run Around
        // could be installed in a subdirectory
        // you should prefer an absolute URL (like "/xd_receiver.php") for more accuracy
        FB.Facebook.init(window.api_key, window.xd_receiver_location);

        window.is_initialized = true;
        callback();
      });
  }
}

/*
 * "Session Ready" handler. This is called when the facebook
 * session becomes ready after the user clicks the "Facebook login" button.
 * In a more complex app, this could be used to do some in-page
 * replacements and avoid a full page refresh. For now, just
 * notify the server the user is logged in, and redirect to home.
 *
 * @param link_to_current_user  if the facebook session should be
 *                              linked to a currently logged in user, or used
 *                              to create a new account anyway
 */
function facebook_button_onclick() {

  ensure_init(function() {
      FB.Facebook.get_sessionState().waitUntilReady(function() {
          var user = FB.Facebook.apiClient.get_session() ?
            FB.Facebook.apiClient.get_session().uid :
            null;

          // probably should give some indication of failure to the user
          if (!user) {
            return;
          }

          // The Facebook Session has been set in the cookies,
          // which will be picked up by the server on the next page load
          // so refresh the page, and let all the account linking be
          // handled on the server side

          // This could be done a myriad of ways; for a page with more content,
          // you could do an ajax call for the account linking, and then
          // just replace content inline without a full page refresh.
          // refresh_page();
          // window.location = window.facebook_authenticate_location;
          
          // possible ajax call to link account
          
          // replace the #facebook_connect div with logged in as info:
          // <fb:profile-pic facebook-logo='true' size='square' uid='12345678'></fb:profile-pic>
          // <p>
          //   Logged in using Facebook as:
          //   Bob Jones
          // </p>
          // do_facebook_connect(user);
          
          // put a cookie where we should go next after facebook auth 
          // redirects
          create_cookie('next', window.location);
          
          window.location = window.facebook_authenticate_location;
        });
    });
}

/*
 * Do a page refresh after login state changes.
 * This is the easiest but not the only way to pick up changes.
 * If you have a small amount of Facebook-specific content on a large page,
 * then you could change it in Javascript without refresh.
 */
function refresh_page() {
  window.location = '/';
}

function logout() {
  window.location = '/login/logout';
}

/*
 * Show the feed form. This would be typically called in response to the
 * onclick handler of a "Publish" button, or in the onload event after
 * the user submits a form with info that should be published.
 *
 */
function facebook_publish_feed_story(form_bundle_id, template_data) {
  // Load the feed form
  FB.ensureInit(function() {
          FB.Connect.showFeedDialog(form_bundle_id, template_data);
          //FB.Connect.showFeedDialog(form_bundle_id, template_data, null, null, FB.FeedStorySize.shortStory, FB.RequireConnect.promptConnect);

      // hide the "Loading feed story ..." div
      // ge('feed_loading').style.visibility = "hidden";
  });
}
