$(document).ready(function(){      
                                      
  /* force all links in challenge and task descriptions to open in a new window */
  $("#challenge-description a[href^='http']").not("[href*='ruzuku.com']").attr('target','_blank');
  $("#descer-for-update a[href^='http']").not("[href*='ruzuku.com']").attr('target','_blank');      
                                      
	$(".submit").live('click', function(){
		if( $(this).closest(".post-ctn").children().find("textarea").val() == "" ){
			event.preventDefault();
		} else if( $(this).closest(".post-ctn").hasClass("link-ctn") && $(".link-ctn .text").val() == "" ) {
			event.preventDefault();
		}
	});

 $(".post").bind("ajaxComplete", function() {
 		$(this).show("fast");
 	});

 $("#gcWelcomeMsg").bind("ajaxComplete", function() {
 		$("#gcWelcomeMsg").hide("fast");
 		$(".no-update").hide("fast");
 	});


  $('#challenge_duration').change();
  $('#challenge_frequency').change();

// Add Options on Quick Update	
	$('.showAddPhoto').click(function(){
		$(".photoUpload").removeAttr("disabled");
		$(".addOptions").hide();
		$(".addPhoto").show();
	});

	$('.showAddVideo').click(function(){
		$(".videoEmbed").removeAttr("disabled");
		$(".addOptions").hide();
		$(".addVideo").show();
	});

	$('.cancelCtn').click(function(){
		$(".photoUpload").attr({disabled: "disabled"});
		$(".videoEmbed").attr({disabled: "disabled"});
		$(".addOptions").show();
		$(".addPhoto, .addVideo").hide();
	});



$(".make-update").click(function(){
	$(".update-form").show();
	$("textarea#update_body").focus();
	$(this).addClass("selected");
	// $('#update_body').val("");
	// $(".post-made .make-update").hide(); 
});

	$(".post-made .cancel-link").live('click', function(){
		$(".update-form").hide();
		$(".updateCtn .options a").removeClass("selected");
	});


	$(".question-ctn form, .note-ctn form, .link-ctn form, .new-comment-form form").live('submit', function(){
		$(this).children("textarea, .submit").attr('disabled','disabled');
		$(this).children().find(".text").attr('disabled','disabled');
	});


$(".read-descer").click(function(){
	$("#descer-for-update").show("fast");
	$(".post-made .read-descer").hide();
});



// setTimeout(function() { $("#appMessages, .appMessages").animate({opacity: 0,height:0}, 500 ); }, 15000 ); 
	
	 // Emotion Selection
  $(".emotionOption").click(function(event) {
    event.preventDefault(); // Don't visit href
		id = this.id.match(/[a-zA-Z]+([0-9]+)/)[1];
    src = $(this).find("img").get(0).src;
		$(".emotionOption img").removeClass("emoticonHighlight");
    $(this).find("img").addClass("emoticonHighlight");


    // Assign id to hidden input value
    $(this).parent().find(".update_emoticon").get(0).value = id;
    $(".update_emoticon").trigger('change');
		
		
  });


	 $("h1.chHeading").hover(function() {
    $(".hoverable").toggle();
		}, 
		function() {
			$(".hoverable").toggle();
		});

	
//create confirm for end of challenge
	$("a.doThisLater").click(function() {
		if ($(this).parent("div #endOfChallenge").children("div.endOfChallenge").children("div.challengeOptions").children("div.challengeUpdate").children("form").children("textarea").val() != "") {
		return confirm("Looks like you're in the middle of making a progress update. If you choose to do this later, this will not be saved. Do you want to continue?");
		}
	});

	$(".viewScheduleLink").click(function() {
		$("#challengeSchedule").toggle();
	});

	$(".view-start-link").click(function() {
		$("#signup_url").toggle();
		$(".view-start-link").toggleClass("highlighted");
	});


	$(".lhField, .lhSctn").click(function(){
		thisField = $(this).closest(".field");
		thisSctn = $(this).closest(".sctn");
		thisHelp = $(this).parents().children(".help");
		$(".field").not(thisField).removeClass("highlighted");
		$(".sctn").not(thisSctn).removeClass("highlighted");
		$(".help").not(thisHelp).hide("fast");
		if ( $(this).hasClass("lhField") ) {
			$(thisField).toggleClass("highlighted");				
		};
		if ( $(this).hasClass("lhSctn") ) {
			$(thisSctn).toggleClass("highlighted");				
		};
		$(thisHelp).toggle("fast");		
	});

	//$('.elastic').elastic();
	$('.active_member a, #participation-score a').tipsy({gravity: 's'});


	$("#navPromptsDescriptions a").click(function(){
		$("#navPromptsDescriptions a").removeClass("selected");	
		$(this).addClass("selected");	
		if ( $(this).attr("id") == "link-all-prompts" ) {
			$("#prompts-ctn").fadeIn("fast");
			$("#descriptions-ctn").hide();
			$("#byday-ctn").hide();
		}
		if ( $(this).attr("id") == "link-all-scheduled" ) {
			$("#prompts-ctn").hide();
			$("#descriptions-ctn").hide();
			$("#byday-ctn").show();
			$(".has-description .description-ctn h3").show("fast");
			$(".has-description .description-content p").show("fast");
			$(".has-description .description-ctn .options").show("fast");
			$(".has-description .description-ctn").removeClass("no-margin");
			$(".has-prompt .prompt-ctn").show("fast");
			$(".missing-description .description-ctn").show("fast");
			$(".missing-prompt .prompt-ctn").show("fast");
			$(".byday-item h2").addClass("expand");
			$(".byday-item h2").removeClass("collapse");

		}
		if ( $(this).attr("id") == "link-all-descer" ) {
			$("#prompts-ctn").hide();
			$("#descriptions-ctn").fadeIn("fast");
			$("#byday-ctn").hide();
		}
		if ( $(this).attr("id") == "link-days-missing" ) {
			$("#prompts-ctn").hide();
			$("#descriptions-ctn").hide();
			$("#byday-ctn").show();
			$(".has-description .description-ctn h3").hide("fast");
			$(".has-description .description-content p").hide("fast");
			$(".has-description .description-ctn .options").hide("fast");
			$(".has-description .description-ctn").addClass("no-margin");
			$(".has-prompt .prompt-ctn").hide("fast");
			$(".missing-description .description-ctn").show("fast");
			$(".missing-prompt .prompt-ctn").show("fast");
			$(".missing-description h2, .missing-prompt h2").addClass("expand");
			$(".missing-description h2, .missing-prompt h2").removeClass("collapse");
			$(".has-prompt h2, .has-description h2").removeClass("expand");
			$(".has-prompt h2, .has-description h2").addClass("collapse");
		}
		return false;
	});


// Toggle for main tasks schedule page
	$(".byday-item h2").click(function(){
		$(this).closest(".byday-item").children(".prompt-ctn").toggle("fast");
		$(this).closest(".missing-description").children(".description-ctn").toggle("fast");
		$(this).closest(".has-description").children(".description-ctn").find("h3").toggle("fast");
		$(this).closest(".has-description").children(".description-ctn").find(".description-content p").toggle("fast");
		$(this).closest(".has-description").children(".description-ctn").find(".options").toggle("fast");
		$(this).closest(".has-description").children(".description-ctn").toggleClass("no-margin");
		$(this).toggleClass("expand")		
		$(this).toggleClass("collapse")		
	});

	$("#schedule-other-days-ctn .more-link").click(function(){
		$(".schedule-other-days-field.hide").show("fast");		
		$("#schedule-other-days-ctn .more-link").removeClass("more-link");
		})

	$('textarea[maxlength], #description-heading-field-ctn input[maxlength]').keyup(function(){
		var max = parseInt($(this).attr('maxlength'));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}
		$(this).parent().find('#chars-remaining').html((max - $(this).val().length));

	});

	$("#participation-score .help-icon, #participation-score .close-icon").click(function(){
		$("#part-help-info").toggle();
	});

	$(".pose-question").click(function(){           
	  $(".update-form").show();
		$(".post-update, .note-ctn, .link-ctn").hide();
		$(".make-update, .post-note, .add-link").removeClass("selected");
		$(".pose-question").addClass("selected");
		$(".question-ctn").show();
	});

	$(".post-note").click(function(){
	  $(".update-form").show();
		$(".post-update, .question-ctn, .link-ctn").hide();
		$(".make-update, .pose-question, .add-link").removeClass("selected");
		$(".post-note").addClass("selected");
		$(".note-ctn").show();
	});

	$(".add-link").click(function(){
	  $(".update-form").show();
		$(".post-update, .question-ctn, .note-ctn").hide();
		$(".make-update, .pose-question, .post-note").removeClass("selected");
		$(".add-link").addClass("selected");
		$(".link-ctn").show();
	});

	$(".make-update").click(function(){
		$(".link-ctn, .question-ctn, .note-ctn").hide();
		$(".add-link, .pose-question, .post-note").removeClass("selected");
		$(".make-update").addClass("selected");
		$(".post-update").show();       
	});
	
  $("#group_challenge_start_date").datepicker({minDate: 0});


	$(".new-activity-link").live('click', function(event){
      var href = $(this).attr('href');
	  Boxy.load(href, {
	    unloadOnHide: true,
	    modal: true,
	    afterShow: function() {
          this.getContent().find('.mceEditor').each(function() {
          load_tinymce($(this).attr('id'));
          });
          this.center();
        },
        beforeUnload: function () {
          this.getContent().find('.mceEditor').each(function() {
            unload_tinymce($(this).attr('id'));
          });
          this.center();
        }
	  });                  
	  event.preventDefault();
	});

	$(".new-step-link").live('click', function(event){
      var href = $(this).attr('href');
	  Boxy.load(href, {
	    unloadOnHide: true,
	    modal: true,
	    afterShow: function() {
          this.getContent().find('.mceEditor').each(function() {
          load_tinymce($(this).attr('id'));
          });
          this.center();
        },
        beforeUnload: function () {
          this.getContent().find('.mceEditor').each(function() {
            unload_tinymce($(this).attr('id'));
          });
          this.center();
        }
	  });                  
	  event.preventDefault();
	});  
	
  // $(".step-edit-action, .activity-edit-action").live('click', function() {
  //   form_id = $(this).attr('href');
  //   alert('show edit form: ' + form_id);
  //   Boxy.
  //  return false;
  // });

	$('.step-edit-action, .activity-edit-action').live('click', function(event) {
	  var href = $(this).attr('href');
    Boxy.load(href, {
      unloadOnHide: true,
      modal: true,
      afterShow: function() {
        this.getContent().find('.mceEditor').each(function() {
          load_tinymce($(this).attr('id'));
        });
        this.center();
      },
      beforeUnload: function () {
        this.getContent().find('.mceEditor').each(function() {
          unload_tinymce($(this).attr('id'));
        });
        this.center();
      }
    });                  
    event.preventDefault();
  });
	
	$(".cancel-link").live('click', function(){
		$(".add-activity, .add-step, .screen, .panel").hide();  
	});
		
	$(".boxy-panel .cancel-link").live('click', function(){
		Boxy.get(this).hide();  
	}); 
   
	$(".done-order-steps").click(function(){
	  $('#step-list').removeClass('sorting');
		$(".activities-list").sortable("disable");
  	$("#step-list").sortable("disable");
		$(".activities-list, #step-list").removeClass("ui-state-disabled")
		$(".new-step-link").show();
		$(".reorder-steps").show();
		$(".done-order-steps").hide();
	});
	
	$(".reorder-steps").click(function(){       
	  $('#step-list').addClass('sorting');
		$(".new-step-link").hide();
		$(".reorder-steps").hide();
		$(".done-order-steps").show();
		$(".activities-list").sortable("enable");
		$(".activities-list").sortable({
		  connectWith: '.activities-list',
		  placeholder: 'activity-sort-placeholder', 
		  items: ".sortable-activity", 
		  cancel: ".add-link, .add-activity", 
		  helper: "clone", 
		  stop: function(event,ui) {
				//The function gets set in the target attr but it is evaluated in this scope.
				eval( $(ui.item).attr("target") )
			// $.ajax({
			// 		type: 'put',
			// 		url: $(ui.item).attr("target"),
			// 		data: {
			// 			'activity[position]': ($(this).children().index(ui.item)),
			// 			'activity[step_id]': $(ui.item).parents("li").attr("key"),
			// 			'activity[position]': ($(ui.item).parent("ul").children().index(ui.item) + 1)
			// 		}
			// })
  					}
  	});
  	$("#step-list").sortable("enable");
  	 $("#step-list").sortable({
  	   placeholder: 'step-sort-placeholder', 
  	   items: ".sortable-step", 
  	   helper: 'clone', 
  	   stop: function(event,ui) {
			//The function gets set in the target attr but it is evaluated in this scope.
			eval( $(ui.item).attr("target") )
			// $.ajax({
			// 		type: 'put',
			// 		url: $(ui.item).attr("target"),
			// 		dataType: 'script',
			// 		data: {
			// 			'step[position]': ($(this).children().index(ui.item) + 1),
			// 			replace_elt_id: 'step-list'
			// 		}
			// 	})
  					}
  	});
	});  
	
  // $('.validate').validate(); plugin needs a little work first

});

// A little magic to make our unobtrusive jQuery rjs replacements work.
$.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 	
})

$(function() {
  $('div #homeScroll').children('div.pagination').hide();
  var pgIter = 2;
  var numPages = $('div.pagination a').length;
  var page = document.location.href;
  $(window).scroll(function(){
    if ($(window).scrollTop() == $(document).height() - $(window).height() && pgIter <= numPages){
      var newEntries = $.get(page + '?page=' + pgIter, null, null, "script")
      pgIter++;
    }
 
  });
});  

function load_tinymce(id) {
  if (!tinyMCE.get(id)) {
    tinyMCE.execCommand('mceAddControl', false, id);
  }
}

function unload_tinymce(id) {
  if (tinyMCE.get(id)) {
    tinyMCE.execCommand('mceRemoveControl', false, id);  
  }
}