Cheddr = new function() {
  this.globals = {
    mode: 'development'
  };
  this.init = function() {
    // Define an object in the global scope (i.e. the window object)
    window.$cheddr = {
      // Initialize all the queries you want to use more than once
      head : $('head'),
      globals : Cheddr.globals,
      is_production : (Cheddr.globals['mode'] == 'production')
    };
    window.$cheddr = $.extend(Cheddr.globals, window.$cheddr);
  };
}
if (window.$cheddr) {} else {
  Cheddr.init();
}
$cheddr['mode'] = 'production';
$cheddr['contest']      = $cheddr['contest']            || {};
$cheddr['contest'].id   = $cheddr['contest'].id         || 1165;
$cheddr['block_interactions']      = $cheddr['block_interactions']            || false;
// Create a namespace for twitter
$cheddr['twitter']                     = $cheddr['twitter']                   || {};
// Save Twitter Session Variables to namespace
$cheddr['twitter'].has_twitter_oauth   = $cheddr['twitter'].has_twitter_oauth || false;
$cheddr['twitter'].screen_name         = $cheddr['twitter'].screen_name       || "";
$cheddr['twitter'].profile_image_url   = $cheddr['twitter'].profile_image_url || "";
// Create a namespace for our participant
$cheddr['participant']      = $cheddr['participant']                          || {};
$cheddr['participant'].id   = $cheddr['participant'].id                       || null;

$(function() {
  // show a simple loading indicator
  var loader = jQuery('<div id="loader"><img src="/img/sprites/busy.gif" alt="loading..." /></div>')
  .css({position: "absolute", top: "1px", left: "25px"})
  .appendTo("body")
  .hide();
  jQuery().ajaxStart(function() {
    loader.show();
  }).ajaxStop(function() {
      loader.hide();
  }).ajaxError(function(a, b, e) {
      throw e;
  });
});

$cheddr['participant'].load_twitter_auth = function(contest_id) {
  // Set href target and other attributes on the oauth_entry_form form
  $('#oauth_entry_form').attr('action', '/' + $cheddr['contest'].id + '/enter.json');

  //alert('here in load twitter auth 1');
  $(function() {
    //alert('here in load twitter auth 2');
    // if authorized via oauth, need to set display of twitter user variables, and conditonally bind events
    if ($cheddr['twitter'].has_twitter_oauth) {
      //alert('has twitter oauth, loading divs with twitter user info!');
      // ####### Add twitter user screen name and profile image to 'twtSess' div ##################
      $('#twtSess').append("<img src=\""+$cheddr['twitter'].profile_image_url+"\" alt=\""+$cheddr['twitter'].screen_name+"\'s Avatar (That\'s You!)\" id=\"twitter_profile_image_url\" />");
      $('#twtSess').append("<div class=\"twtLoggedIn\">"+"You're logged in as <span id=\"twitter_user_screen_name\">"+$cheddr['twitter'].screen_name+"</span>"+'<a href="/oauth/logout.html">Log out</a>'+"</div>");
      // ####### Bind Events for 'instant' entry ##################################################
      $("a#enter_w_ajax_rolldown_submit").each(function (i){
        $(this).click(function(event) {
          event.preventDefault();
          if ( $("#body_for_oauth").valid() ) {
            $("#oauth_entry_form").ajaxSubmit({
              method:       'POST',
              dataType:     'json',
              success:      processJson
            });
          }
          else {
            return false;
          }
        });
        return false;
      });

    }
    else {
      //alert('NO oauth, setting form to "popup"');

      // Set enter_w_ajax_rolldown_submit href
      var popup_href = '/' + $cheddr['contest'].id + '/oauth/popup.html?parent_hostname='+document.location.host;
      $('#enter_w_ajax_rolldown_submitl').attr('href', popup_href).attr('target', 'popupWindow');
      // ############## Bind Events for 'popup' oauth passthrough and then entry ##################
      $("a#enter_w_ajax_rolldown_submit").each(function (i){
        $(this).click(function(event) {
          // Prevent the browser's default onClick handler
          event.preventDefault();
          var params = $(this).data("popup") || {};
          if ($(this).attr("target")) {
            params.windowName = $(this).attr("target");
          }
          popup_href += '&tweet=' + encodeURI($("textarea[name='body_for_oauth']").val());
          $("textarea[name='body_for_oauth']").val('');
          var windowObject = $cheddr['util'].popup.open(popup_href, params);
          $(this).data("windowObject", windowObject);
        });
      });
    }
    // ############## Show hidden div now that it is 'complete' ###################################
    //alert('here in load twitter auth 3');
    $('#oa_enter').show();
    //alert('here in load twitter auth 4');
  });
}
$cheddr['participant'].load_votes = function(contest_id) {
  $(function() {
    if ($cheddr['participant'].id) {
      var d = new Date();
      $.getJSON('/' + $cheddr['contest'].id + '/voting/' + $cheddr['participant'].id + '.json?t='+(d.getTime()-d.getMilliseconds())/1000, function (data){
        if ((data) && (data.voting_results)) {
          $cheddr['participant'].voting_results = data.voting_results;
          jQuery.each($cheddr['participant'].voting_results, function(val, i) {
            // find and set class on voting button if found.  Voting buttons are id: trigger-entry-#{entry_id}-#{'up'||'down'}
            var new_name = ''; var old_name = ''; var direction_name = '';
            if (i == 1) { var new_name = 'plus-atv'; var old_name = 'plus'; var direction_name = 'up'; }
            else { var new_name = 'minus-atv'; var old_name = 'minus'; var direction_name = 'down'; }
            $('#trigger-entry-' + val + '-' + direction_name).removeClass(old_name).addClass(new_name);
          });
        }
      });
    }
  });
}
$cheddr['participant'].block_votes = function(block)
{
  if (block) {
     $('.voteButtons').block({ message: null }).children().block({ message: null }).children().block({ message: null });
     $('.voteButtons').parent().block({ message: null });
     $cheddr['block_interactions'] = true;
  }
  else {
    $('.voteButtons').unblock().children().unblock().children().unblock();
    $('.voteButtons').parent().unblock();
    $cheddr['block_interactions'] = false;
  }
}
$(function() {
  //alert('dom ready');
  $cheddr['contest_id']      = $cheddr['contest_id']    || 1165;
  // TODO: move this inline?
  //alert('loading twitter auth');
  $cheddr['participant'].load_twitter_auth($cheddr['contest_id']);

  $('.plus, .minus, .retweet').show();
});