$(document).ready(function(){
    $('#newStory').click(function(){new_form('story', 0)});
    $('#scrum_container button.newTask ').live('click', function(){new_form('task', $(this).attr('sid'));});
    delete_story();
    delete_task();
    $('div.task').draggable({
      addClasses: false,
			appendTo: 'body',
			drag: function() {$(this).css({zIndex:'1000'})},
			revert: true
      });
   dragdrop();
   taskview();
	deleteUser();
	backlog();
   //textareaGrow();
   
$('#newForm button').click(function(){
  var text = $('#newForm textarea').val();
  var mode = $(this).data('mode');
  var id = $(this).data('id');
  var owner = $('#newForm input#taskowner').val();
    $.ajax({
       type: "POST",
       url: "functions.php",
       data: "mode=new"+mode+"&id="+id+"&text="+text+'&owner='+owner,
       dataType: 'json',
       success: function(data){
        if(mode == 'story') {
          new_story(data);
        } else if(mode == 'task') {
          new_task(data);
        }
       }
     });
    $('#newForm').fadeOut().children('textarea').val('');
});
$('#cancelnew').click(function(){
  $(this).parent().hide();
});

  editStory();
	deleteUser();
	colorChange();
	displayUserTasks();
});


function new_form(mode, id) {
  $('#newForm button#submitnew').data('mode', mode);
  $('#newForm button#submitnew').data('id', id);
  $('#newForm').fadeIn().children('h2').text('new '+mode).next().focus();
	$('#newForm input').val('');
	mode == 'task' ? $('#newForm input').show():$('#newForm input').hide();
}

function new_story(data) {
 //alert(data);
  var story = $('#story_template').clone().appendTo('#scrum_container').attr('id', data.id).hide();
  story.children('td.story').children('p.storyview').text(data.text);
  story.children('td.story').children('p.storyedit').children('textarea').attr('storyid', data.id).val(data.text);
  story.children('td.newTask').children('button').attr('sid', data.id).bind('click', function() {
    new_form('task', data.id);
  });
  story.fadeIn();
}

function delete_story() {
  $('#scrum_container td.story a.delete_story').live('click', function(){
    var id = $(this).parent().parent().parent().attr('id');
    if(confirm("Delete Story "+id+" ?")) {
    $.ajax({
       type: "POST",
       url: "functions.php",
       data: "mode=deletestory&id="+id,
       success: function(data){
        $('#scrum_container tr#'+id).remove();
       }
     });
     }
     return false;
  });
}

function new_task(data) {
  $('#task_template').clone().appendTo('tr#'+data.id+' td.status_task').attr({
		id: data.tid,
		status: 'status_task',
		story_id: data.id,
		task_owner: data.owner,
		style: 'background:'+data.color
		}).hide().fadeIn('slow').draggable({snap: true}).children('p').text(data.text);
		alert(data.newuser);
		if(data.newuser) {
			alert(data.ownerid);
			$('#users ul li.usertemplate').clone().appendTo('#users ul').attr('id',data.ownerid).children('p.username').text(data.owner);
		}
		
}

function delete_task() {
  $('div.task a.delete_task').live('click', function(){
    var id = $(this).parent().attr('id');
    if(confirm("Delete Task "+id+" ?")) {
    $.ajax({
       type: "POST",
       url: "functions.php",
       data: "mode=deletetask&id="+id,
       success: function(data){
        $('#scrum_container div#'+id).remove();
       }
     });
     }
     return false;
  });
}

function dragdrop() {
    $('#scrum_container td[class*="status"]').droppable({
      accept: 'div.task',
      tolerance: 'intersect',
      addClasses: false,
      drop: function(event, ui) {
        ui.draggable.appendTo($(this)).css({top: '0', left: '0', zIndex: '0'});
        statusChange(ui.draggable, $(this));
      }
    });
}

function backlog() {
	$('#backlog').droppable({
    accept: 'div.task',
    tolerance: 'intersect',
    addClasses: false,
    drop: function(event, ui) {
      ui.draggable.appendTo($(this)).css({top: '0', left: '0'});
      statusChange(ui.draggable, $(this));
    }
  });

	$('#statusmsg a.backloglink').click(function(){
		$('#backlog').toggle();
		return false;
	});
}

function statusChange(task, story) {
  //alert('status: '+task.attr('status')+' story: '+story.attr('class'));

  if(task.attr('status') != story.attr('class')) {
    task.attr('status', story.attr('class'));
    updateTask('status', story.attr('class'), task.attr('id'));
    //alert('task: '+task.attr('status')+' status: '+story.attr('class'));
  }
  
  if(task.attr('story_id') != story.parent().attr('id')) {
		if(story.attr('class') == 'status_backlog') {
			var id = 0;
		} else {
			var id = story.parent().attr('id');
		}
    //alert('task: '+task.attr('story_id')+' status: '+story.parent().attr('id'));
    task.attr('story_id', id);
    updateTask('story', id, task.attr('id'));
  }
}

function updateTask(target, variable, id) {
  $.ajax({
    type: "POST",
    url: "functions.php",
    data: "mode=change"+target+"&var="+variable+'&id='+id,
  });
}

function updateStory(target, variable, id) {
  $.ajax({
    type: "POST",
    url: "functions.php",
    data: "mode=change"+target+"&var="+variable+'&id='+id
  });
}

function taskview() {
  $('#scrum_container').live('click', function(e){
    //alert($(e.target).attr('class'));

    if($(e.target).attr('class') == 'task' &&  $(e.target).attr('class') != 'active') {
			$(this).find('.task').removeClass('active');
      $('#taskedit').hide();
      $('#taskview').show();
      $('#task_description h2 a').show();
      $('#taskview').data('taskformatted', $(e.target).children('p').html());
      $('#taskview').data('taskraw', $(e.target).children('p').text());
			$('#taskview').data('taskowner', $(e.target).attr('task_owner'));
			
			$('#taskview p.taskdetail').html($('#taskview').data('taskformatted'));
			$('#taskview span#oname').text($('#taskview').data('taskowner'));
			
      $(e.target).addClass('active');
      makeEditable(e.target);
    } 

		
		
  });
}

function makeEditable(task) {
  
  $('#task_description h2 a').click(function(){
    $('#taskview').hide();
    $('#edittask').unbind();
    //$('#taskview').unbind();
    $('#taskedit').show().children('textarea').val($('#taskview').data('taskraw')).focus();
		$('#taskedit input[name="taskowner"]').val($('#taskview').data('taskowner')).show();
		
    $('#edittask').click(function() {
       var text = $('#task_description textarea').val();
			 var owner = $('#taskedit input[name="taskowner"]').val();
       editTask($(task).attr('id'), text, owner);
       $('#taskedit').hide();
    });

    $('#canceledit').click(function() {
       $('#taskedit').hide();
       $('#taskview').show();
    });

  });
}

function editTask(id, txt, owner) {
  $.ajax({
    type: "POST",
    url: "functions.php",
    data: "mode=edittask&id="+id+"&text="+txt+'&owner='+owner,
		dataType: 'json',
    success: function(data) {
     //$('#task_description textarea').val(txt);
      $('#taskview').data('taskraw', txt);
      $('#taskview').data('taskformatted', txt.replace(/\n/g,'<br>'));
      
      $('div#'+id+' p').html($('#taskview').data('taskformatted'));
      $('#taskview').show().children('p.taskdetail').html($('#taskview').data('taskformatted')).next('span#oname').text(data.owner);
			$('div#'+id).attr({
					task_owner: data.owner,
					style: 'background:'+data.color
			});
			
			if(data.newuser){
				$('#users ul li.usertemplate').clone().appendTo('#users ul').text(data.owner).attr('id',data.userid);
			}
      $('#statusmsg p').text('Task Updated').fadeIn().wait(1000).fadeOut();
    }
  });
}

function editStory() {

  $('.storyview').live('click', function(){
    $(this).data('origtext', $(this).text());
    //alert(h);
    
    $(this).hide();
    $(this).next('.storyedit').show().children('textarea').val($(this).data('origtext')).css({'width':'190px'}).focus();
    
    $(this).next('.storyedit').children('button.cancelstoryedit').click(function(){
      $(this).parent().hide();
      $(this).parent().prev().show();
    });
    
    $(this).next('.storyedit').children('button.editstory').click(function(){
      var txt = $(this).prev('.storytext').val();
      var txtformatted = txt.replace(/\n/g,'<br>');
      var id = $(this).prev('.storytext').attr('storyid');

      $.ajax({
        type: "POST",
        url: "functions.php",
        data: "mode=editstory&id="+id+"&text="+txt,
        success: function(data) {
        $('tr#'+id+' .storyview').html(txtformatted).show();
        $('tr#'+id+' .storyedit').hide().children('textarea').val(txt);
        $('#statusmsg p').text('Story Updated').fadeIn().wait(1000).fadeOut();
        updateHistory('story', id, 'edited', 'edited')
        }
      });
      
    });
  });
}

function textareaGrow() {
  $('textarea').bind('scroll', function() {
    $(this).css({'height':$(this).height()+5});
  });
}

function updateHistory(mode, id, event, status) {
  $.ajax({
    type: "POST",
    url: "functions.php",
    data: {
      mode: 'updatehistory',
      hmode: mode,
      id:id,
      event:event,
      status:status
     },
    success: function(data) {
    var now = new Date();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    var year = now.getFullYear();
    var h = now.getHours();
    var m = now.getMinutes();
    var time = day +'.'+month+'. '+year+'-'+h+':'+m;

      var status = mode +' '+ id +' '+ event +' status: '+status+' '+time;
      $('#history ul').prepend('<li>'+status+'</li>').hide().fadeIn();
    }
  });
}

function colorChange() {
	$('#users ul li a.usercolor').live('click', function(){
		$(this).children('span').fadeIn();
		return false;
	}); 
	
	$('#users ul li a.usercolor button').live('click', function(){
		var color = $(this).prev().val();
		var id = $(this).attr('userid');
		var username = $(this).attr('username');
		
		$.ajax({
      type: "POST",
      url: "functions.php",
      data: "mode=colorchange&id="+id+"&color="+color,
      success: function(data) {
      $('#scrum_container').find('div[task_owner="'+username+'"]').css({background:color});
			$('#users ul li[id="'+id+'"]').css({background:color});
      }
    });
$(this).parent().fadeOut();
return false;
	});
}

function deleteUser() {

$('#users ul li a.delete_user').live('click', function() {
	var id = $(this).parent().parent().attr('id');
	
	$.ajax({
    type: "POST",
    url: "functions.php",
    data: "mode=deleteuser&id="+id,
    success: function() {
    	$('#users ul li#'+id).remove();
    }
  });
})	

}

function displayUserTasks() {
	$('#users li').live('click', function(){
		$('#scrum_container').find('div[task_owner!="'+$(this).attr('username')+'"]').toggle(function(){
			$(this).css({'opacity':'0.5'});
		}, function() {
            $(this).css({'opacity':'1'});
        });
	});
}
