jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

/* ------------------------------------------------------------------------------ */

$(document).ready(function() {		
	roundCorners();
	focusLoginField();
	observeStatusForm();		
	prepButtons();
	initTooltips();
	initCaretrackerLoader();
	buildStatusWidgets();
  // positionStatusDropdowns();
  // positionStatusValues();
	
	observeApprovalForm();
	observeSignupSubscriptionOptions();
	observeSignupExistingAccountQuestion();
	observeCommentToggleLinks();	
	observeWeeklyUpdateSettings();
	observeSubscriptionUpdateFrequencies();
	observeTriggerLinks();
	observeResidentTabs();
	observeEditResidentForm();
	observeCorkboardForm();
	observeProviderForgotPasswordLink();
	observeQuickConnectForm();
  observeMetricCustomizations();
	scrollToErrors();	
	
	observeSessionExpiration();	
});

// when page is completely loaded (graphics, etc.)
$(window).load(function() {
	fixTallSidebars();
});


function fixTallSidebars()
{
	if ($('#sidebar').height() > $('#main').height()) {
		$('#main').css('min-height', $('#sidebar').height());
	}
}

function roundCorners()
{
	$('.rounded').corners();
	$('.status_buttons a').corners("1px transparent");
}

function focusLoginField()
{
	$('form input#login').focus();
}

function observeStatusForm()
{
	// make sure all metrics have been entered
	$('form#status_update').submit(function(event) {
		var missing_ratings = false;		
		$('ul#status_blocks li input').each(function(index) {
			if ($(this).val().length == 0) {
				missing_ratings = true;				
			}
		});
		
		if (missing_ratings) {
			alert("Please make sure that all metrics have been rated.");
			event.stopPropagation();
			return false;			
		}
	});
	
	// watch for button mouseovers
	$('ul#status_blocks li div.status_buttons a').click(function() {
		var id = this.id.split('_')[1];
		$(this).parents('li').removeClass().addClass(this.className);
		$('input.rating_'+id).val(this.className);
		return false;
	});
}

function prepButtons()
{
	// construct a hidden, dummy submit button - firefox and IE
	// seems to want a submit button to enable "Enter" button
	// submissions
	$('a.submit').after("<input name='commit' type='submit' value='' />").next().addClass('wayout');
	
	$('a.submit').focus(function() {
		$(this).addClass("medium_button_hover");
	});	

	$('a.submit').blur(function() {
		$(this).removeClass("medium_button_hover");
	});	

	$('a.submit').click(function() {
		$(this).parents('form').submit();
		return false;
	});	
		
	// add an inner span tag so that the CSS builds the button
	$('a.medium_button').wrapInner("<span></span>");
	
	$('a.submit').parents('form').submit(function(event) {
	  if (!event.isPropagationStopped()) {
			$('a.submit').each(function() {
				var submit_text = $(this).attr('rel');
				if (submit_text == "") { 
					submit_text = "Saving..."
				}
				$(this).children('span').addClass('inactive').html(submit_text);
			});				
		}		
	});	
}

function initCaretrackerLoader()
{
	if ($('#caretracker_loading').length) {
		$.fn.colorbox.init();
	  $.fn.colorbox({
	    inline:       true,
	    opacity:      0.8,
	    href:         "#caretracker_loading",
	    width:        "300px",
	    height:       "220px",
	    overlayClose: false
	  });   		
	}
}

function observeApprovalForm()
{
	// set initial values
	$('.button_option').hide();

	var selected_response = $('select#approval_response option:selected').val();
	if (selected_response == '') {
		$('#default_button').show();
	}
	else {		
		$('#'+selected_response+'_button').show();
		$('.callout .note').hide();
		$('#'+selected_response+'_note').show();		
	}
	
	// watch for changes
	$('select#approval_response').change(function() {
		// notes
		$('.callout .note').hide();
		$('#'+this.value+'_note').show();
		
		// buttons
		$('.button_option').hide();
		if (this.value == '') {
			$('#default_button').show();
		}
		else {			
			$('#'+this.value+'_button').show();		
		}
	});
}

function hideTooltips() 
{
	$('.tooltip').hide();	
}

function initTooltips() 
{
	hideTooltips();
	
	if ($('.normal_tooltip').length) {
		$('.normal_tooltip').tooltip({ 
			showURL: false,
			top: -50,
			extraClass: "normal_tooltip"
		});
		$('.normal_tooltip').click(function() {
			return false;
		});
	}
}

function buildStatusWidgets()
{	
	$('ul.status_widget li').each(function() {		
		num_metrics = $(this).siblings().size() + 1;		
		block_width = Math.floor((100 - num_metrics + 1) / num_metrics);
		
		var metric = $(this).children('span.metric').html();
		var rating = $(this).children('span.rating').html();
		
		if (rating == "Good" || rating == "Better than last update") {
			$(this).addClass('good').width(block_width);
		}
		else if (rating == "Fair" || rating == "About the same") {
			$(this).addClass('fair').width(block_width);			
		}
		else if (rating == "Not Very Good" || rating == "Not as well") {
			$(this).addClass('not_good').width(block_width);
		}
	});
	
	if ( $('ul.status_widget').length) {		
		$('ul.status_widget').tooltip({ 
				track: true,
				extraClass: "tooltip",
				opacity: 1,
		    bodyHandler: function() { 
		      return $($(this).next('.tooltip').html()); 
		    }	
		});
	}
}

function positionStatusDropdowns()
{
	var longest = 100; // default value
	var current_width = 0;
	
	$('ul#status_blocks li').each(function() {
		current_width = $(this).children('label').width();
		if (current_width > longest) {			
			longest = current_width;
		}
	});
	
	$('ul#status_blocks li select').css({ left:longest + 30 + "px"});
	$('ul#status_blocks li .status_buttons').css({ left:longest + 35 + "px"});
}

function positionStatusValues()
{
	var longest = 100; // default value
	var current_width = 0;
	
	$('ul#status_blocks li').each(function() {
		current_width = $(this).children('label').width();
		if (current_width > longest) {			
			longest = current_width;
		}
	});
	
	$('ul#status_blocks li span.value').css({ left:longest + 40 + "px"});
}

function scrollToErrors()
{
	if ($('#flash_error').length) {		
		$.scrollTo('#flash_error', {offset:-20});
	}
}

function observeCommentToggleLinks()
{
	$('td.comments a.toggle').click(function() {
		var current_row = $(this).closest('tr');
		var comment_row = current_row.next('tr.comment_row');
		
		if (comment_row.is(':visible')) {
			current_row.removeClass('active');
			comment_row.removeClass('active');
			comment_row.hide();
		}
		else {
			current_row.addClass('active');
			comment_row.addClass('active');
			comment_row.show();
		}
		return false;
	});	
}

function observeWeeklyUpdateSettings()
{
	// see how many twice weekly days are checked
	num_selected = $('#twice_weekly_updates_days input:checked').length;
	
	if (num_selected == 0) {
		$('#twice_weekly_warning').html("Select two more days");
	}
	else if (num_selected == 1) {
		$('#twice_weekly_warning').html("Select one more day");
	}
	else if (num_selected == 2) {
		$('#twice_weekly_warning').hide();
	}
		
	// and observe the twice-weekly days of the week to make sure two are chosen
	$('#twice_weekly_updates_days :checkbox').click(function () {
		num_selected = $('#twice_weekly_updates_days input:checked').length;

		if (num_selected == 0) {
			$('#twice_weekly_warning').show();			
			$('#twice_weekly_warning').html("Select two more days");
		}
		else if (num_selected == 1) {
			$('#twice_weekly_warning').show();						
			$('#twice_weekly_warning').html("Select one more day");
		}		
		else if (num_selected == 2) {
			$('#twice_weekly_warning').hide();
		}		
		else if (num_selected > 2) {
			$(this).uncheck();
			alert('Only two days may be selected');
		};
		
	});
}

function observeSubscriptionUpdateFrequencies()
{
	$('#subscription_options :radio').click(function() {
		// hide all of them		
		$('span.downgrade_warning').hide();
		// then show the proper one, if applicable
		$(this).next().next().next('span.downgrade_warning').show();
	});
}

function observeResidentTabs()
{
	$('div.resident_panel').hide();

	$('#all_residents_trigger').click(function() {
		showResidentTab('all');
	});
	$('#due_residents_trigger').click(function() {
		showResidentTab('due');
	});
	$('#awaiting_residents_trigger').click(function() {
		showResidentTab('awaiting');		
	});
}

function showResidentTab(tab) {
	$('.loading').hide();
	$('.resident_panel').hide();
	$('#'+ tab + '_residents_wrapper').show();		
	$('ul.tab_bar li').removeClass('active');
	$('#tab_' + tab + '_residents').addClass('active');	
}

function observeTriggerLinks()
{
	$('#show_update_form_trigger').click(function() {
		showStatusEntryForm();
		return false;
	});

	$('#resident_in_home_care').is(':checked') ? $('#resident_home_address').show() : $('#resident_home_address').hide();
	$('#resident_in_home_care').click(function() {
		$('#resident_in_home_care').is(':checked') ? $('#resident_home_address').show() : $('#resident_home_address').hide();
	});
}

function observeSessionExpiration()
{
  if (!window.TIMEOUT_URL) return;
	if (!window.SESSION_TIMEOUT_MINUTES) return;
	
  $.idleTimer(SESSION_TIMEOUT_MINUTES * 60 * 1000);
	
	$(document).bind("idle.idleTimer", function(){
		location.href = TIMEOUT_URL;	  
    $.idleTimer('destroy');
  });  
}

function observeProviderForgotPasswordLink()
{
	$('a#provider_forgot_password').click(function() {
		$('#provider_forgot_password_instructions').show();
		$('#forgot').hide();
		return false;
	});
}

function observeSignupSubscriptionOptions()
{
	var amount = $('#subscription_options input:checked').next('label').children('em').children('span.amount').html();
	$('#monthly_amount').html(amount);
	
	$('#subscription_options input').click(function() {
		var amount = $($(this).next('label')).children('em').children('span.amount').html();
		$('#monthly_amount').html(amount);
	});
}

function observeSignupExistingAccountQuestion()
{
	$('a.existing_account_no').click(function() {
		$('#new_subscriber_wrapper').show();
		$('#existing_account_question').hide();
		$('#existing_account_wrapper').hide();
		return false;
	});

	$('a.existing_account_yes').click(function() {
		$('#existing_account_wrapper').show();		
		$('#existing_account_question').hide();
		$('#new_subscriber_wrapper').hide();
		return false;		
	});

}

function observeEditResidentForm() {
	$('#subscription_provider_paid').is(':checked') ? $('#subscription_provider_paid_wrapper').show() : $('#subscription_provider_paid_wrapper').hide();
	$('#subscription_provider_paid').click(function() {
		$('#subscription_provider_paid').is(':checked') ? $('#subscription_provider_paid_wrapper').show() : $('#subscription_provider_paid_wrapper').hide();
	});	
}

function observeCorkboardForm()
{
	if ($('#provider_corkboard_content').length == 0) {
		return;
	}
	$('a.corkboard_edit_trigger').livequery('click', function() {
		$('#corkboard_main_content_wrapper').hide();
		$('#corkboard_form').show();
		return false;
	});
	
	$('#corkboard_form a.cancel').livequery('click', function() {
		$('#corkboard_form').hide();
		$('#corkboard_main_content_wrapper').show();
		return false;
	});
	
	var myEditor = new YAHOO.widget.Editor('provider_corkboard_content', { 
		height: '400px', 
		width: '100%', 
		autoHeight: true
	}); 
	
	myEditor.on('editorContentLoaded', function() { 
		var head = this._getDoc().getElementsByTagName('head')[0]; 
		var link = this._getDoc().createElement('link'); 
		link.setAttribute('rel', 'stylesheet'); 
		link.setAttribute('type', 'text/css'); 
		link.setAttribute('href', 'https://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/base/base-min.css'); 
		head.appendChild(link); 
		
		var link2 = this._getDoc().createElement('link'); 
		link2.setAttribute('rel', 'stylesheet'); 
		link2.setAttribute('type', 'text/css'); 
		link2.setAttribute('href', 'https://ajax.googleapis.com/ajax/libs/yui/2.8.0r4/build/fonts/fonts-min.css'); 
		head.appendChild(link2);
	}, myEditor, true);
	
	myEditor.render();

	$('#corkboard_form form').submit(function() {
		myEditor.saveHTML();
		$.ajax({
				data: 		$.param($(this).serializeArray()), 
				dataType: 'script', 
				type:     'post', 
				url:      '/provider/activities/save'
		}); 
		return false;				
	});
}

function observeQuickConnectForm()
{	
	$('a#quick_connect_trigger').click(function() {
		$('#quick_connect_cta').hide();
		$('form#quick_connect').show();
		fixTallSidebars();		
		return false;
	});

	$('a#quick_connect_cancel').click(function() {
		$('#quick_connect_cta').show();
		$('form#quick_connect').hide();
		fixTallSidebars();		
		return false;		
	});
	
	$('input#send_to_family').change(function() {
	  if ($(this).is(':checked')) {	    
      $('form#quick_connect .indent').slideDown('fast');
		  fixTallSidebars();		      
	  }
	  else {
      $('form#quick_connect .indent').slideUp('fast');	    
	  }
	});
	
	if ($('#quick_connect_message').length) {
		$("#quick_connect_message").charCounter(160, {
			container: "#quick_connect_count",
			format: "<strong>%1</strong> characters remaining"
		});		
	}
}

function observeMetricCustomizations() {
  // initialize UI
  $('table.provider_metrics td input:checked').each(function() {
    $(this).closest('td').addClass('disabled');
  });

  $('a#toggle_custom_metrics').click(function() {
    $('#custom-metrics-wrapper').slideDown('fast');
    $('a#toggle_custom_metrics').hide();
    return false;
  });

  // observe checkboxes
  $('table.provider_metrics td input:checkbox').change(function() {
    if ($(this).is(':checked')) {
      $(this).closest('td').addClass('disabled');
    }
    else {
      $(this).closest('td').removeClass('disabled');
    }
  });

  // observe new metrics
  $('a#add_metric').click(function() {
    saveCustomMetric();
    return false;
  });
  
  // observe deleting metrics
  $('a.delete-metric').live('click', function() {
    if (confirm('Are you sure you want to remove this metric?')) {
      removeCustomMetric($(this).attr('id').split('_')[1]);
    }
    return false;
  });

  // watch for hitting the enter key while adding custom metrics
  // so that we don't trigger a form submission for the entire page
  $('#new_custom_metric').keypress(function(event) {
    if (event.keyCode == '13') {
      saveCustomMetric(event);
      event.preventDefault();
     }
  });
  
}

function saveCustomMetric() {
  if ($('input#new_custom_metric').val().replace(/^\s+|\s+$/g, '') == '') {
    alert('Please enter a metric name.');
    $('input#new_custom_metric').focus();
  }
  else {
    $.ajax({
      type: "POST",
      dataType: "script",
      url: "/provider/settings/add_metric",
      data: "metric="+$('input#new_custom_metric').val()
    });
  }
}

function addCustomMetric(metric, id) {
  $('#custom-metrics').append('<li>'+metric+'<a href="#" id="metric_'+id+'" class="delete-metric">REMOVE</a></li>');
  $('#new_custom_metric').val('');
}

function removeCustomMetric(metric_id) {
  $.ajax({
    type: "POST",
    dataType: "script",
    url: "/provider/settings/delete_metric",
    data: "metric_id="+metric_id
  });
}

function hideCustomMetric(metric_id) {
  $('ul#custom-metrics a#metric_'+metric_id).closest('li').hide();
}

function residentTabLoad(hash) {
	if (hash) {			
		var hash_pieces = hash.split('/');
		var tab         = hash_pieces[0];
		showResidentTab(tab);
	} 
	else {
		// default, due residents
		showResidentTab('due');
	}
}

function initResidentTabs(callback_url)
{
	var hash = location.hash;
	hash = hash.replace(/^.*#/, '');		

	if (hash) {
		var hash_pieces = hash.split('/');
		var tab         = hash_pieces[0];
		var page				= hash_pieces[1] ? hash_pieces[1] : 1;
		
		// set proper tab/page link for tabs
		var hash_string = "#" + tab;		
		if (page) hash_string += "/" + page;
		$('#' + tab + '_residents_trigger').attr('href', hash_string);

		// reload the correct page if need be
		if (page != 1) {
			var data_string = "&tab="+tab;
			if (page) {
				data_string += "&page="+page;
			}

			$.ajax({
				type:"GET", 
				url:callback_url + '?',
				data:data_string,
				success: function(html) {
					$('#'+tab+'_residents_wrapper').replaceWith(html);
					hideTooltips();
					buildStatusWidgets();
					showResidentTab(tab);	
					$.historyInit(residentTabLoad);					
				}
			});										
		}
		else {
			// show the proper tab
			showResidentTab(tab);		
			$.historyInit(residentTabLoad);			
		}		
	}		
	else {
		showResidentTab('due');		
	}
}

function showStatusEntryForm()
{
	$('#not_due_notice').hide();
	$('#update_form_wrapper').show();
	positionStatusDropdowns();	
}

function loadStatusFromCareTracker(resident_id)
{
	var data_string = "&id="+resident_id;
	
  $.getJSON(
		"/provider/residents/load_caretracker_status",
		{ id: resident_id },
		function(data) {
		  
		  if (data.result == "success") {
		    showCareTrackerData(data);
		    setDateRangeFields(data);
		  }
		  else {
	      $.fn.colorbox.close();		    
	      $('<div id="flash_error">There was a problem loading the update information from CareTracker.</div>')
      			.insertAfter('h2:first-child').hide().slideDown(800);			        	
		  }
		  
		});  
}

function showCareTrackerData(data)
{
	// make sure form is visible
	showStatusEntryForm();

  $.each(data.metrics, function(i,metric) {
		var link = $('a#'+metric.rating.replace('_','')+'_'+metric.wm_id);
		link.click().hide().siblings('a').hide();
		var label = link.html();
		var indent = link.parent('div.status_buttons').css('left');
		link.parents('li').append('<span class="value">'+label+'</span>').find('span.value').css('left', indent);
  });
				
  $.fn.colorbox.close();
	
	$('<div class="notice">The status information below has been loaded from CareTracker.</div>')
			.insertAfter('h2:first-child').hide().slideDown(800);			  

  $('#status_comments').val(data.comments);
}

function setDateRangeFields(data)
{
  $('#status_start_date').val(data.start_date);
  $('#status_end_date').val(data.end_date);
}

function popup(url,width,height) 
{
	window.open(url,'popup','width='+width+',height='+height+',scrollbars=yes,resizable=yes,toolbar=no,directories=no,menubar=no,status=no,left=100,top=100');
	return false;
}

function getArgs(query_str) {
	var args  = new Object();
	var query = "";
	
	if (query_str != null) {
		query = query_str.substring(1);
	}
	else {		
		query = location.search.substring(1);     
	}
	var pairs = query.split("&");
	
	for (var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring(0,pos);
		var value = pairs[i].substring(pos+1);
		args[argname] = unescape(value);
	}
	return args;
}


