function initJoinChallenge()
{
  //$("#btn-solve-challenge").click(function ()
  //{
  //	$(this).toggleClass("active")
  //	$(".form-join-challenge").toggle();
  //	$("#btn-join-callenge").removeClass("active");
  //});
  $("#btn-join-callenge").click(function ()
  {
    if($("#btn-solve-challenge").hasClass("active"))
    {
      $(this).addClass("active");
      $(".form-join-challenge").hide();
      $("#btn-solve-challenge").removeClass("active");
    }
  });
}
function initTogglers()
{
  $(".challenge-opener span").click(function ()
  {
    $(this).find("a").attr("href", "javascript:;");
    $(this).parent().parent().toggleClass("active");
    return false;
  });

  $(".opener").click(function ()
  {
    $(this).find("a").attr("href", "javascript:;");
    $(this).parent().toggleClass("active");
    return false;
  });

  $(".close").click(function ()
  {
    $(this).find("a").attr("href", "javascript:;");
    $(this).parent().removeClass("active");
    $(this).parent().parent().removeClass("active");
    return false;
  });
}
var number = 1;
function initAddEmail()
{
  $(".add-another").click(function ()
  {
    $("<div class='wrapper'><label for='email-" + ++number + "'>Judge " + number + "</label><input type='text' value='E-mail address' class='input' id='email-" + number +"'/></div>").appendTo($(".emails"));
    return false;
  });
}
function initFormOpener()
{
  var openers = $(".form-opener").find("li");
  $(openers).each(function(i, el)
  {
    $(el).click(function ()
    {
      if($(this).hasClass("active"))
      {
        $(this).removeClass("active");
        $(this).parent().parent().removeClass("active");
      }
      else
      {
        $(openers).removeClass("active");
        $(this).addClass("active");
        $(this).parent().parent().addClass("active");
      }
      return false;
    });
  });
/*$("#btn-found-solution").click(function ()
	{
		$(this).parent().toggleClass("active");
		if($(this).parent().hasClass("active"))
			$(".solution-existing-box").show();
		else
			$(".solution-existing-box").hide();
		return false;
	});*/
}
function initTabs(h_list)
{
  $(h_list).each(function(_ind, _el) {
    var btn_h = $(_el);
    var _btn = $(_el).find("a.tab");
    var _a = 0;
    _btn.each(function(_ind, _el) {
      this._box = $("#"+_el.href.substr(_el.href.indexOf("#") + 1));
      if($(_el).hasClass("active")) {
        this._box.show();
        _a = _ind;
      }
      else {
        this._box.hide();
      }
      _el.onclick = function() {
        if(!$(this).hasClass("active")){
          _btn.get(_a)._box.hide();
          _btn.eq(_a).removeClass("active");
          this._box.show();
          $(this).addClass("active");
          _a = _ind;
        }
        return false;
      }
    });
  });
}

function initPage()
{
  initTabs(".tabset");
  initTogglers();
  // initJoinChallenge();
  initFormOpener();
// initAddEmail();
}

if (window.addEventListener)
{
  window.addEventListener("load", initPage, false);
}
else if (window.attachEvent)
{
  window.attachEvent("onload",initPage);
}


var Challenge = new function()
{


  this.AttachThankyouPostForm = function(form)
  {

    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {

        $('.error').removeClass('error');

        $('.error-message').remove();
        $('.success-message').remove();

        if (data.result == 1)
        {

          Challenge.ThankyouSubmitted(data);
          if ($('#update_facebook_feed').is(':checked'))
          {
            Challenge.PublishFacebookLink(location.href, '');
          }

          if ($('#update_twitter_feed').is(':checked'))
          {
            var message = $('#wish-input').val();
            if (message.length > 95)
            {
              message = message.substring(0, 95) + '...';
            }
            Challenge.PublishTwitterLink(message + ' http://bit.ly/7nJTrl' + " #NYCBigApps Winners");
          }
          $('#thankpost').hide();
        }
        else
        {
          $('#wish-input').parent().addClass('error');
          $('#wish-input').parent().append('<span class="error-message">'+data.message+'</span>');
        }
      },

      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      beforeSubmit: function () {
        // CPGlobal.ShowWaitMessage();
        var isvalid = true;
        pageTracker._trackPageview(form.attr('action'));
        $(".defaultText").each(function() {
          if($(this).val() == $(this).attr('title')) {
            $('#wish-input').parent().addClass('error');
            $('#wish-input').parent().append('<span class="error-message">Please enter a wish</span>');
            isvalid = false;
          }
        });
        return isvalid;
      },

      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      $(this).ajaxSubmit(options);
      return false;
    });


    $('#btn-thank-submit').click(function () {
      Challenge.ThankYouPost();
      return false;
    });

  };

  this.ThankYouPost = function()
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $("#thankpost").submit();
    } );
  };

  this.ThankyouSubmitted = function(data)
  {
    $('#wish_submitted').removeClass('hide');
    $('.error').removeClass('error');
    $('.error-message').remove();
    $('#thankpost').after('<span class="success-message">'+data.message+'</span>');


  };

  this.SetupGiftCard = function()
  {
    // add a button to the place after the field
    $('#gift_card').after('<input type="button" value="Apply" id="apply"/>');
    $('#gift_card').parent().show();

    // get the money amount that they entered

    $('#apply').click(function() {

      // remove any error messages

      $('.card_message').html('');

      $.getJSON('/challenge/checkcoupon', {
        "code" : $('#gift_card').val(),
        "amount" : $('#money').val()
      }, function(data){

        $('.card_message_row').show();
        $('.card_message').html(data.message);
        $('.card_message').html(data.message);



      });


    });

  }

  this.SolutionVoteFromList = function(url)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $.post(url, {}, function(data, textStatus) {
        Challenge.SolutionVotedFromList(data);
      }, 'json');
      return false;
    });
  };


  this.SolutionVotedFromList = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
      return;
    }

    if (data.votes == 1)
    {
      $('#solution_vote_count_' + data.solution_id).html(data.votes + " vote");
    }
    else
    {
      $('#solution_vote_count_' + data.solution_id).html(data.votes + " votes");
    }

    $('.btn-solution-vote').hide();

    $('.vote-box-' + data.solution_id).show();


  };


  this.SetupSolveTermsAgree = function()
  {
    $("div.terms-shell").scroll( function() {

      });

    $('#agreeterms').click(function() {

      if ($("div.contents").length > 0)
      {
        shellHeight = $("div.contents").innerHeight();
        scrollPosition = $("div.terms-shell").scrollTop();

        if(shellHeight < (scrollPosition + 376))
        {

        }
        else
        {
          alert('Please read the entire agreement.');
          $(this).attr('checked', false);
        }
      }
    });



  }

  this.SetupVoteSolutionLinks = function()
  {
    $(".btn-solution-vote").unbind("click");

    $('.btn-solution-vote').each(function() {
      $(this).click(function () {
        Challenge.SolutionVoteFromList($(this).attr('href'));
        return false;
      });
    });
  };



  this.SupportPromote = function(url)
  {

    CPGlobal.ShowWait('.info fieldset .wheel2 span');
    $('.error-message', '#usersupportpromote').remove();
    var message = jQuery.trim($('#status').val());

    if (message === "")
    {
      var messages = new Array();
      messages[0] =  "A message is required";
      message = CPGlobal.BuildErrorMessage(messages);
      if (!$('.error-message', '#usersupportpromote').length) {
        $('#status').after(message);
      }
      CPGlobal.HideWait();

      return false;
    }
    else if (!$('#update_facebook_feed').is(':checked') && !$('#update_twitter_feed').is(':checked'))
    {
      var messages = new Array();
      messages[0] =  "Please select at least one external site";
      message = CPGlobal.BuildErrorMessage(messages);
      if (!$('.error-message', '#usersupportpromote').length) {
        $('#status').after(message);
      }
      CPGlobal.HideWait();

      return false;
    }
    else
    {
      if ($('#update_facebook_feed').is(':checked'))
      {
        Challenge.PublishFacebookLink(url, '');
      }

      if ($('#update_twitter_feed').is(':checked'))
      {
        Challenge.PublishTwitterLink(message);
      }

    }
    CPGlobal.HideWait();

    $('.promote-form').hide();

    $('.promote-confirm').slideDown('slow');

  }

  this.SupportToggle = function() {
    $('#incr-adult, #incr-kid').removeClass('hidden');
    $('#supportFamily').attr('style', '');
  }

  this.SupportAdd = function() {

    var SendSupport = function (options, data) {

      var params = {
        type: "POST",
        dataType: "json",
        url: "",
        data: data,
        onSuccess: function() {},
        onError: function() {},
        onComplete: function() {}
      }

      params = $.extend(params, options);

      $.ajax({
        type:params.type,
        dataType: params.dataType,
        url: params.url,
        data: data,
        success: function() {
          params.onSuccess();
        },
        error:function() {
          params.onError();
        },
        complete:function() {
          params.onComplete();
        }
      })
    }

    var cancelSupport = function() {
      SendSupport({
        url:"/challenge/usda-apps-for-healthy-kids/rm-support-family/"
      },{
      // no data required
      });

      $.each(["adult", "kid"], function(index, who) {
        $("#incr-"+who).css("background-image", "url(modules/usda/images/ico-"+who+".gif)");
        var select = $(":input[name=incr-"+who+"]");
        if (select.attr("disabled")) {
          select.removeAttr("disabled");
          // decrement
          increment(select, who, -select.val());
        }
      })

      hideCancel();
    }

    // add supporters
    var increment = function(select, who, value) {

      var defvalue = (typeof value != "undefined");

      // value of the select input
      var val = 0;
      if (defvalue) {
        val = value;
      } else {
        val = select.val();
      }

      // elt to increment
      var elt = $("#support_" + who);

      // Update the number of supporters, adults and kids
      if (!defvalue) {
        var data = {};
        data = {
          "incr-kid": 0,
          "incr-adult": 0
        }
        data["incr-" + who] = val;
        var options = {
          url: "/challenge/usda-apps-for-healthy-kids/support-family/"
        }
        SendSupport(options, data);
      }

      var incr_elts = function(elts, value) {
        $.each(elts, function(index, jelt) {
          var curr = jelt.html()
          curr = curr.replace(/,/g, "");
          
          var final_value = (parseInt(curr) ) + value;

          var convertint = function (value) {
            if (!parseInt(value / 1000)) {
              return value;
            }
            return convertint(parseInt(value / 1000)) + "," + (value % 1000);
          }
          

          jelt.html(convertint(final_value));
        });
      }

      incr_elts([elt, $(".family strong")], parseInt(val));

      if (!defvalue) {
        select.attr("disabled", "disabled");
        $("#incr-"+who).css("background-image", "url(modules/usda/images/ico-"+who+"-purple.gif)");
        showCancel();
      }

    }

    var showCancel = function() {
      $("#undo").slideDown("fast");
    }
    var hideCancel = function() {
      $("#undo").slideUp("fast");
    }


    // Add adults supporters
    var AdultsAdd = function(select, value) {
      increment(select, "adult", value);
    }

    // add kids supporters
    var KidsAdd = function(select, value) {
      increment(select, "kid", value);
    }

    return {
      adults:AdultsAdd,
      kids:KidsAdd,
      cancel:cancelSupport
    }

  }

  this.SupportRegister = function(url)
  {

    var validateForm = function() {
      $(".row.error").removeClass("error");
      
      var required = $(".defaultText.required");
      required.each(function(i) {
        if ($(this).attr("value") == $(this).attr("title")) {
          $(this).parent(".row").addClass("error");
          $(this).after('<div class="error-message">This value is required</div>')
        }
      });
      if ($(".row.error").length) {
        return false;
      }
      return true;
    }

    var regoptions = {
      complete: function() {
        CPGlobal.HideWait();
        $('#btn-register').removeAttr("disabled");
      },
      success: function(data) {

        if (data.result == 1)
        {
          // callback();

          // show a confirmation screen
          loggedin = 1;

          // $('#continueaction').click(function() { $.modal.close(); callback(); });

          ChallengeUser.RefreshTopMenu();

          // show them a button which when clicked will do what they had started to do

          pageTracker._trackPageview(location.pathname + '/supportregister');

          var href = '/challenge/' + url + '/metoo';

          $.post(href, {}, function(data, textStatus) {
            CPGlobal.HideWait();
            $('.support-register').hide();
            $('.why-joined').show();
          }, 'json');

        }
        else
        {

          $('.error-message').remove();

          CPGlobal.AttachErrorMessages(data.errors);

          $('#usersupportregister').append('<div class="error-message">'+data.message+'</div>');
        }
      },
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      resetForm: false,        // reset the form after successful submit
      timeout:   3000,

      beforeSubmit: function () {
        $('.error-message').remove();
        CPGlobal.ShowWait('.info fieldset .wheel3 span');

        if (!validateForm()) {
          CPGlobal.HideWait();
          return false;
        }

        $('#btn-register').attr("disabled", "true");
        pageTracker._trackPageview('/register');
        return true; // @todo validate to make sure that they enter something
      }
    };

    $('#usersupportregister').unbind('submit');

    // bind to the form's submit event


    $('#usersupportregister').submit(function() {
      $(this).ajaxSubmit(regoptions);
      return false;
    });

  };


  this.Support = function(link)
  {
    var href = link.attr("href");

    $('.error-message').remove();

    pageTracker._trackPageview(location.pathname + '/support');

    CPGlobal.ShowWait('.me-too .wheel');
    $.post(href, {}, function(data, textStatus) {

      CPGlobal.HideWait();
      Challenge.SupportComplete(data);
    }, 'json');

    return false;

  }

  this.SupportComplete = function(data)
  {


    if (data.result == 1)
    {
      $('.me-too').hide().after('<h4>Including you!</h4>');


      if (data.user_id == 0)
      {
        $('.support-register').slideDown('slow');
      }
      else
      {
        $('.why-joined').slideDown('slow');
      }

      $('.quantity-box strong').html(data.totalsponsors);

      if (data.totalsupporters > 1)
      {
        $('.quantity-box .want-this').html('PEOPLE WANT<br />THIS SOLVED');
      }

      // Challenge.RefreshChallengers(data.url);

      pageTracker._trackPageview(location.pathname + '/supportcomplete');

      $.cookie("support_" + data.challenge_id, "1", {
        expires: 180
      });


    }
    else
    {
      $('.me-too').prepend('<span class="error-message">'+data.message+'</span>');

      pageTracker._trackPageview(location.pathname + '/supporterror');

    }
  }

  this.MeToo = function(link)
  {

    var href = link.attr("href");

    pageTracker._trackPageview(location.pathname + '/metoo');

    ChallengeUser.LoginRequiredCallback(function() {
      CPGlobal.ShowWait('.me-too .loading');
      $.post(href, {}, function(data, textStatus) {
        CPGlobal.HideWait();
        Challenge.MeTooComplete(data);
      }, 'json');
      return false;
    });

    return false;

  }

  this.MeTooComplete = function(data)
  {
    if (data.result == 1)
    {
      $('.me-too').hide().after('<div class="note-text note-text-center"><p>Including you!</p></div>');

      $('.why-joined').slideDown('slow');
      $('.quantity-box .people').html(data.totalsponsors);
      $('.quantity-box strong:not(.gift)').html(data.totalsponsors);
      if (data.sponsors > 1)
      {
        $('.quantity-box .want-this').html('PEOPLE WANT<br />THIS SOLVED');
      }
      Challenge.RefreshChallengers(data.url);
      pageTracker._trackPageview(location.pathname + '/metoocomplete');


    }
    else
    {
      $('#joinchallenge fieldset').prepend('<span class="error-message">'+data.message+'</span>');
      $('#challengewhyjoined fieldset:first').prepend('<span class="error-message">'+data.message+'</span>');
      pageTracker._trackPageview(location.pathname + '/metooerror');

    }
  }

  this.Subscribe = function(link)
  {

    var href = link.attr("href");

    pageTracker._trackPageview(href);

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(href, {}, function(data, textStatus) {
        Challenge.Subscribed(data);
      }, 'json');
      return false;
    });

    return false;

  }

  this.Subscribed = function(data)
  {
    if (data.result = 1)
    {
      $('.email_subscribe').hide().after('<em>'+data.message+'</em>');
    }
    else
    {
      alert(data.message);
    }

  }

  this.UnSubscribe = function(link)
  {
    var href = link.attr("href");

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(href, {}, function(data, textStatus) {
        Challenge.Unsubscribed(data);
      }, 'json');
      return false;
    });

    return false;
  }

  this.Unsubscribed = function(data)
  {
    if (data.result = 1)
    {
      $('.email_unsubscribe').hide().after('<em>'+data.message+'</em>');
    }
    else
    {
      alert(data.message);
    }
  }

  this.CheckCriteriaEntered = function(selectobj)
  {
    // if changed select dropdown has a value remove any related error messages

    if (selectobj.val() != '')
    {
      var ta = selectobj.attr('name').split("_");

      if (ta.length = 3)
      {
        $('.criteria_label_' + ta[1] + '_' + ta[2]).removeClass('error-message');
      }

    }

  }

  this.Vote = function(url)
  {
    var message = $('#vote-message-' + url).val();

    if (message === undefined) {
      message = '';
    }

    ChallengeUser.LoginRequiredCallback(function() {
      $.post('/challenge/' + url + '/vote', {
        'message' : message
      }, function(data, textStatus) {
        Challenge.Voted(data);
      }, 'json');
      return false;
    });
  };

  this.AddAnotherJudge = function()
  {
    $("<div class='wrapper'><label for='email-" + ++number + "'>Judge " + number + "</label><input type='text' value='E-mail address' class='input' id='email-" + number +"' name='judge_other_" + number +"'/></div>").appendTo($(".emails"));
    return false;
  };

  this.ShowSolutionReplyForm = function(link)
  {
    var id = link.attr("id");

    var ta = id.split(":");
    if (ta.length > 1)
    {
      parent_id = ta[1];
      $('#solutionreplyform_' + parent_id).slideDown('fast');
    }
    return false;


  };

  this.CancelSolutionReply = function(link)
  {
    var id = link.attr("id");

    var ta = id.split(":");
    if (ta.length > 1)
    {
      parent_id = ta[1];
      $('#solutionreplyform_' + parent_id).slideUp('fast');
    }
    return false;
  };


  this.SubmitSolutionReply = function(link)
  {
    var id = link.attr("id");

    var ta = id.split(":");
    if (ta.length > 1)
    {
      parent_id = ta[1];
      $('#solutionreply_' + parent_id).submit();
    }
    return false;
  };

  this.SolutionReplySent = function(data)
  {
    $('#solutionreplyform_' + data.solution_id).slideUp().after('<div class="success-message">' + data.message + '</div>');
  };

  this.AttachSolutionReplyForm = function(form)
  {
    var options = {
      target:        '#output2',   // target element(s) to be updated with server response
      success: function(data) {
        if (data.result == 1)
        {
          Challenge.SolutionReplySent(data);
        }
        else
        {
          // todo - show error message
          alert(data.message);
        }
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: true,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };

  this.GiftUpdated = function(data)
  {
    if (data.result == 1)
    {
      Challenge.RefreshPrize(data.url);
      Challenge.RefreshChallengers(data.url);
      $('.change-pledge').slideUp();
      $('#update-pledge').hide();
      $('#current-gift').html(data.gift);
    }
    else
    {
      $('.change-pledge').after('<span class="error-message">' + data.message + '</span>');
    }
  };

  this.UpdateGift = function(url)
  {
    // get the new gift

    var gift = $('#change-gift').val();

    $('.error-message').remove();

    $.post(url, {
      'gift' : gift
    }, function(data, textStatus) {
      Challenge.GiftUpdated(data);
    }, 'json');
  };

  this.UpdatePrize = function(url)
  {

    $('.error-message').remove();

    var amount = $('#change-amount').val();

    CPGlobal.ShowWait();

    $.post(url, {
      'amount' : amount
    }, function(data, textStatus) {
      Challenge.PrizeUpdated(data);
    }, 'json');
  };

  this.PrizeUpdated = function(data)
  {
    if (data.result == 1)
    {
      Challenge.RefreshPrize(data.url);
      Challenge.RefreshChallengers(data.url);
      $('.change-pledge').slideUp();
      $('#update-pledge').hide();
      $('#current-pledge').html(data.total);
    }
    else
    {
      $('.change-pledge').after('<span class="error-message">' + data.message + '</span>');
    }
    CPGlobal.HideWait();
  };


  this.SetupLeaveLinks = function()
  {
    $('.leave_challenge').each(function() {
      $(this).click(function () {
        Challenge.LeaveFromList($(this).attr('href'));
        return false;
      });
    });
  };

  this.LeaveFromList = function(url)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $.post(url, {}, function(data, textStatus) {
        Challenge.LeftFromList(data);
      }, 'json');
      return false;
    });
  };

  this.LeftFromList = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
      return;
    }
    $('.leave_challenge_' + data.challenge_id).after('<span class="i-posted">' + data.message + '</span>');
    $('.leave_challenge_' + data.challenge_id).hide();

  };

  this.SaveDecisionDraft = function(challenge_url)
  {
    var ref = "/challenge/" +challenge_url+"/save-decision-draft";

    // scroll through each selected decision
    var decisions = '{';

    $('input:radio').each(function () {
      if ($(this).is(":checked")) {
        decisions += '"' + $(this).attr('name') +  '" : "' + $(this).val() + '",';
      }
    });

    $('.solutiondecisiontext').each(function () {
      decisions += '"' + $(this).attr('id') +  '" : "' + $(this).val() + '",';
    });

    decisions += '}';

    var d = eval( "(" + decisions + ")" );

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(ref, d, function(data, textStatus) {
        Challenge.DecisionsDraftsSaved(data);
      }, 'json');
      return false;
    });

  };

  this.SaveCriteriaDecisionDraft = function(challenge_url)
  {

    $('.confirm-solutions .loading').show();

    var ref = "/challenge/" +challenge_url+"/save-criteria-decision-draft";

    $('.criteria_label').removeClass('error-message');
    $('.success-message').html('');

    // scroll through each selected decision

    var size = $('.criteria').size();
    var rsize = $('.recuse').size();

    var decisions = '{';

    $('.criteria').each(function (idx) {
      decisions += '"' + $(this).attr('name') +  '" : "' + $(this).val() + '"';
      if (idx < (size - 1) || rsize > 0) { // at last item
        decisions += ",";
      }
    });

    $('.recuse').each(function (idx) {
      decisions += '"' + $(this).attr('name') +  '" : "' + ($(this).is(":checked") ? 1 : 0) + '"';
      if (idx < (rsize - 1)) { // at last item
        decisions += ",";
      }
    });


    decisions += '}';

    var d = eval( "(" + decisions + ")" );

    $('.confirm-solutions .loading').hide();

    ChallengeUser.LoginRequiredCallback(function() {
      $('.confirm-solutions .loading').show();
      $.post(ref, d, function(data, textStatus) {
        $('.confirm-solutions .loading').hide();
        Challenge.DecisionsDraftsSaved(data);
      }, 'json');
      return false;
    });

  };

  this.DecisionsDraftsSaved = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
    }
    else
    {
      // reload the page

      $('.success-message').html(data.message);

    //$('.confirm_decision_confirm').hide();

    //$("#confirm_decision_confirm_message").slideUp();

    }

  };


  this.ConfirmDecision = function(challenge_url)
  {
    $('.success_message').remove();

    var ref = "/challenge/" +challenge_url+"/confirm-decision";

    var agree=confirm('Please click "OK" to reconfirm.');

    if (!agree)
    {
      return;
    }

    // scroll through each selected decision
    var decisions = '{';

    $('input:radio').each(function () {

      if ($(this).is(":checked")) {
        decisions += '"' + $(this).attr('name') +  '" : "' + $(this).val() + '",';
      }
    });

    $('.solutiondecisiontext').each(function () {
      decisions += '"' + $(this).attr('id') +  '" : "' + $(this).val() + '",';
    });

    decisions += '}';

    var d = eval( "(" + decisions + ")" );

    $('.confirm-solutions .loading').hide();

    ChallengeUser.LoginRequiredCallback(function() {
      $('.confirm-solutions .loading').show();
      $.post(ref, d, function(data, textStatus) {
        $('.confirm-solutions .loading').hide();
        Challenge.ConfirmedDecision(data);
      }, 'json');
      return false;
    });

  };

  this.ConfirmCriteriaDecision = function(challenge_url)
  {


    var ref = "/challenge/" +challenge_url+"/confirm-criteria-decision";


    $('.criteria_label').removeClass('error-message');

    $('.success-message').html('');

    var agree=confirm('Please click "OK" to reconfirm.');

    if (!agree)
    {
      return;
    }

    $('.confirm-solutions .loading').show();


    // scroll through each selected decision

    var size = $('.criteria').size();
    var rsize = $('.recuse').size();

    var decisions = '{';

    $('.criteria').each(function (idx) {
      decisions += '"' + $(this).attr('name') +  '" : "' + $(this).val() + '"';
      if (idx < (size - 1) || rsize > 0) { // at last item
        decisions += ",";
      }
    });


    $('.recuse').each(function (idx) {
      decisions += '"' + $(this).attr('name') +  '" : "' + ($(this).is(":checked") ? 1 : 0) + '"';
      if (idx < (rsize - 1)) { // at last item
        decisions += ",";
      }
    });

    decisions += '}';
    var d = eval( '(' + decisions + ')' );

    $('.confirm-solutions .loading').hide();

    ChallengeUser.LoginRequiredCallback(function() {
      $('.confirm-solutions .loading').show();
      $.post(ref, d, function(data, textStatus) {
        Challenge.ConfirmedCriteriaDecision(data);
      }, 'json');
      return false;
    });

  };

  this.ConfirmedCriteriaDecision = function(data)
  {
    $('.confirm-solutions .loading').hide();

    if (data.result == "0")
    {
      alert(data.message);

      // highlight all the criteria that were not selected

      for (var i = 0; i < data.missingdecisions.length; i++)
      {
        $('.criteria_label_' + data.missingdecisions[i][0] + '_' +  data.missingdecisions[i][1]).addClass('error-message');
      }

      $('.success-message').html('');

    }
    else
    {
      // reload the page

      $('.success-message').html(data.message);

      $('.btn-save-criteria-draft').hide();

      $('.btn-confirm-criteria-decision').hide();

    //$('.confirm_decision_confirm').hide();

    //$("#confirm_decision_confirm_message").slideUp();

    }

  };

  this.ConfirmDecisionConfirm = function(link)
  {
    $("#confirm_decision_confirm_message").slideDown();
    return false;
  };

  this.ConfirmDecisionCancel = function(link)
  {
    $("#confirm_decision_confirm_message").slideUp();
    return false;
  };

  this.ConfirmedDecision = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);

      if (data.backtodetail !== undefined && data.backtodetail == 1)
      {
        window.location.href = '/challenge/' + data.url;
      }

    }
    else
    {
      // reload the page

      window.location.reload();
      return;
      if (data.reload == 1)
      {
        window.location.reload();
      }
      else
      {
        $('.confirm_decision_confirm').before('<div class="success-message">' + data.message + '</div>');

        $('.confirm_decision_confirm').hide();

        $("#confirm_decision_confirm_message").slideUp();
      }

    }

  };

  this.PendingJudgeAccept = function(challenge_url, judge_pending_id)
  {
    var ref = "/challenge/" +challenge_url+"/accept-judge";

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(ref, {
        "j" : judge_pending_id
      }, function(data, textStatus) {
        Challenge.PendingJudgedConfirmation(data);
      }, 'json');
      return false;
    });

  };

  this.PendingJudgeDecline = function(challenge_url, judge_pending_id)
  {
    var ref = "/challenge/" +challenge_url+"/decline-judge";

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(ref, {
        "j" : judge_pending_id
      }, function(data, textStatus) {
        Challenge.PendingJudgedConfirmation(data);
      }, 'json');
      return false;
    });

  };

  this.PendingJudgedConfirmation = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
    }
    else
    {
      $('.pending-judge-decision').html('<div class="judge-instructions">' + data.message + '</div>');
    }
  };

  this.OtherJudgeConfirmDecision = function(challenge_url)
  {
    var ref = "/challenge/" +challenge_url+"/other-judge-confirm-decision";

    ChallengeUser.LoginRequiredCallback(function() {
      var agree=confirm('Please click "OK" to reconfirm.');
      if (agree) { } else {
        return false
      };
      $.post(ref, {}, function(data, textStatus) {
        Challenge.OtherJudgeConfirmedDecision(data);
      }, 'json');
      return false;
    });

  };

  this.OtherJudgeConfirmDecisionConfirm = function(link)
  {
    $("#other_judge_confirm_decision_confirm_message").slideDown();
    return false;
  };

  this.OtherJudgeConfirmDecisionCancel = function(link)
  {
    $("#other_judge_confirm_decision_confirm_message").slideUp();
    return false;
  };

  this.OtherJudgeConfirmedDecision = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
    }
    else
    {

      $('.success-message').html(data.message);

    // $('.other_judge_confirm_decision_confirm').before('<div class="success">' + data.message + '</div>');

    // $('.other_judge_confirm_decision_confirm').hide();

    // $("#other_judge_confirm_decision_confirm_message").slideUp();

    }

  };

  this.AcceptSolution = function(challenge_url, link)
  {
    var id = link.attr("id");
    id = id.split(":");

    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    var ref = "/challenge/" +challenge_url+"/solution-pending-accepted?id="+ solution_id;

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(ref, {}, function(data, textStatus) {
        Challenge.AcceptedSolution(data);
      }, 'json');
      return false;
    });

  };

  this.AcceptSolutionConfirm = function(link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    $("#accept_solution_confirm_message_" + solution_id).removeClass('hide');
    return false;
  };

  this.AcceptSolutionCancel = function(link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    $("#accept_solution_confirm_message_" + solution_id).addClass('hide');
    return false;
  };

  this.AcceptedSolution = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
    }
    else
    {
      // highlight the solution green

      $('#marked_status_' + data.solution_id).html(data.message);
      $('.notify_decision').show();
      // remove the link

      // $('#marked_status_' + data.solution_id).hide();

      $('#accept_solution_link:' + data.solution_id).hide();

      $('#solution_decision_' + data.solution_id).hide();

    }

  };


  this.HonorSolution = function(challenge_url, link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    var ref = "/challenge/" +challenge_url+"/solution-pending-honored?id="+ solution_id;

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(ref, {}, function(data, textStatus) {
        Challenge.HonoredSolution(data);
      }, 'json');
      return false;
    });

  };

  this.HonorSolutionConfirm = function(link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    $("#marked_status_" + solution_id).removeClass('hide');
    return false;
  };

  this.HonorSolutionCancel = function(link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    $("#marked_status_" + solution_id).addClass('hide');
    return false;
  };

  var suggest_timeout = null;

  this.ChallengeSuggest = function()
  {
    $("#title").keyup(function()
    {
      var search;
      search = $("#title").val();

      if (search.length > 6)
      {

        if (suggest_timeout) {
          clearTimeout(suggest_timeout);
        }
        suggest_timeout = setTimeout(function(){

          $.get('/challenge/suggest', {
            "q" : search
          }, function(data){
            $('.suggestions').remove();
            $('#title').after(data);
            $('#challenge_suggestions').slideDown();
            $(".hide_suggestions").click(function() {
              $('.suggestions').slideUp();
              $("#title").unbind("keyup");
              return false;
            });

          });

        }, 400);



      }
      else
      {
    // Empty suggestion list

    }
    });
  };



  this.HonoredSolution = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
    }
    else
    {
      // highlight the solution green

      $('#marked_status_' + data.solution_id).html(data.message);

      $('.notify_decision').show();

    // remove the link

    //$('#honor_solution_confirm_message_' + data.solution_id).hide();

    //$('#honor_solution_link:' + data.solution_id).hide();

    //$('#solution_decision_' + data.solution_id).hide();

    }

  };


  this.DeclineSolution = function(challenge_url, link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    var ref = "/challenge/" +challenge_url+"/solution-pending-declined?id="+ solution_id;

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(ref, {}, function(data, textStatus) {
        Challenge.DeclinedSolution(data);
      }, 'json');
      return false;
    });

  };

  this.DeclineSolutionConfirm = function(link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    $("#decline_solution_confirm_message_" + solution_id).removeClass('hide');
    return false;
  };

  this.DeclineSolutionCancel = function(link)
  {
    var id = link.attr("id");

    id = id.split(":");
    if (id.length > 1)
    {
      solution_id = id[1];
    }
    else
    {
      return false;
    }

    $("#decline_solution_confirm_message_" + solution_id).addClass('hide');
    return false;
  };

  this.DeclinedSolution = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
    }
    else
    {
      // highlight the solution green

      $('#marked_status_' + data.solution_id).html(data.message);
      $('.notify_decision').show();
    // remove the link

    //$('#decline_solution_confirm_message_' + data.solution_id).hide();

    //$('#decline_solution_link:' + data.solution_id).hide();

    //$('#solution_decision_' + data.solution_id).hide();

    }

  };

  this.VoteFeature = function(link)
  {

    var ch_ref = link.attr("href");

    var challenge_id = 0;
    var ta = ch_ref.split(":");
    if (ta.length > 1)
    {
      challenge_id = ta[1];
    }

    if(challenge_id == "0")
    {
      // @todo alert here
      alert('No challenge found');
      return;
    }

    ChallengeUser.LoginRequiredCallback(function() {
      $.post('/challenge/' + challenge_id + '/vote', {}, function(data, textStatus) {
        Challenge.VotedFeature(data);
      }, 'json');
      return false;
    });

  };

  this.Sponsor = function(source)
  {

    var ch_ref = source.attr("id");

    var challenge_id = 0;
    var ta = ch_ref.split(":");
    if (ta.length > 1)
    {
      challenge_id = ta[1];
    }

    var message = $('#sponsor-message').val();

    if (message === undefined) {
      message = '';
    }

    // get the information out of the form
    var form = source.parents('form:first');
    var amount = $("input[name='amount']",form).val();
    var card = $("select[name='card']",form).val();

    if (card == "0") { // redirect them to the sponsor page with the amount pre-populated
      window.location.href = form.attr("action") + '?amount=' + amount;
    }

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(form.attr("action"), {
        "amount": amount,
        "challenge_id": challenge_id,
        'message' : message,
        'card' : card
      }, function(data, textStatus) {
        Challenge.Sponsored(data);
      }, 'json');
      return false;
    });

  };

  this.SponsorFeature = function(source)
  {

    var ch_ref = source.attr("id");

    var challenge_id = 0;
    var ta = ch_ref.split(":");
    if (ta.length > 1)
    {
      challenge_id = ta[1];
    }

    var message = $('#sponsor-message-' + url).val();

    if (message === undefined) {
      message = '';
    }

    // get the information out of the form
    var form = source.parents('form:first');
    var amount = $("input[name='amount']",form).val();
    var card = $("select[name='card']",form).val();

    if (card == "0") { // redirect them to the sponsor page with the amount pre-populated
      window.location.href = form.attr("action") + '?amount=' + amount;
    }

    ChallengeUser.LoginRequiredCallback(function() {
      $.post(form.attr("action"), {
        "amount": amount,
        "challenge_id": challenge_id,
        'message' : message
      }, function(data, textStatus) {
        Challenge.SponsoredFeature(data);
      }, 'json');
      return false;
    });

  };

  this.RefreshMessages = function(url)
  {
    $.get('/challenge/' + url + '/messages', {},
      function(data){
        $("#recent_messages").html(data);
      });
  };

  this.ImpressFeature = function(link)
  {

    var ch_ref = link.attr("href");

    var challenge_id = 0;
    var ta = ch_ref.split(":");
    if (ta.length > 1)
    {
      challenge_id = ta[1];
    }

    if(challenge_id == "0")
    {
      // @todo alert here
      alert('No challenge found');
      return;
    }
    ChallengeUser.LoginRequiredCallback(function() {
      $.post('/challenge/' + challenge_id + '/watch', {}, function(data, textStatus) {
        Challenge.ImpressedFeature(data);
      }, 'json');
      return false;
    });

  };

  this.Working = function(url)
  {


    ChallengeUser.LoginRequiredCallback(function() {
      $.post('/challenge/' + url + '/working', {}, function(data, textStatus) {
        Challenge.Worked(data);
      }, 'json');
      return false;
    });
  };


  this.Watch = function(url)
  {
    var message = $('#impress-message-' + url).val();

    if (message === undefined) {
      message = '';
    }

    ChallengeUser.LoginRequiredCallback(function() {
      $.post('/challenge/' + url + '/watch', {
        'message' : message
      }, function(data, textStatus) {
        Challenge.Watching(data);
      }, 'json');
      return false;
    });
  };

  this.SponsoredFeature = function(data)
  {
    if (data.result == "0") {
      alert(data.message);
      return;
    }

    $("#hover-challenge-sponsor_" + data.challenge_id).html(data.featuremessage);
    $("#feature-sponsor-form_" + data.challenge_id).html(data.message).addClass('success');
  };

  this.Sponsored = function(data)
  {
    if (data.result == "0") {
      alert(data.message);
      return;
    }

    if (data.result == 1)
    {
      Challenge.RefreshCurrencyWho(data);
      return;
    }
    $("#feature-sponsor-form_" + data.challenge_id).html(data.message).addClass('success');
    $(".total-sponsored_" + data.challenge_id).html(data.prize);
    Challenge.RefreshMessages(data.url);
    $('#currency_notice').hide('slow');
  };

  this.ImpressedFeature = function(data)
  {
    if (data.result == 1)
    {
      $('#hover-challenge-impress_' + data.challenge_id).html(data.featuremessage);
      Challenge.RefreshMessages(data.url);
    }
    if (data.result == "0") {
      alert(data.message);
    }
    $('#currency_notice').hide('slow');
  };

  this.VotedFeature = function(data)
  {
    if (data.result == 1) {
      $('#hover-challenge-help_' + data.challenge_id).html(data.message);
      if (data.watching == 1)
      {
        $('#hover-challenge-impress_' + data.challenge_id).html(data.featureimpressedmessage);
      }
    }
    if (data.result == "0")
    {
      alert(data.message);
    }


  };

  this.Voted = function(data)
  {

    if (data.result == 1)
    {
      Challenge.RefreshCurrencyWho(data);
      return;
    }
    $('#votecount').html(data.votes);
    $('#help-metric').html(data.message);
    $('#votechallengelink').hide().after('<div class="' + data.result + '">' + data.confirmation + '</div>');
    $('#vote-message-' + data.url).hide();
    $('#vote-label-' + data.url).hide();
    $('#currency_notice').hide('slow');
    $('#help-me-link').hide();
    Challenge.RefreshMessages(data.url);
  };

  this.SolutionExists = function(data)
  {
    // hide the comment types

    // select the solution exists comment type

    // update the question label

    ChallengeUser.LoginRequiredCallback(function() {

      //$("#btn-found-solution").parent().toggleClass("active");
      //if($("#btn-found-solution").parent().hasClass("active"))
      //{
      $(".found-solution").show();
    //}
    //else
    //{
    //	$(".solution-existing-box").slideUp();
    //}

    } );

    return false;

  };

  this.SolutionQuestionSent = function(data)
  {

    $('.success').slideUp();

    $('#solution-question').slideUp().after('<div class="success">' + data.message + '<a href="#" onclick="$(\'.success\').hide(); return false;">[x]</a></div>');

    // refresh the comments section

    Challenge.RefreshSolutionMessages(data.url);

    // increase the number of comments

    $("#question_and_suggestions_count").html($("#question_and_suggestions_count").html() + 1);


  };

  this.SolverSuggestion = function(data)
  {
    // hide the comment types

    // select the solution exists comment type

    // update the question label

    ChallengeUser.LoginRequiredCallback(function() {

      //$('#solution-question').show();

      //$('#fieldset-commenttype').hide();

      $('#challengecomment').clearForm();

      $("#challengecomment input[@name='type']").val('4');

      $("#challengecomment label[@for='question']").html('Please enter your suggestion. If you are submitting a solution to this challenge, please click the Solve button above. ');

      $("#make-suggestion").parent().trigger("click");

      return false;

    });

    return false;
  };

  this.SolverQuestion = function(data)
  {
    // hide the comment types

    // select the solution exists comment type

    // update the question label

    ChallengeUser.LoginRequiredCallback(function() {

      //$('#solution-question').show();

      //$('#fieldset-commenttype').hide();

      $('#challengecomment').clearForm();

      $("#challengecomment input[@name='type']").val('1');

      $("#challengecomment label[@for='question']").html('Your question to the challenger');

      $("#ask-question").parent().trigger("click");

      return false;

    });

    return false;

  };

  this.SolverQuestionSent = function(data)
  {
    // $('#solution-question').hide().after('<div class="success">' + data.message + '<a href="#" onclick="$(\'.success\').hide(); return false;">[x]</a></div>');

    $("#btn-cancel-2").trigger('click');

    // refresh the comments section

    Challenge.RefreshSolutionMessages(data.url);

    // increase the number of comments

    $("#question_and_suggestions_count").html(data.count);


  };


  this.ExistingSolutionSent = function(data)
  {
    $(".found-solution").hide().after('<div class="result-message">' + data.message + '</div>');

  // refresh the existing solutions

  };

  this.GetDetailGifts = function(url)
  {
    CPGlobal.ShowWait('#detail-gifts .loading');
    $('#detail-gifts ul').remove();
    $.get('/challenge/' + url + '/get-detail-gifts', {},
      function(data){

        $('#detail-gifts').prepend(data);
        CPGlobal.HideWait();

      });


  };


  this.CommentSent = function(data)
  {
    $('#challengecomment').clearFields();

    // refresh the comments section

    Challenge.RefreshSolutionMessages(data.url);

    // increase the number of comments

    $("#question_and_suggestions_count").html(data.count);

    $("#btn-cancel-2").trigger('click');
  };


  this.RefreshSolutionMessages = function(url)
  {
    $.get('/challenge/' + url + '/messages', {
      "solutions": "1"
    },
    function(data){

      $("#recent_comments").html(data);

      $(".commentreply").click(function() {
        return Comment.ShowReplyForm($(this));
      });
      $(".solutioncommentreply").each(function () {
        Challenge.AttachSolutionCommentReplyForm($(this));
      });


      $(".reply-submit").click(function () {
        return Comment.SubmitSolverCommentReply($(this));
      });

      $(".reply-cancel").click(function () {
        return Comment.CancelSolverCommentReply($(this));
      });

    });

  };

  this.RefreshPrize = function(url)
  {
    $.get("/challenge/" + url + "/get-detail-prize", function(data) {
      $('.prize-stakes').html(data);

      $("#gifts").unbind('click');

      $("#gifts").click(function () {
        Challenge.GetDetailGifts(url);
        initTogglers();
      });

    //$(".detail_prize_sentence").hide();
    //$(".detail_prize_sentence").html(data);
    //$(".detail_prize_sentence").slideDown('slow');
    //$(".gift_prize").click(function () { $('#display_gift_list').html($('#gift_list').html()).slideDown('slow')});
    });
  };

  this.RefreshThankYous = function(url)
  {
    $.get("/challenge/" + url + "/get-thank-yous", function(data) {
      $('.thank-you-wrapper').html(data);
    });
  };

  this.RefreshJoinForm = function(url, joined, twittersent)
  {
    $.get("/challenge/" + url + "/get-detail-form", function(data) {
      // $('.join-form').hide('slow');
      $('.join-form').html(data);

      if(joined !== undefined && joined == 1) {
        $('.button-holder').slideUp();
      }
      if(twittersent !== undefined && twittersent == 1) {
        $('.join_twitter_update_confirm').show();
      }

      // $('.join-form').slideDown('slow');
      Challenge.SetupJoinForm(url);
      //$(".detail_prize_sentence").hide();
      //$(".detail_prize_sentence").html(data);
      //$(".detail_prize_sentence").slideDown('slow');
      //$(".gift_prize").click(function () { $('#display_gift_list').html($('#gift_list').html()).slideDown('slow')});
      $("#show_twitter_update").click(function () {
        if ($(this).is(":checked")) {
          Challenge.ShowWhyJoinedTwitter();
        } else {
          $("#join_twitter_update").slideUp();
        }
      });

    });
  };

  this.RefreshChallengers = function(url, wish)
  {
    $.get("/challenge/" + url + "/get-detail-challengers?w=" + wish, function(data) {
      $(".detail_currency_who").html(data);
      $(".sponsor-challenge").click(function () {
        Challenge.Sponsor($(this));
      });
    /*
                  $("#join_challengers").click(function() { $(this).addClass('hide'); $("#join_challenge_form").slideDown('slow'); return false; });;
                  $("#cancel_join_challengers").click(function() { $("#join_challengers").removeClass('hide'); $("#join_challenge_form").hide(); return false; });
                  $("#pay").change( function() { Challenge.UpdatePostSponsor($(this).val()); });
                  $(".detail_challengers_header").click(function () { $('#who').toggle(); $('#who_map').toggle();});
                  $("#status_update_form").each(function () { Challenge.AttachTwitterStatusUpdateForm($(this)); });
                  $("#cancel_update_pledge").click(function() { $('#update_pledge_form').slideUp(); return false; });
                  $("#update_pledge").click(function() { $('#update_pledge_form').slideDown(); return false; });
                  $("#update_pledge_form").each(function () { Challenge.AttachJoinForm($(this)); });
                  $("#update_gift_form").each(function () { Challenge.AttachJoinForm($(this)); });
                  $("#cancel_update_gift").click(function() { $('.change-gift').slideUp(); return false; });
                  $("#update_gift").click(function() { $('.change-gift').slideDown(); return false; });
                  $("#show_twitter_update").click(function () { if ($(this).is(":checked")) { Challenge.ShowWhyJoinedTwitter(); } else { $("#join_twitter_update").slideUp(); } });
     */
    });
  };

  this.ShowWhyJoinedTwitter = function()
  {
    var message = $('#message').val();
    var status = $('#status').val();
    var title = $('#title').val();
    var short_url = $('#short_url').val();
    var prize = $('#prize').val();

    var amount = $('#amount').val();

    if (status === '') // @todo - better check
    {
      if (message == '')
      {
        if (amount == '')
        {
          message = 'Check out this ' + prize  + 'challenge on ChallengePost - ' + title;
        }
        else
        {
          message = 'I pledged ' + amount  + ' to this challenge on ChallengePost - ' + title;
        }
      }
      $('#status').val(message + ' ' + short_url);
    }

    $(".twitter-area").slideDown();
  };

  this.UpdatePostSponsor = function(val)
  {
    $('.post_reward').hide();

    $('#currency').addClass('hide');

    $('.payment_row').hide();

    $("label[for='money']").hide();

    $('#money').hide();

    $('#gift').hide();

    if (val == 1)
    {
      $('#money').show();
      $('.payment_row').show();
      $("label[for='money']").show();

    }
    else if (val == 2)
    {
      $('#gift').show();
    }

  };

  this.WhyJoined = function(data)
  {



    $('.form-post').hide();

    $('.why-joined-message p').html(data.message);

    if(data.updatefacebookfeed !== undefined && data.updatefacebookfeed == 1)
    {
      Challenge.PublishFacebookLink(location.href, document.title);
    }

    if (data.updatetwitterfeed != undefined && data.updatetwitterfeed == 1)
    {
      Challenge.PublishTwitterLink($('#status').val());
    }

    if (data.updatetwitterfeed != undefined && data.updatetwitterfeed == 2)
    {
      var updatetwitterfeed = 1;
    }
    else
    {
      var updatetwitterfeed = 0;
    }

    // Challenge.RefreshPrize(data.url);

    Challenge.RefreshChallengers(data.url);

    // Challenge.RefreshJoinForm(data.url);

    // $('.button-holder').slideUp();

    return;

    if (data.joined === undefined)
    {
      Challenge.RefreshJoinForm(data.url, 0, updatetwitterfeed);
    }
    else
    {
      Challenge.RefreshJoinForm(data.url, 1, updatetwitterfeed);
    }


    //       	$('.button-holder').css("margin-left","-1000px");

    if (data.updatethankyous !== undefined && data.updatethankyous == 1)
    {
      Challenge.RefreshThankYous(data.url);
    }


  }

  this.Joined = function(data)
  {

    if(data.updatefacebookfeed !== undefined && data.updatefacebookfeed == 1)
    {
      Challenge.PublishFacebookLink(location.href, document.title);
    }

    if (data.updatetwitterfeed != undefined && data.updatetwitterfeed == 1)
    {
      Challenge.PublishTwitterLink($('#status').val());
    }

    if (data.updatetwitterfeed != undefined && data.updatetwitterfeed == 2)
    {
      var updatetwitterfeed = 1;
    }
    else
    {
      var updatetwitterfeed = 0;
    }

    Challenge.RefreshPrize(data.url);

    Challenge.RefreshChallengers(data.url);

    // Challenge.RefreshJoinForm(data.url);

    // $('.button-holder').slideUp();



    if (data.joined === undefined)
    {
      Challenge.RefreshJoinForm(data.url, 0, updatetwitterfeed);
    }
    else
    {
      Challenge.RefreshJoinForm(data.url, 1, updatetwitterfeed);
    }


    //       	$('.button-holder').css("margin-left","-1000px");

    if (data.updatethankyous !== undefined && data.updatethankyous == 1)
    {
      Challenge.RefreshThankYous(data.url);
    }




  // $(".form-join-challenge").slideUp('slow');

  };

  this.TwitterStatusUpdated = function(data)
  {
    $('#twitter_update_form').html('<div class="success">' + data.message + '</div>');
  };

  this.AttachTwitterStatusUpdateForm = function(form)
  {
    var options = {
      target:        '#output2',   // target element(s) to be updated with server response
      success: function(data) {
        if (data.result == 1)
        {
          Challenge.TwitterStatusUpdated(data);
        }
        else
        {
          // todo - show error message
          alert('something is wrong');
        }
        return false;
      },
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      timeout:   3000
    };

    form.submit(function() {
      $(this).ajaxSubmit(options);
      return false;
    });
  };

  this.PromoteChallengeEmailSent = function(data)
  {

    $('#promotechallengeemail .form-email').append("<span class='success-message'>"+data.message+"</span>");
  };

  this.PromoteChallengeEmailSetup = function(form)
  {
    var options = {
      target: '#output2',   // target element(s) to be updated with server response

      success: function(data) {
        if (data.result == 1)
        {
          Challenge.PromoteChallengeEmailSent(data);
        }
        else {
          // todo - show error message
          alert(data.message);
        }
        return false;
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit
      beforeSubmit: function () {
        $('.success-message').hide();
        pageTracker._trackPageview(form.attr('action'));

      },
      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };

  this.InviteWishesSent = function(data)
  {
    $('.success-message').remove();
    $('#invitewishes').after("<div class='success-message'>"+data.message+"</div>");
  };

  this.InviteWishesSetup = function(form)
  {
    var options = {
      target: '#output2',   // target element(s) to be updated with server response

      success: function(data) {
        if (data.result == 1)
        {
          Challenge.InviteWishesSent(data);
        }
        else {
          // todo - show error message
          alert(data.message);
        }
        return false;
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };


  this.AttachWhyJoinForm = function(form)
  {


    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {

        $('.error-message').remove();

        if (data.result == 1)
        {
          Challenge.WhyJoined(data);
        }
        else
        {
          $('.note-error-message p').html(data.message);
        }

        CPGlobal.HideWait();

        return false;
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      beforeSubmit: function () {
        $('.note-error-message p').html('');
        $('.note-error p').html('');
        CPGlobal.ShowWait('#challengewhyjoined .loading');
        pageTracker._trackPageview(form.attr('action'));
      },

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };


  this.AddPledge = function(url)
  {

    $('.note-error p').html('');

    var amount = $('#input-add-to-pledge').val();

    $.post("/challenge/" + url + "/update-sponsor", {
      "amount": amount
    }, function(data, textStatus) {
      Challenge.AddedPledge(data);
    }, 'json');

    return false;

  }

  this.AddedPledge = function(data)
  {

    if (data.result == -1) // redirect them to the sponsor page
    {
      window.location.href = '/challenge/' + data.url + '/sponsor?amount=' + data.amount;
    }
    else if (data.result == 1)
    {
      $('.quantity-box .money').html(data.prize);
      $('.my-amount').html(data.amount);
      $('#input-add-to-pledge').val('$ ');
      Challenge.RefreshChallengers(data.url);
    }
    else
    {
      $('.note-error p').html(data.message);
    }
  }

  this.AttachJoinForm = function(form)
  {

    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {

        $('.error-message').remove();
        $('#gift').removeClass('error');


        if (data.result == 1)
        {
          Challenge.Joined(data);
        }
        else if (data.result == -1) // redirect them to the sponsor page
        {
          // $("#join_challenge_form").slideUp();
          $("#secure_redirect").slideDown();
          window.location.href = '/challenge/' + data.url + '/sponsor?amount=' + data.amount;
        }
        else if (data.result == -2) // problem with the gift
        {
          $('#gift').addClass('error');
          $('#joinchallenge fieldset').prepend('<span class="error-message">'+data.message+'</span>');
        }
        else {
          $('#joinchallenge fieldset').prepend('<span class="error-message">'+data.message+'</span>');
          $('#challengewhyjoined fieldset:first').prepend('<span class="error-message">'+data.message+'</span>');

        }

        CPGlobal.HideWait();

        return false;
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      beforeSubmit: function () {
        CPGlobal.ShowWait();
        pageTracker._trackPageview(form.attr('action'));
      },

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };


  this.AttachCommentForm = function(form)
  {

    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {
        if (data.result == 1)
        {
          Challenge.CommentSent(data);
        }
        else
        {
          // todo - show error message
          $('.error-message').remove();

          CPGlobal.AttachErrorMessages(data.errors);
        }
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: true,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };

  this.AttachExistingSolutionForm = function(form)
  {

    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {
        if (data.result == 1)
        {
          Challenge.ExistingSolutionSent(data);
        }
        else
        {
          // @todo - show error message
          alert(data.message);
        }
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: true,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      beforeSubmit: function () {
        for ( i = 0; i < parent.frames.length; ++i )
        {
          if ( parent.frames[i].FCK ) {
            parent.frames[i].FCK.UpdateLinkedField();
          }
        }
        pageTracker._trackPageview(form.attr('action'));

      },



      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };

  this.ReplySent = function(data)
  {
    $('#replyform_' + data.comment_id).slideUp().after('<div class="success">' + data.message + '<a href="#" onclick="$(\'.success\').hide(); return false;">[x]</a></div>');
    Challenge.RefreshSolutionMessages(data.url);
  };

  this.AttachSolutionCommentReplyForm = function(form)
  {
    var options = {
      target:        '#output2',   // target element(s) to be updated with server response
      success: function(data) {
        if (data.result == 1)
        {
          Challenge.ReplySent(data);
        }
        else
        {
          // todo - show error message
          alert(data.message);
        }
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: true,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };

  this.PublishFacebookLink = function(url, title)
  {

    window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(url)+'&t=' + encodeURIComponent(title),'sharer','toolbar=0,status=0,width=626,height=436');

  };

  this.PublishTwitterLink = function(message)
  {
    window.open('http://twitter.com/home?status='+encodeURIComponent(message),'twittersharer','toolbar=0,status=0,width=506,height=606');
  };

  this.PublishFacebookFeed = function(template_id, challenge, link, description, message, image)
  {
    var comment_data = {
      "challenge":challenge,
      "link":link,
      "description" : description
    };

    if (image !== undefined && image !== "")
    {
      comment_data.images = [{
        "src":image,
        "href":link
      }];
    }

    FB.ensureInit(
      function(){
        result = FB.Connect.showFeedDialog(template_id, comment_data, null, null, null, FB.RequireConnect.promptConnect, null, 'Why I Joined', {
          value: message
        });
      } );
  };

  this.AttachQuestionForm = function(form)
  {

    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {
        if (data.result == 1)
        {
          Challenge.SolutionQuestionSent(data);
        }
        else
        {
          // todo - show error message
          CPGlobal.AttachErrorMessages(data.errors);
        }
      },


      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: true,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };


  this.Worked = function(data)
  {

    $('.workingcount').html(data.working);
    $('#workingchallengelink').hide().after('<div class="' + data.result + '">' + data.message + '</div>');
  };

  this.RefreshCurrencyWho = function(data)
  {
    $.get("/challenge/" + data.url + "/get-detail-currency", function(data) {
      $(".detail_currency_who").html(data);
    });
  };

  this.Watching = function(data)
  {

    if (data.result == 1)
    {
      Challenge.RefreshCurrencyWho(data);
      return;
    }

    $('#impress-metric').html(data.message);
    $('#impress-me-link').hide();
    $('#impress-tab').hide().after('<div class="' + data.result + '">' + data.confirmation + '</div>');
  };

  this.Post = function(next)
  {
    Challenge.ClearDefaultText();
    $('#next').val(next);
    ChallengeUser.LoginRequiredCallback(function() {
      $("#challengepost").submit();
    } );
    return false;
  };

  this.Join = function(form)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $('#joinchallenge').submit();
    } );
  };

  this.JoinMessage = function(form)
  {

    var message = jQuery.trim($('#message').val());

    if (message === "")
    {
      var messages = new Array();
      messages[0] =  "A message is required";
      message = CPGlobal.BuildErrorMessage(messages);
      $('#message').after(message);
      return false;
    }
    else
    {
      if ($('#update_facebook_feed').is(':checked'))
      {
        var challenge = $('#title').val();
        var link = $('#short_url').val();
        var description = $('#description').val();
        var image = $('#image').val();
        var template_id = $('#template_id').val();

        Challenge.PublishFacebookFeed(template_id, challenge, link, description, message, image);
      }
    }

    ChallengeUser.LoginRequiredCallback(function() {
      $("#challengewhyjoined").submit();
    } );
  };

  this.SetupFlagInnapropriate = function(link)
  {
    link.click(function () {

      ChallengeUser.LoginRequiredCallback(function() {
        var current_location = window.location.href;
        $.get('/notification/flag-as', {
          'url' : current_location
        },
        function(data){
          link.html('').after('Thank you. We will look into it.');
        });
      } );


      return false;
    });
  };
  this.SetupFindCurrency = function(terms)
  {
    $('#find-currency').click( function() {
      url = $('#url').val();
      terms = $('#find-challengers').val();
      $.get('/challenge/' + url + '/currency', {
        "terms" : terms,
        "auto_search" : "0"
      },
      function(data){
        $("#results").html(data);
        Problem.SetupCurrencyRequest();
      });
      return false;
    } );

    if (terms !== '')
    {
      url = $('#url').val();
      $.get('/challenge/' + url + '/currency', {
        "terms" : terms,
        "auto_search" : "1"
      },
      function(data){
        $("#results").html(data);
        Problem.SetupCurrencyRequest();
      });
    }
    return false;
  };


  this.TogglePostAddCard = function(show)
  {
    if (show == -1)
    {
      var addNewSelected = $('input[name=card]:checked').val();

      if (addNewSelected == "0")
      {
        show = 1;
      }
      else
      {
        show = 0;
      }
    }

    if (show)
    {
      $('#cc-info').show();
    }
    else
    {
      $('#cc-info').hide();
    }
  };

  this.ToggleSponsorAddCard = function(show)
  {
    if (show == -1)
    {
      var addNewSelected = $('input[name=card]:checked').val();
      if (addNewSelected == "0")
      {
        show = 1;
      }
      else
      {
        show = 0;
      }
    }

    if (show)
    {
      $('.addcard-info').parent().show();
    }
    else
    {
      $('.addcard-info').parent().hide();
    }
  };

  this.SetupEditForm = function()
  {
    if (!$('#deadline_type-1').is(":checked"))
    {
      $('.deadline-question').hide();
    }

    $('#deadline_type-1').click(function() {
      $('.deadline-question').show();
    });

    $('#deadline_type-0').click(function() {
      $('.deadline-question').hide();
    });
  };

  this.SetupJoinForm = function(url)
  {
    $("#btn-join-challenge-btn").click(function () {
      $("#joinchallenge").hide();
      pageTracker._trackPageview(location.pathname + '/joinreveal');
      $(".form-join-challenge").slideDown(200, function() {
        $("#joinchallenge").show();
      } );
    });

    $("#update_gift").click(function () {
      $(".change-gift").slideDown();
      return false;
    });

    $("#btn-join").click(function () {
      return Challenge.Join();
    });

    $("#joinchallenge #btn-reset").click(function () {
      pageTracker._trackPageview(location.pathname + '/joincancel');
      $(".form-join-challenge").slideUp();
      return false;
    });

    $("#cancel_update_gift-cancel").click(function () {
      $(".change-gift").slideUp();
      return false;
    });

    $("#joinchallenge").each(function () {
      Challenge.AttachJoinForm($(this));
    });

    $("#challengewhyjoined").each(function () {
      Challenge.AttachWhyJoinForm($(this));
    });

    $("#challengewhyjoined #btn-cancel").click(function () {
      $(".change-pledge").slideUp();
      $(".error-message").remove();
      return false;
    });

    $("#challengewhyjoined #update-pledge").click(function () {
      $(".change-pledge").slideDown();
      return false;
    });

    $(".btn-update-prize").click(function () {
      Challenge.UpdatePrize("/challenge/" + url + "/update-sponsor");
    });

    $(".btn-update-gift").click(function () {
      Challenge.UpdateGift("/challenge/" + url + "/update-gift");
    });

    $("#pay-the-solver").change( function() {
      Challenge.UpdatePostSponsor($(this).val());
    });


  };


  this.SetupPostForm = function()
  {
    // hide judge questions
    // $('.judge-question').parent().parent().hide().prev().hide();
    // $('.deadline-type-question').parent().parent().hide().prev().hide();

    if (!$('#deadline_type-1').is(":checked"))
    {
      $('.deadline-question').hide();
    }

    if ($('#judge-1').is(":checked"))
    {
      $('.judge-other').show();
    }

    $('.ip-other').parent().hide().prev().hide();

    $('#judge-1').click(function() {
      $('.judge-other').show();
      return true;
    });
    $('#judge-0').click(function() {
      $('.judge-other').hide();
      return true;
    });

    $('#intellectural_property-3').click(function() {
      $('.ip-other').parent().show().prev().show();
      return true;
    });

    $('#add-judge').click(function() {
      $('.other-judges').append('<div>Judge 2:<input type="input"/></div>');
      return false;
    });

    // hide the ip questions
    // $('.ip-question').parent().parent().hide().prev().hide();

    $('#edit-judge').click(function() {
      $('.judge-question').show();
      // $(this).parent().hide().prev().hide();
      return false;
    });

    $('#edit-deadline').click(function() {
      //$('.deadline-type-question').parent().parent().toggle().prev().show();
      // $(this).parent().hide().prev().hide();
      return false;
    });

    $('#edit-ip').click(function() {
      $('.ip-question').parent().parent().show().prev().show();
      // $(this).parent().hide().prev().hide();
      return false;

    });

    $('#deadline_type-1').click(function() {
      $('.deadline-question').show();
    });

    $('#deadline_type-0').click(function() {
      $('.deadline-question').hide();
    });

  };

  this.ShowFeatureTab = function(tablink)
  {
    tablink.click(function () {
      var tabstoshow = $(this).attr("href");
      var tab = 0;
      var ta = tabstoshow.split(":");
      if (ta.length > 1)
      {
        tab = ta[1];
        tabstoshow = ta[0];
      }


      /* if ($(tabstoshow).hasClass("feature-tab-displayed")) {
        		   // get the currently selected tab. if same tab we hide
        		   var selected = $(tabstoshow).data('selected.tabs');
        		   if (selected == tab)
        		   {
        		       $(tabstoshow).hide("fast").removeClass("feature-tab-displayed");
        		       return false;
        		   }
        	   } */
      // $(".feature-tab-displayed").hide("fast");
      $(tabstoshow).toggle("normal"); // .addClass("feature-tab-displayed");
      // $(tabstoshow).tabs('select', tab);
      return false;
    });

  };


  this.SetupSubCategorySelect = function()
  {
    $("#subcategory_select").change(function()
    {
      var parent_id = String($("#subcategory_select").val());

      if (parent_id !== undefined)
      {
        var c = parent_id.split(",");

        if (c.length > 1)
        {
          $(this).attr('selectedIndex', -1);
          alert('Only one sub-category is allowed.');
          return;
        }
      }

    });

  };


  this.SetupCategorySelect = function()
  {
    $("#category_select").change(function()
    {
      var parent_id = String($("#category_select").val());

      if (parent_id !== undefined)
      {
        var c = parent_id.split(",");

        if (c.length > 1)
        {
          $(this).attr('selectedIndex', -1);
          alert('Only one category is allowed.');
          return;
        }
      }

      $("#subcategory_select").empty();

      // get all subcategories for the selected parent

      var options = '';

      $('.parent_category_' + parent_id).each(function(srcc) {

        options += '<option value="' + $(this).attr('id') + '">' + $(this).val() + '</option>';
      });

      if (options.length > 0)
      {
        $("#subcategory_select").html(options);
        $("#subcategory_select").show();
      }
      else
      {
        $("#subcategory_select").hide();
      }

      Challenge.SetupSubCategorySelect();

    });

  };

  this.ClearDefaultText = function()
  {
    $(".defaultText").each(function(srcc)
    {
      if ($(this).val() == $(this)[0].title)
      {
        $(this).removeClass("defaultTextActive");
        $(this).val("");
      }
    });
  };

  this.SetupDefaultText = function()
  {

    $(".defaultText").focus(function(srcc)
    {
      if ($(this).val() == $(this)[0].title)
      {
        $(this).removeClass("defaultTextActive");
        $(this).val("");
      }
    });

    $(".defaultText").blur(function()
    {
      if ($(this).val() === "")
      {
        $(this).addClass("defaultTextActive");
        $(this).val($(this)[0].title);
      }
    });

    $(".defaultText").blur();

    $(".addlowerhint").each(function()
    {
      $(this).after('<div class="formhint">' + $(this).attr('title') + '</div>');
    });


  };

  this.ShowFeatureAction = function(hoverarea)
  {
    hoverarea.hover(
      function () {
        var position = $(this).position();
        var top = $(this).offset().top ;
        var left = $(this).offset().left;
        $("#action_menu").css('top',top - 25);
        $("#action_menu").css('left',left);
        $("#action_menu").show().css('background-color',  '#CCFFFF');
        $(".tab-preview").css('background-color',  '');
        $(this).css('background-color',  '#CCFFFF');
        $("#action_menu").width($(this).width());
        $(".tab-action-link").hide();
        var tab = 1;

        var ch_ref = $(this).attr("id");

        var challenge_id = 0;

        var ta = ch_ref.split("_");

        if (ta.length > 1)
        {
          challenge_id = ta[1];
        }

        if ($(this).hasClass("preview-earn"))
        {
          $("#action_menu_sponsor").show();
          tab = 2;
          $("#action_menu_sponsor").attr("href", "#tabs-"+ challenge_id + ":" + tab);
        }
        else if ($(this).hasClass("preview-help"))
        {
          $("#action_menu_help").show();
          tab = 3;
          $("#action_menu_help").attr("href", "#hover-action:" + challenge_id);
        }
        else if ($(this).hasClass("preview-impress"))
        {
          $("#action_menu_impress").show();
          tab = 4;
          $("#action_menu_impress").attr("href", "#hover-action:" + challenge_id);
        }
      },
      function () {
        $('#action_menu').hide();
        $(".tab-preview").css('background-color',  '');
      }
      );
  };
};

var Comment = new function()
{

  this.ShowReplyForm = function(link)
  {
    var id = link.attr("id");

    var ta = id.split(":");
    if (ta.length > 1)
    {
      parent_id = ta[1];
      $('#replyform_' + parent_id).slideDown('fast');
    }
    return false;


  };

  this.CancelSolverCommentReply = function(link)
  {
    var id = link.attr("id");

    var ta = id.split(":");
    if (ta.length > 1)
    {
      parent_id = ta[1];
      $('#replyform_' + parent_id).slideUp('fast');
    }
    return false;
  };


  this.SubmitSolverCommentReply = function(link)
  {
    var id = link.attr("id");

    var ta = id.split(":");
    if (ta.length > 1)
    {
      parent_id = ta[1];
      $('#reply_' + parent_id).submit();
    }
    return false;
  };


};

var Solution = new function()
{

  this.Voted = function(result)
  {
    $('#votecount').html(result.votes);
    $('#votesolutionlink').hide().after('Voted!');
  };


};

var Problem = new function()
{
  this.Vote = function(url)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $.post(url.attr('href'), {}, function(data, textStatus) {
        Problem.Voted(data);
      }, 'json');
      return false;
    });
  };

  this.VoteFromList = function(url)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $.post(url, {}, function(data, textStatus) {
        Problem.VotedFromList(data);
      }, 'json');
      return false;
    });
  };

  this.Delete = function(url)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      var agree=confirm("Are you sure you want to delete?");
      if (agree) { } else {
        return false
      };
      $.get(url, {}, function(data, textStatus) {
        Problem.Deleted(data);
      }, 'json');
      return false;
    });
    return false;
  };


  this.Deleted = function(data)
  {
    $('.wish_' + data.wish_id).slideUp();
  };

  this.WishPost = function()
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $("#wishpost").submit();
    } );
  };



  this.Share = function(data)
  {

    var url = '/wishes/' + data.url + '/share?s=1';

    $.get(url, {}, function(data){
      $('#categorize_wish').html(data);
      Problem.AttachShareForm($('#problemshare'));
      $('#categorize_wish').modal({
        persist:true
      });
    });
  }

  this.WishPostAdd = function()
  {
    // get the wish ID

    var wish_id = $('#add-wish-id').val();

    var url = '/suggest-app/add?w=' + wish_id;

    $.get(url, {}, function(data){

      if (data.result == 1)
      {
        // show confirmation

        $('#wishpostadd').slideUp('fast');
        $('#wishpostaddconfirm').slideDown('fast');

      }
      else
      {
    // show error message


    }
    }, 'json');

  }

  this.WishSubmitted = function(data)
  {
    $('#wish_submitted').removeClass('hide');
    $('.error').removeClass('error');
    $('.error-message').remove();

    /* new functionality
   *
   *  var url = '/wishes/' + data.url + '/categorize?s=1';

		$.get(url, {}, function(data){
			$('#categorize_wish').html(data);
			Problem.AttachCategorizeForm($('#problemcategorize'));
			Challenge.SetupCategorySelect();
			$('#categorize_wish').modal({persist:true});
		});
   */

    if (data.suggest)
    {
      $('#wishpostadd').slideDown('fast');
      $('#add-wish-id').val(data.wish_id);
    }
    else
    {
      $('#wish-input').parent().after('<span class="success-message">'+data.message+'</span>');
      $('#wish-count').html(data.count);

      $(".categorize_wish").click(function (e) {
        Problem.CategorizeWish($(this));
        return false;
      }
      );
    }


  };

  this.WishUpdateSubmitted = function(data)
  {
    $('#wish_submitted').removeClass('hide');

    $('.error').removeClass('error');

    $('.error-message').remove();

    $('#edit_wish_' +data.wish_id).hide();

    $('#wish_title_' + data.wish_id).html(data.wish_description).css("background", "yellow").fadeTo(500,1); ;

  };

  var suggest_timeout = null;

  this.WishSuggest = function()
  {
    $("#wish-input").keyup(function()
    {
      var search;
      search = $("#wish-input").val();

      if (search.length > 6)
      {

        if (suggest_timeout) {
          clearTimeout(suggest_timeout);
        }
        suggest_timeout = setTimeout(function(){

          $.get('/wishes/suggest', {
            "q" : search
          }, function(data){
            $('.suggestions').remove();
            $('#wish-input').parent().after(data);
            $('#problem_suggestions').slideDown();
            Problem.SetupVoteListLinks();
            $(".hide_suggestions").click(function() {
              $('.suggestions').slideUp();
              $("#wish-input").unbind("keyup");
              return false;
            });

          });

        }, 400);



      }
      else
      {
    // Empty suggestion list

    }
    });
  };

  this.AttachWishUpdatePostForm = function(form)
  {

    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {

        $('.error').removeClass('error');

        $('.error-message').remove();
        $('.success-message').remove();

        if (data.result == 1)
        {
          Problem.WishUpdateSubmitted(data);
        }
        else
        {
          $('#wish-input').parent().addClass('error');
          $('#wish-input').parent().append('<span class="error-message">'+data.message+'</span>');
        }
      },

      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: true,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      $(this).ajaxSubmit(options);
      return false;
    });



  };


  this.AttachWishPostForm = function(form)
  {

    var options = {
      target:        '#output2',   // target element(s) to be updated with server response

      success: function(data) {

        $('.error').removeClass('error');

        $('.error-message').remove();
        $('.success-message').remove();

        if (data.result == 1)
        {
          Problem.WishSubmitted(data);
        }
        else
        {
          $('#wish-input').parent().addClass('error');
          $('#wish-input').parent().append('<span class="error-message">'+data.message+'</span>');
        }
      },

      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: true,        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      beforeSubmit: function () {
        // CPGlobal.ShowWaitMessage();
        var isvalid = true;
        pageTracker._trackPageview(form.attr('action'));
        $(".defaultText").each(function() {
          if($(this).val() == $(this).attr('title')) {
            $('#wish-input').parent().addClass('error');
            $('#wish-input').parent().append('<span class="error-message">Please enter a wish</span>');
            isvalid = false;
          }
        });
        return isvalid;
      },

      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      $(this).ajaxSubmit(options);
      return false;
    });


    $('.submit_wish').click(function () {
      Problem.WishPost();

      return false;
    });

  };

  this.VotedFromList = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
      return;
    }
    $('.voteproblemcount' + data.problem_id).html(data.votes);
    $('.voteproblemlink' + data.problem_id).after('<span class="i-posted">' + data.message + '</span>');
    $('.voteproblemlink' + data.problem_id).hide();



  };

  this.SetupVoteListLinks = function()
  {
    $(".problem_vote").unbind("click");

    $('.problem_vote').each(function() {
      $(this).click(function () {
        Problem.VoteFromList($(this).attr('href'));
        return false;
      });
    });
  };



  this.Voted = function(data)
  {
    if (data.result == "0")
    {
      alert(data.message);
      return;
    }

    $('.voteproblemcount').html(data.votes);
    $('.problem_vote').hide().after('<span class="i-share">' + data.message + '</span>');
  };

  this.Post = function()
  {
    ChallengeUser.LoginRequiredCallback(function() {
      $("#problempost").submit();
    } );
  };

  this.AnswerSubmitted = function(data)
  {
    if (data.result == 1)
    {
      alert('Submitted - need to refresh but autorefresh coming soon...');
    }
    else
    {
      alert('Error');
    }
  };

  this.ProblemSaved = function(data)
  {
    if (data.result == 1)
    {
      $('#setcategory').hide();
      $('#problemcategorize').hide();
      $('#category').html('Category: ' + data.category_name).show();
    }
    else
    {
      alert('Error');
    }
  };

  this.CategorizeWish = function(link)
  {
    url = link.attr('href');

    ChallengeUser.LoginRequiredCallback(function() {
      $.get(url, {}, function(data, textStatus) {
        $('#categorize_wish').html(data);
        Problem.AttachCategorizeForm($('#problemcategorize'));
        Challenge.SetupCategorySelect();
        $('#categorize_wish').modal({
          persist:true
        });
      }, 'html');
      return false;
    });

    return false;

  };

  this.Categorized = function(data)
  {

    if ($("#wish-input").length > 0 && data.s == '1')
    {
      $('.success-message').remove();
      $('#wish-input').parent().after('<span class="success-message">'+data.message+'</span>');
    }
    else
    {
      $('#wish_cat_name_'+ data.wish_id).html(data.category_name);
      $('#wish_cat_name_narrow_'+ data.wish_id).html(data.category_name);
    }





    $.modal.close();
  };

  this.AttachShareForm = function(form)
  {
    var options = {
      success: function(data) {
        if(data.result == 1)
        {
          if (data.updatetwitterfeed != undefined && data.updatetwitterfeed == 1)
          {
            Challenge.PublishTwitterLink($('#status').val());
          }
          else
          {

        }
        }
        else
        {
          alert(data.message);
        }
      },

      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      //clearForm: true        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });

    $('#categorize-wish-cancel').click(function() {
      $.modal.close();
      return false;
    });
  };

  this.AttachCategorizeForm = function(form)
  {
    var options = {
      success: function(data) {
        if(data.result == 1)
        {
          Problem.Categorized(data);
        }
        else if (data.result == 2)
        {
          Problem.Share(data);
        }
        else
        {
          alert(data.message);
        }
      },

      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      //clearForm: true        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });

    $('#categorize-wish-cancel').click(function() {
      $.modal.close();
      return false;
    });
  };

  this.RequestIgnored = function(data)
  {
    // remove the message

    // if no messages are left - remove the whole thing @todo

    $('#currency_notice').hide('slow');
  };

  this.WishesClaimed = function(data)
  {
    if (data.result == 1)
    {
      $('.claim_wishes').hide().after('<div class="success">'+data.message+'</div>');
    }
    else
    {
      alert(data.message);
    }
  };

  this.ClaimWishes = function()
  {
    $.post('/profile/claim-wishes', {
      "claim" : "1"
    }, function(data, textStatus) {
      Problem.WishesClaimed(data);
    }, 'json');
  };

  this.IgnoreRequest = function(url)
  {
    $.post(url, {}, function(data, textStatus) {
      Problem.RequestIgnored(data);
    }, 'json');
  };

  this.CurrencyRequested = function(data)
  {
    // hide the link that was clicked and append a message after it
    if (data.result == 1)
    {
      // build the message - @todo this should come from the server so we can translate it more easily

      var message = '';
      var messagetype = 'notice';

      if (data.sent == 1)
      {
        message = '1 invitation sent. ';
        messagetype = 'success';
      }
      else
      {
        message = data.sent + ' invitations sent. ';
        messagetype = 'success';
      }

      if (data.alreadysent > 0)
      {
        message += data.alreadysent + ' invitations already sent. ';
      }

      if (data.alreadyengaged == 1)
      {
        message += data.alreadyengaged + ' person has already joined this challenge.';
      }
      else if (data.alreadyengaged > 1)
      {
        message += data.alreadyengaged + ' people have already joined this challenge.';
      }
      $('#curreny_request_link_' + data.problem_id).hide().after('<div class="' + messagetype + '">' + message + '</div>');
    }
    else
    {
      alert('error');
    }

  };

  this.SetupCurrencyRequest = function()
  {
    $('.invitewishes').each(function() {
      Challenge.InviteWishesSetup($(this));
    });
  };

  this.AttachAnswerForm = function(form)
  {
    var options = {
      success: function(data) {
        if (data.result == 1)
        {
          Problem.AnswerSubmitted(data);
        }
        else
        {
      // todo - show error message
      }
      },

      // other available options:
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      //clearForm: true        // clear all form fields after successful submit
      //resetForm: true        // reset the form after successful submit

      // $.ajax options can be used here too, for example:
      timeout:   3000
    };

    // bind to the form's submit event
    form.submit(function() {
      // inside event callbacks 'this' is the DOM element so we first
      // wrap it in a jQuery object and then invoke ajaxSubmit
      $(this).ajaxSubmit(options);

      // !!! Important !!!
      // always return false to prevent standard browser submit and page navigation
      return false;
    });
  };
};


var Notification = new function()
{
  this.HelpMe = function(url)
  {
    // prase the url
    url = url.split("#");
    ChallengeUser.LoginRequiredCallback(function() {
      $.post(url[0], {}, function(data, textStatus) {
        Notification.HelpMeComplete(data, url[1]);
      }, 'json');
      return false;
    });
  };

  this.HelpMeComplete = function(data, notification_id)
  {
    // clear messages

    $('.action_message').remove();

    // display a confirmation message

    if (data.result == 1)
    {
      $('.notifications').before('<div class="success action_message">' + data.message + '</div>');
    }
    else
    {
      $('.notifications').before('<div class="notice action_message">' + data.message + '</div>');
    }

    // refresh the notifications

    Notification.Refresh();
  };

  this.ImpressMe = function(url)
  {
    // prase the url
    url = url.split("#");
    ChallengeUser.LoginRequiredCallback(function() {
      $.post(url[0], {}, function(data, textStatus) {
        Notification.ImpressMeComplete(data, url[1]);
      }, 'json');
      return false;
    });
  };

  this.Read = function(link)
  {
    // prase the url
    id = link.attr('id');
    id = id.split(":");
    ChallengeUser.LoginRequiredCallback(function() {
      $.post('/notification/read', {
        'id' : id[1]
      }, function(data, textStatus) {
        $("#unread_"+data.id).remove();
      }, 'json');
      return false;
    });
  };

  this.ImpressMeComplete = function(data, notification_id)
  {
    // clear messages

    $('.action_message').remove();

    // display a confirmation message

    if (data.result == 1)
    {
      $('.notifications').before('<div class="success action_message">' + data.message + '</div>');
    }
    else
    {
      $('.notifications').before('<div class="notice action_message">' + data.message + '</div>');
    }

    // refresh the notifications

    Notification.Refresh();
  };


  this.Refresh = function()
  {
    $.get('/notification/index', {}, function(data, textStatus) {
      $('.notifications').html(data);
    }, 'html');

  };


};


var CPGlobal = new function()
{

  this.ShowWait = function(str)
  {
    if (str === undefined || str === '')
    {
      $('.loading').show();
    }
    else
    {
      $(str).show();
    }
  };

  this.HideWait = function()
  {
    $('.loading').hide();
  };

  this.AttachErrorMessages = function(errors)
  {
    $('.error').removeClass('error');
    for (var i = 0; i < errors.length; i++)
    {
      field = errors[i].field;
      messages = errors[i].messages;
      if (messages.length)
      {
        message = CPGlobal.BuildErrorMessage(messages);
        $('#' + field).after(message);
        $('#' + field).parent().addClass('error');

      }

    }
  };

  this.BuildErrorMessage = function(messages)
  {
    var message = '';

    for (var j = 0; j < messages.length; j++)
    {
      message = message + "<span class='error-message'>" + messages[j] + "</span>";
    }

    return message;


  };
};

var ChallengeUser = new function()
{
  this.RefreshTopMenu = function()
  {
    $.get("/nav/get-top-menu", {
      'current_url' : location.pathname
    }, function(data) {
      $("#header").before(data).remove();
    });
  };
  this.LoginRequiredRedirect = function(link)
  {
    if (!loggedin)
    {
      $('#userlogin').unbind('submit');
      $('#userregister').unbind('submit');
      $("#redirect").val(link.attr("href"));
      $("#registerredirect").val(link.attr("href"));
      $("#basicModalContent").modal({
        persist:true
      });
      return false;
    }
    window.location=link.attr("href");
  };

  this.SetCropCords = function(c)
  {
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#x2').val(c.x2);
    $('#y2').val(c.y2);
    $('#w').val(c.w);
    $('#h').val(c.h);

  };

  this.SaveCrop = function(e)
  {
    alert(e.tellSelect);
  };

  this.Login = function(link)
  {
    if (!loggedin)
    {

      var href = link.attr("href");
      var ta = href.split("?");

      if (ta.length > 1)
      {
        var redirect = ta[1];
        ta = redirect.split("=");
        redirect = ta[1];
        $("#redirect").val(redirect);
      }
      else
      {
        $("#redirect").val(href);
      }

      $("#basicModalContent").modal({
        persist:true
      });
      return false;
    }
    return true;
  };

  this.LoginRequired = function(result)
  {
    if (!loggedin)
    {
      $('#userlogin').unbind('submit');
      $('#userregister').unbind('submit');
      $("#basicModalContent").modal({
        persist:true
      });
      return false;
    }
    return true;
  };

  this.DeleteCard = function(link)
  {
    var answer = confirm("Are you sure?");
    if (!answer){
      return false;
    }

    $.get(link, { },
      function(data){

        if (data.result == 1)
        {
          $(".card_" + data.customer_payment_profile_id).slideUp();
          $(".card_" + data.customer_payment_profile_id + '_message').addClass('success').html(data.message).slideDown();
        }
        else
        {
          alert(data.message);
        }


      }, 'json');
    return false;
  };

  this.ExternalInvited = function(data)
  {
    alert(data.message);
    window.location.reload();
  };

  this.AttachInviteExternalForm = function(form)
  {
    var options = {
      success: function(data) {
        if (data.result == 1)
        {
          ChallengeUser.ExternalInvited(data);
        }
        else
        {
          // todo - show error message
          alert(data.message);
        }
      },

      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      timeout:   3000
    };
    form.submit(function() {
      $(this).ajaxSubmit(options);
      return false;
    });
  };

  this.ExternalFollowed = function(data)
  {
    alert(data);
  };

  this.AttachFollowExternalForm = function(form)
  {
    var options = {
      success: function(data) {
        // CPGlobal.HideWaitMessage();
        if (data.result == 1)
        {
          ChallengeUser.ExternalFollowed(data);
        }
        else
        {
          // todo - show error message
          alert(data.message);
        }
      },

      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      beforeSubmit: function () {
        // CPGlobal.ShowWaitMessage();
        pageTracker._trackPageview(form.attr('action'));

      },

      timeout:   3000
    };
    form.submit(function() {
      $(this).ajaxSubmit(options);
      return false;
    });
  };


  this.CheckUsername = function(username)
  {

    $.get('/user/' + username + '/available', { },
      function(data){
        $("#username").after(data.message);
      });
  };

  this.LoginRequiredCallback = function(callback)
  {
    /*
   * Had to change the way this worked to ensure that if someone times out based on a session or a logout on another tab
   */
    $.getJSON('/check-login', { },
      function(data){
        if (data.result)
        {
          callback();
        }
        else
        {
          ChallengeUser.showLoginWindow(callback);
        }
      });
  /*
        if (!loggedin)
        {
        	this.showLoginWindow(callback);
        }
        else
        {
        	// @todo - if timed out - need to check




        }
   */
  };

  this.handleLoginResult = function(responseText, statusText)
  {
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
      '\n\nThe output div should have already been updated with the responseText.');
  };

  this.showLoginWindow = function(callback)
  {
    $("#basicModalContent").modal({
      persist:true
    });

    // add ajax to the form
    $('#uemail').focus();
    var loginoptions = {
      success: function(data) {
        if (data.result == 1)
        {
          $.modal.close();
          loggedin = 1;
          callback();
          ChallengeUser.RefreshTopMenu();
        }
        else
        {
          $('.error-message').remove();
          $('#userlogin').append('<div class="error-message">'+data.message+'</div>');
        }
        CPGlobal.HideWait();
      },
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      resetForm: false,        // reset the form after successful submit
      timeout:   3000,

      beforeSubmit: function () {
        CPGlobal.ShowWait();
        $('.error-message').remove();
        pageTracker._trackPageview('/login');
        return true; // @todo validate to make sure that they enter something
      }
    };

    $('#userlogin').unbind('submit');

    // bind to the form's submit event
    $('#userlogin').submit(function() {
      $(this).ajaxSubmit(loginoptions);
      return false;
    });

    var regoptions = {
      success: function(data) {
        CPGlobal.HideWait();

        $('#btn-register').removeAttr("disabled");

        if (data.result == 1)
        {
          Challenge.ClearDefaultText();
          // callback();

          // show a confirmation screen
          loggedin = 1;
          $('.modal-register-form').empty();
          $('.modal-register-form').append('<h2>'+data.message+'</h2>');
          $('.modal-register-form').append('<p>We have just sent you a welcome e-mail with a link so that we can verify your e-mail address.</p>');
          $('.modal-register-form').append('<p>You may now click <a href="#" id="continueaction">here</a> to continue.</p>');
          $('#continueaction').click(function() {
            $.modal.close();
            callback();
          });
          ChallengeUser.RefreshTopMenu();
        // show them a button which when clicked will do what they had started to do

        }
        else
        {
          $('.error-message').remove();
          CPGlobal.AttachErrorMessages(data.errors);
          $('#userregister').append('<div class="error-message">'+data.message+'</div>');
        }
      },
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      resetForm: false,        // reset the form after successful submit
      timeout:   3000,

      beforeSubmit: function () {
        CPGlobal.ShowWait();
        $('#btn-register').attr("disabled", "true");
        pageTracker._trackPageview('/register');
        return true; // @todo validate to make sure that they enter something
      }
    };

    $('#userregister').unbind('submit');
    // bind to the form's submit event
    $('#userregister').submit(function() {
      $(this).ajaxSubmit(regoptions);
      return false;
    });




  };

  this.AttachCropForm = function()
  {
    var regoptions = {
      success: function(data) {
        if (data.result == 1)
        {

        }
        else
        {

      }
      },
      dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type)
      clearForm: false,        // clear all form fields after successful submit
      resetForm: false,        // reset the form after successful submit
      timeout:   3000,

      beforeSubmit: function () {
        return true; // @todo validate to make sure that they enter something
      }
    };


    // bind to the form's submit event
    $('#crop').submit(function() {
      $(this).ajaxSubmit(regoptions);
      return false;
    });
  };

  this.fbIfUserConnected = function()
  {
    $.getJSON("/login-from-facebook", function(data){
      if (data.result == 1)
      {
        // callback();

        // show a confirmation screen
        loggedin = 1;
        window.location.reload(); // @todo only refresh parts of the page that need refreshing.

      }
      else
      {
    // @todo - not sure what to do here
    }
    });

  };


  this.fbIfUserNotConnected = function()
  {
  // @todo - do we need to do anything here?
  };

  this.Follow = function(url)
  {

    ChallengeUser.LoginRequiredCallback(function() {
      CPGlobal.ShowWait();
      $.get(url, {}, function(data, textStatus) {
        ChallengeUser.Followed(data);
        CPGlobal.HideWait();
      }, 'json');
      return false;
    });
    return false;
  };

  this.Block = function(url)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      CPGlobal.ShowWait();
      $.get(url, {}, function(data, textStatus) {
        ChallengeUser.Blocked(data);
        CPGlobal.HideWait();
      }, 'json');
      return false;
    });
    return false;
  };

  this.UnFollow = function(url)
  {
    ChallengeUser.LoginRequiredCallback(function() {
      CPGlobal.ShowWait();
      $.get(url, {}, function(data, textStatus) {
        ChallengeUser.UnFollowed(data);
        CPGlobal.HideWait();
      }, 'json');
      return false;
    });
    return false;
  };

  this.Blocked = function(data)
  {

    // CPGlobal.HideWaitSpinner();
    if (data.result == 1)
    {
      //$('#msg_' + data['block']).html('<div class="">' + data['message'] + '</div>');
      //$('#action_' + data['block']).addClass('hide');
      $('#action_' + data.block).html('<span class="action-text">' + data.message + '</span>');
    }
    else
    {
      alert(data.message);
    }
  };

  this.UnFollowed = function(data)
  {

    // CPGlobal.HideWaitSpinner();
    if (data.result == 1)
    {
      $('#action_' + data.unfollow).html('<span class="action-text">' + data.message + '</span>');
      //$('#msg_' + data['unfollow']).html('<div class="">' + data['message'] + '</div>');
      //$('#action_' + data['unfollow']).addClass('hide');
      //$('#unfollow_user').hide().after('<div class="">' + data['message'] + '</div>');
      $('span.following').html('<div class="">' + data.message + '</div>');
    }
    else
    {
      alert(data.message);
    }
  };

  this.Followed = function(data)
  {

    // CPGlobal.HideWaitSpinner();
    if (data.result == 1)
    {
      $('#action_' + data.follow).html('<span class="action-text">' + data.message + '</span>');
      // $('#msg_' + data['follow']).html('<div class="">' + data['message'] + '</div>');
      // $('#action_' + data['follow']).addClass('hide');
      $('#follow_user').hide().after('<span class="following">' + data.message + '</span>');
      $('#followingme').hide('normal');
      $('#followingme').after('<a href="/'+data.my_user_url+'">' + data.my_name + '</a>');
      $('#followingme').show('slow');
      $('.followers_count').html(data.followers);
      if (data.followers == 1)
      {
        $('.followers_link').html("follower");
      }
      else
      {
        $('.followers_link').html("followers");
      }
    }
    else
    {
      alert(data.message);
    }
  };

};

