var chevronPosition = 0;
var multiplier = 1;

$(document).ready( function() {
	document.onkeydown = process_keyboard;

  $('.item').hover( 
		function() { $(this).addClass('item_hovering'); },
		function() { $(this).removeClass('item_hovering'); }
	);

	zebraTable( '#todo_items_table' );

	fixNotificationWidth();

    show_current_chevron();

	//$.datepicker.setDefaults({showOn: 'both', buttonImageOnly: true, 
    //buttonImage: 'calendar.gif', buttonText: 'Calendar'});
});

function open_link() {
  var id = get_chevron_id();
  var el = $('.item_description:eq('+chevronPosition+')')
  var desc = el.text();
  var url_re = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;
  var match = desc.match( url_re );
  //document.location = match[0];
  window.open( match[0] );
}

function show_current_chevron() {
  $('.chevron_img').hide();
  $('.chevron_img:eq('+chevronPosition+')').show();
}

function chevron_down() {
  var maxChevrons = $('.chevron_img').length;
  if ( ++chevronPosition > maxChevrons-1 ) chevronPosition = maxChevrons-1;
  show_current_chevron();
}

function chevron_up() {
  if ( --chevronPosition < 0 ) chevronPosition = 0;
  show_current_chevron();
}

function get_chevron_id() {
  var el = $('.item_checkbox:eq('+chevronPosition+')')[0];
  var itemid = el.id.split('_')[1];
  return itemid;
}

function chevron_mark() {
  markItemComplete( get_chevron_id() );
  var el = $('.item_checkbox:eq('+chevronPosition+')');
  if ( el.filter(':checked').length ) {
	el.attr( 'checked', false );
  } else {
	el.attr( 'checked', true );
  }
}

function chevron_postpone( numdays ) {
  postPoneItem( get_chevron_id(), numdays );
}

function fixNotificationWidth() {
  var tableWidth = $('#todo_items_table').width();
	$('#notifications').width( tableWidth-2 );
}

function zebraTable( tableid ) {
  $(tableid + ' tr').removeClass( 'odd even' );
  $(tableid + ' tr:odd').addClass( 'odd' );
  $(tableid + ' tr:even').addClass( 'even' );
}

function markItemComplete( itemId ) {
  var complete = $('#item_id_' + itemId).toggleClass( 'itemcomplete' ).hasClass( 'itemcomplete' );
	var q = complete ? 'markcomplete' : 'marktodo';
	$.get( 'helper.php', { q: q, id: itemId } );
}

function ExpandEdit( itemnum ) {
	var containerid = document.getElementById('communityposts');
	var textarea = document.getElementById('p_text_box_' + itemnum);
	
	$('#existing_entry_' + itemnum).hide();
	$('#edit_entry_form_' + itemnum).show();

	textarea.style.width = containerid.offsetWidth - 50 + "px";
}

function postPoneItem( itemId, daysToPostpone ) {
	$.get( 'helper.php', { q: 'postpone', 'id': itemId, 'days': daysToPostpone }, function(data){
		$('#notifications').html(data).show();
		//$( '#item_id_' + itemId).hide();
		$( '#item_id_' + itemId).remove();
		$( '#itemdue_' + itemId ).html( 'in ' + daysToPostpone + ' days' );
		show_current_chevron();
	});

}

function disableAutoRenew( itemId ) {
	$.get( 'helper.php', { q: 'disableautorenew', 'id': itemId }, function(data){
		$('#notifications').html(data).show();
	});

}

function toggleHelper( elId, displayType ) {
	var el = document.getElementById( elId );
	if ( el.style.display !== '' ) {
		el.style.display = ''; // no display, equivalent to 'none'
	} else {
		el.style.display = displayType;
	}
}
function toggleBlockDisplay( elId ) { // {{{
	return toggleHelper( elId, 'block' );
} // }}}

function toggleNote( elId ) {
  $('#'+elId).toggle();
}

function editOn( basetag ) {
  $('#'+basetag).hide();
	$('#edit_'+basetag).show();
	$('#input_'+basetag).focus();
}

function editOff( basetag ) {
	$('#'+basetag).show();
	$('#edit_' + basetag).hide();
}

function editSelect( basetag ) {
	$('#input_' + basetag).select();
}

function newDue( itemId ) {
	var newvalue = $('#input_itemdue_' + itemId).val();

	$.get( 'helper.php', { q: 'newduedate', id: itemId, due: newvalue }, function(data){
		$('#notifications').html(data).show();
    $( '#itemdue_' + itemId ).html( newvalue );
    $( '#item_id_' + itemId ).hide();
  });
}

function newName( itemId ) {
	var newvalue = $('#input_itemname_' + itemId).val();
	$( '#itemname_' + itemId ).html( newvalue );

	$.get( 'helper.php', { q: 'newname', id: itemId, name: newvalue } );
}

function newTag( itemId ) {
	var newvalue = $('#input_itemtag_' + itemId).val();
	$( '#itemtag_' + itemId ).html( newvalue );

	$.get( 'helper.php', { id: itemId, tag: newvalue } );
}

function process_keyboard(e) {
  // if IE, use window.event, else use event "e"
  var key = document.all ? window.event.keyCode : e.keyCode;

  var targ;
  if (!e) e = window.event;
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;

	if ( key == 27 ) { // ESC
		hideQuickAdd();
		targ.blur();
		multiplier = 1;
	}

	var is_text = targ.tagName == 'INPUT' || targ.tagName == 'TEXTAREA';
	if ( is_text ) {
		var is_editname = targ.className == 'editname';
		if ( is_editname ) {
			switch( key ) {
				case 13: // Enter
					targ.blur();
					break;
				default: 
					break;
			}
		}
	} else if ( key >= 50 && key <= 57 ) {
		multiplier = key - 48;
		return false;
	} else {
		switch( key ) {
			case 68: // 'd'
			    chevron_postpone( 1*multiplier );
				multiplier = 1;
				return false;
			case 74: // 'j'
			    chevron_down();
				return false;
			case 75: // 'k'
			    chevron_up();
				return false;
			case 76: // 'l'
			    open_link();
				return false;
			case 77: // 'm'
			    chevron_postpone( 30*multiplier );
				multiplier=1;
				return false;
			case 87: // 'w'
			    chevron_postpone( 7*multiplier );
				multiplier=1;
				return false;
			case 88: // 'x'
			    chevron_mark();
				return false;
			case 81: // 'q'
				showQuickAdd();
				return false; // returning false swallows the keystroke
			case 83: // '/'
				$('#search_input').focus();
				$('#search_input').select();
				return false;
			case 222: // '
				editOn( chevronPosition );
				break;
			default:
				//alert( key );
				break;
		}
	}
	return true;
}

function showQuickAdd() {
	$('#quickaddarea').show();
	$('#qa_task').focus();
}

function hideQuickAdd() {
	$('#quickaddarea').hide();
	document.getElementById('quickadd_form').reset();
}

function editItem( itemid ) {
  // call a helper that returns HTML
	// HTML will be a formatted div similar to the #quickaddarea
	// Will submit changes back to helper for updating
  showQuickAdd();
}

function showAdvancedAdd() {
	$('#advancedadd').show();
}

function processQuickAdd() {
	var params = { 'q': 'additem' };
	// Walk through the params manually and ditch null ones
	$("#quickadd_form :input[@name^='qa_']").each( function() {
	  if ( this.value.length > 0 ) {
		  params[ this.name ] = this.value;
		}
	});

	$.get( 'helper.php', params, function(data) {
		hideQuickAdd();
		$('#notifications').html(data).show();
	});
	
	return false; // cancel form submit
}
