var SLIDE_SPEED = 500


var changed = '';


jq.fn.togglify = function(options){

  var $allToggles = jq(this);

  var defaults = {
    toggleElement: ".element",
    toggleContainer: ".elements",
    toggleClass: "toggle",
    activeClass: "active",
    onToggle: function(){}
  }

  var settings = jq.extend({}, defaults, options);

  this.each(function(){
    var $toggEle = jq(this).parents(settings.toggleElement).first();
    var $toggCont = jq(this).parents(settings.toggleContainer).first();
    var $togglee = jq(this);
    
    $toggEle.addClass(settings.toggleClass);
    
    $toggEle.bind("click", function(){
      if (!$toggEle.hasClass(settings.activeClass)) {
        $toggCont.find(settings.toggleElement).removeClass(settings.activeClass);
        $toggEle.addClass(settings.activeClass);
        
        $togglee.attr("checked", true)
        settings.onToggle.call($togglee);
      }
    });
    
    if ($togglee.is(":checked")) {
      $toggCont.find(settings.toggleElement).removeClass(settings.activeClass);
      $toggEle.addClass(settings.activeClass);
    }
    
    $togglee.hide();
  });

}

function checkVisibility($checkMe){
  if (!$checkMe.hasClass("collapsed") && !$checkMe.hasClass("empty")) {
    if ($checkMe.find(".spec_head:visible").length == 0) {
      $checkMe.addClass("invisible");
      makeDroppable($checkMe);
    } else {
      $checkMe.removeClass("invisible");
      Droppables.remove($checkMe.attr("id"));
    }
  }
}

function checkEmptiness($checkMe) {
  if ($checkMe.find(".spec").length == 0) {
    $checkMe.addClass("empty");
    $checkMe.find(".blank_slate").show();
  } else {
    $checkMe.removeClass("empty");
    $checkMe.find(".blank_slate").hide();
  }
}

function makeDroppable($droppable){
  Droppables.add($droppable.attr("id"), {
    accept: "spec",
    hoverclass: "like_its_hot",
    onDrop: function(dragged, dropped, event) {
      changed = dragged.id;
      
      $newDragged = jq(dragged).clone();
      
      specList = jq(dropped).find(".spec_list");
      
      jq(dropped).find(".spec_list").append($newDragged);
      
      iteration_id = jq(dropped).find(".spec_list").attr('id').gsub('spec_list_iteration_', '');
      formatted_update_positions_iteration_specs_ajaxx(iteration_id, 'js', 'POST',          Sortable.serialize(specList.attr("id"))+'&changed='+changed.gsub('spec_', ''));
      
      jq(dragged).remove();
    }
  });
}



//tog
function tog(clicker, toggler, callback, speed){
  if (speed == undefined) {speed = SLIDE_SPEED;}
  if (callback) {jq(clicker).click(function(){jq(toggler).slideToggle(speed, callback); return false;});}
  else {jq(clicker).click(function(){jq(toggler).slideToggle(speed); return false;});}
  

}
function togger(j, callback, speed){
  if (speed == undefined) {speed = SLIDE_SPEED}
  if(callback) {jq(j).slideToggle(speed, callback); }
  else {jq(j).slideToggle(speed); }
}

function toggle_this(caller, to_tog){
  togger(to_tog);
  var text = jq(caller).html();
  if (text == 'show iteration' || text == 'hide iteration') {
    if (jq(caller).html() == 'show iteration') {jq(caller).html('hide iteration')}
    else {jq(caller).html('show iteration')}
  }
  if (text == 'show' || text == 'hide') {
    if (jq(caller).html() == 'show') {jq(caller).html('hide')}
    else {jq(caller).html('show')}
  }
  else if (text == 'Show' || text == 'Hide') {
    if (jq(caller).html() == 'Show') {jq(caller).html('Hide')}
    else {jq(caller).html('Show')}
  }
  else {
    if (jq('img', caller).attr('src') == "/images/hide.png") {jq('img', caller).attr('src', "/images/show.png")}
    else {jq('img', caller).attr('src', "/images/hide.png")}
  }
}

jq.fn.togger = function(){
  return this.each(function(){
    jq(this).slideToggle(SLIDE_SPEED); 
  })
}

jq.fn.shower = function(){
  return this.each(function(){
    if (jq(this).is(':hidden')){ jq(this).togger()}
  })
}
jq.fn.hider = function(){
  return this.each(function(){
    if (!jq(this).is(':hidden')){ jq(this).togger()}
  })
}
//tog








jQuery.fn.center = function(){
  return this.each(function(){
    var win = jq(window).width();
    var width = jQuery(this).width();
    jq(this).css({width: width +'px', left: (win/2 - width/2) + 'px'});
  })
}







//message
function async_message(m, d){message(m, d);}
function msg(m, d){message(m, d);}
function messages(m, d){message(m, d);}
function message(message, duration){
    if (duration == undefined){ duration = 3000;}
    if (jq.browser.msie) { jq("#message").css({position: 'absolute'}); }
    jq("#message").text(message).show().center();
    setTimeout('jq("#message").hide()',duration);
    return false;
}
//message


function debug(m){if (typeof console != 'undefined'){console.log(m);}}
function puts(m){debug(m);}


function prompt_for_new_iteration(){
  return prompt('Name of new iteration?');
}
function add_iteration_to_list(){
	  var name = prompt_for_new_iteration();
	  if (name == null) { return; }
	  formatted_iterations_ajax('js', 'POST', "type=list&name=" + name, {
	    async:true, 
	    success: function(e){
//	      eval(e);
	    }
	  });
}








function initSpecSortables(){
	var ids = [];
	jq('.spec_list').each(function(){ids.push(jq(this).attr('id'))});
	jq('.spec_list').each(function(){
	  Sortable.create(jq(this).attr('id'), {
	    dropOnEmpty: true,
	    handle: 'handle',
	    containment: ids,
	    tag: 'div',
	    only: 'spec',
	    onUpdate: function(el){
		    iteration_id = jq(el).attr('id').gsub('spec_list_iteration_', '');
		    formatted_update_positions_iteration_specs_ajaxx(iteration_id, 'js', 'POST',          Sortable.serialize(el)+'&changed='+changed.gsub('spec_', ''));
		    checkVisibility(jq(el).parents(".iteration"));
		    checkEmptiness(jq(el).parents(".iteration"));
	    },
	    onChange: function(el){
		    changed = el.id;
	    }
	  })
	});
}


function initSpecOptions(){
  jq('.spec_options').unbind('change.spec_options').bind('change.spec_options', function(){
    var data = jq(this).metadata();
    var id = data.id;
    var iteration_id = data.iteration_id;
//    var format = data.alt == 'true' ? 'script' : js
    switch (jq(this).selectedValues()[0]){
      case "Estimate": 
        tb_show('Estimate', new_spec_estimate_ajaxx(id) + "?height=200&width=300");
      break;
      case "Delete": 
        if (confirm('Are you sure you want to delete this spec?')){
          formatted_iteration_spec_ajaxx(iteration_id, id, 'js', 'delete');
        }
        break;
      case "Move": 
        formatted_move_iteration_spec_ajaxx(iteration_id, id, 'js', 'POST');
        break;
      case "Watch": 
        formatted_watch_spec_ajaxx(id, 'js', 'POST');
        break;
      case "Unwatch": 
        formatted_unwatch_spec_ajaxx(id, 'js', 'POST');
        break;
    }
    jq(this).selectOptions("");
  })
}


function stickySortables(){
	var ids = [];
	jq('.sticky_column').each(function(){ids.push(jq(this).attr('id'));});
	jq('.sticky_column').each(function(){
	  Sortable.create(jq(this).attr('id'), {
	    dropOnEmpty: true, 
	    containment: ids, 
	    tag: 'div', 
	    only: 'sticky', 
	    scroll: window, 
	    onUpdate: function(el){
		    var spec = formatted_update_sticky_project_iteration_ajax(jq(el).attr('project_id'), jq(el).attr('iteration_id'), 'json', 'POST', 'changed='+changed+'&bottom='+bottom+'&top='+top+'&status='+status);
		    jq('#spec_'+spec.id).removeClass('high medium low').addClass(spec.html_class);
	    },
	    onChange: function(el){
		    status = jq(el).parent('.sticky_column').attr('status_id');
    		if (jq(el).next('.sticky').size() == 0) { bottom = ''}
    		else {	bottom = jq(el).next('.sticky').attr('id').gsub('spec_', '');	}
    		if (jq(el).prev('.sticky').size() == 0) {top = ''}
    		else {	top = jq(el).prev('.sticky').attr('id').gsub('spec_', '');}
		    changed = jq(el).attr('id').gsub('spec_', '');
	    }
	  })
	});
}


function initProject() {
	initSpecSortables();
	initSpecOptions();
	try {tb_init('a.thickbox, area.thickbox, input.thickbox');} catch(e){}
	
  jq(".inline_iteration_name").each(function(){
    var iter = jq(this);
    var data = iter.metadata();
    //var data = {
    //  project_id: jq(this).parents(".spec_sortable").attr("id").gsub("project_"),
    //  id: jq(this).parents(".iteration").attr("id").gsub("iteration_")
    //}
    iter.editable(formatted_edit_name_project_iteration_path(data.project_id, data.id, 'js'), { 
      cancel    : 'Cancel',
      submit    : 'Save',
      indicator : "Saving....",
      tooltip   : 'Click to edit...'//,
//      callback  : function(){alert('x');}
    })
  }).hover(function(){jq(this).css({background: '#ff9'})}, function(){jq(this).css({background: ''})});
    
	jq(".inline_project_name").each(function(){
		var proj = jq(this);
		var data = proj.metadata();
		proj.editable(formatted_edit_name_project_path(proj.id, 'js'), {
      cancel    : 'Cancel',
      submit    : 'Save',
      indicator : "Saving....",
      tooltip   : 'Click to edit...'
		})
	}).hover(function(){jq(this).css({background: '#ff9'})}, function(){jq(this).css({background: ''})});
	
	hide_all_hidden();
}

function new_project_link(just_create){
//	jq('#new_project_link').unbind('click.new_project_link').bind('click.new_project_link', function(){
		var name = prompt('Name of new project?');
		if (name == null) {return;}
		if (name == ''){
		  msg('Project title is required.')
		  return;
		}
		formatted_projects_ajaxx('script', 'POST', 'project[name]='+name + "&just_create=" + just_create);
//  });
}








jq.fn.less_tabs = function(){
  return this.each(function(){
    var tabs = jq("a", this);
    var div_ids = [];
    tabs.each(function(i, a){div_ids.push(a.href.split('#')[1]);});
    div_ids.each(function(d, i){
      var anchor = window.location.href.replace(/^.*\#/,'')
      if (jq(tabs.get(i)).is('.on,.viewing') || anchor == d || anchor == d.replace(/tab_/,'')  ){
        jq(tabs).removeClass('on').removeClass('viewing');
        jq('#' + div_ids.join(',#')).hide();
        jq('#'+ jq(tabs.get(i)).get(0).href.split('#')[1]).show();
        jq(tabs.get(i)).addClass('on').addClass('viewing');
        return false;
      }
      if (i == 0) {jq('#' + d).show(); jq(tabs.get(i)).addClass('on').addClass('viewing');}
      else { jq('#' + d).hide(); jq(tabs[i]).removeClass('on').removeClass('viewing'); }
      })
    tabs.each(function(i,a){
      jq(a).bind('click.less_tabs', function(){
        jq(tabs).removeClass('on').removeClass('viewing');
        jq(this).addClass('on').addClass('viewing');
        jq('#' + div_ids.join(',#')).hide();
        jq('#'+ a.href.split('#')[1]).show(); 
        return false;})
    })
  })
}











function toggle_form(id){
  jq('#' + id).slideToggle(SLIDE_SPEED).get(0).reset();
  try{}
  catch (e) {}
}










//people form
jQuery.fn.extend({
	show_select_or_message : function() {
		return this.each(function() { 		
			if (jq(this).find('option').length > 0) {
				jq(this).siblings('.no_more_people').hide();
				jq(this).show();
				jq(this).siblings('.add_button').show();
			} else {
				jq(this).siblings('.no_more_people').show();
				jq(this).hide();
				jq(this).siblings('.add_button').hide()
			}
		});
	}
})

function invited_person(person){
  toggle_form('new_person_adder');
  jq('.people_select_for_projects').addOption(person.id, person.f, true).show_select_or_message();
}

function remove_project(project_id, dom_id){
  jq('#' + dom_id).remove();
  jq('#project_select').removeOption(project_id+'');
  if (jq('#project.' + project_id).size() > 0){
    jq('#project.' + project_id).empty();
    jq('#project_select').change();
  }
  //jq('#header').empty();
}


function remove_person(person){
  jq('#person_list_person_' + person.id).remove();
  jq('.people_select_for_projects').removeOption(person.id+'').show_select_or_message();
  jq('.person_in_project_list_' + person.id).remove();
}

function add_to_project(membership){
  jq('.people_select_for_project_' + membership.project_id).removeOption(membership.person_id+'')
  jq('.people_select_for_projects').show_select_or_message();
}

function remove_from_project(project, person){
  jq('.people_select_for_project_' + project.id).addOption(person.id, person.f, true);
  jq('.people_select_for_projects').show_select_or_message();
  jq('#in_project_list_' + project.id + '_person_' + person.id).remove();
}


//people form






function close_drawers(obj){
  tb_remove();
}

/* Filters & stuff */

var filters_status = [];

function toggle_filters(check_id) {
  switch(check_id) {
    case "all_filter":
      jq('.completed').removeClass('completed_hidden');
      filters_status['completed'] = true;
      break;
    case "unfinished_filter":
      jq('.completed').addClass('completed_hidden');
  		jq('.completed').parents(".spec").removeClass("expanded");
  		jq('.completed').parents(".spec").find(".spec_content").remove();
  		filters_status['completed'] = false;
      break;
    case "everyone_filter":
      jq('.not_mine').removeClass('not_mine_hidden');
      filters_status['everyone'] = true;
      break;
    case "yours_filter":
      jq('.not_mine').addClass('not_mine_hidden');		
  		jq('.not_mine').parents(".spec").removeClass("expanded");
  		jq('.not_mine').parents(".spec").find(".spec_content").remove();
  		filters_status['everyone'] = false;
      break;
  }
  jq(".iteration").each(function(){
    $iteration = jq(this);
    //setTimeout(function(){
      checkVisibility($iteration);
      //}, 2000);
    
  });
}



function toggle_finished() {
  jq("input[name=specs_status]").each(function(){
    if (jq(this).is(":checked")) {
      check_id = jq(this).attr("id");
      toggle_filters(check_id);
    }
  });
	/* current_text = jq('#finished_question').text();
	if (current_text == "finished and unfinished") {
		jq('#finished_question').text("unfinished");
		jq('.completed').addClass('completed_hidden');
		jq('.completed').parents(".spec").removeClass("expanded");
		jq('.completed').parents(".spec").find(".spec_content").remove();
	} else {
		jq('#finished_question').text("finished and unfinished");
		jq('.completed').removeClass('completed_hidden');
	} */
};

function toggle_mine() {
  jq("input[name=specs_to_show]").each(function(){
    if (jq(this).is(":checked")) {
      check_id = jq(this).attr("id");
      toggle_filters(check_id);
    }
  });
	/* current_text = jq('#mine_question').text();
	if (current_text == "everyone's") {
		jq('#mine_question').text("your");
		jq('.not_mine').addClass('not_mine_hidden');		
		jq('.not_mine').parents(".spec").removeClass("expanded");
		jq('.not_mine').parents(".spec").find(".spec_content").remove();
	}	else {
		jq('#mine_question').text("everyone's");
		jq('.not_mine').removeClass('not_mine_hidden');
	} */
};

function hide_if_necessary(spec_id) {
	spec = '#' + spec_id;
	jq(spec).addClass('completed');
	toggle_finished();
	if (filters_status["completed"] == false) {
		jq(spec).addClass('completed_hidden');
	}
};




















function hide_all_hidden() {
  toggle_finished();
  toggle_mine();
  
  
  /*
	if (jq('#mine_question').text() == "everyone's") {
		jq('.not_mine').removeClass('not_mine_hidden');
	}	else {
		jq('.not_mine').addClass('not_mine_hidden');		
	}
	
	if (jq('#finished_question').text() == "finished and unfinished") {		
		jq('.completed').removeClass('completed_hidden');			
	} else {
		jq('.completed').addClass('completed_hidden');					
	}	 */
}

function load_spec_content(s, spec_data) {
  spec_id = s.attr("id").substr(5);  
  
  s.append("<div class='spec_content'>" + spec_data + "</div>");
  s.addClass("expanded");
  // Globalize the onChange for the specs details

}

/*
jq(".inline_spec_name").each(function(){
  var iter = jq(this);
  var data = iter.metadata();
  iter.editable(formatted_edit_name_spec_path(data.id, 'js'), { 
    cancel    : 'Cancel',
    submit    : 'Save',
    indicator : "Saving....",
    tooltip   : 'Click to edit...'
  })
}).hover(function(){jq(this).css({background: '#ff9'})}, function(){jq(this).css({background: ''})});*/



//startup
jq(function(){
	jQuery("#waiter").ajaxStart(function(){jq(this).show();}).ajaxStop(function(){jq(this).hide();}).ajaxError(function(){jq(this).hide();});
	
//	hide_all_hidden();
	jq('#project_select').change(function(){
		if (jq(this).val() == '0') {
			formatted_all_projects_ajaxx('js', 'GET');
		} else {
			formatted_project_ajaxx(jq(this).val(), 'js', 'GET');
		}
	});
	
  
  jq('#business_select').bind('change.change_business', function(){
   var sel = jq(this);
   window.location = sel.val()
  });
	
	initProject();
	
	jq('.less_tabs').less_tabs();
	
	jq('#businsess_clicker').click(function(){close_drawers('#control_business');})
	
	jq('.spec .priority_id').live("change", function() {
	  iteration_id = jq(this).parents(".iteration").attr("id").substr(10);
	  spec_id = jq(this).parents(".spec").attr("id").substr(5);
    formatted_attribute_update_spec_ajaxx(spec_id, 'js', 'POST', {'priority_id':jq(this).val(), 'iteration_id':iteration_id}); 
  });

  jq('.spec .assigned_to_id').live("change", function() {
    iteration_id = jq(this).parents(".iteration").attr("id").substr(10);
	  spec_id = jq(this).parents(".spec").attr("id").substr(5);
    formatted_attribute_update_spec_ajaxx(spec_id, 'js', 'POST', {'assigned_to_id':jq(this).val(), 'iteration_id':iteration_id}); 
  });

  jq('.spec .iteration_id').live("change", function() {
    iteration_id = jq(this).parents(".iteration").attr("id").substr(10);
	  spec_id = jq(this).parents(".spec").attr("id").substr(5);
    formatted_attribute_update_spec_ajaxx(spec_id, 'js', 'POST', {'new_iteration_id':jq(this).val(), 'iteration_id':iteration_id}); 
  });

  jq('.spec .status_id').live("change", function() {
    iteration_id = jq(this).parents(".iteration").attr("id").substr(10);
	  spec_id = jq(this).parents(".spec").attr("id").substr(5);
    formatted_attribute_update_spec_ajaxx(spec_id, 'js', 'POST', {'status_id':jq(this).val(), 'iteration_id':iteration_id}); 
  });
	
	jq(".spec_title a, a.collapse").live("click",function(){
    $this = jq(this);
    if (!$this.parents(".spec").hasClass("expanded")) {
      jq.ajax({
        url: $this.attr("href"),
        success: function(data) {
          load_spec_content($this.parents(".spec"), data);
          $this.parents(".spec").find(".new_comment").bind("submit", function(){
            jq(this).find("textarea").val("");
          });
        }
      });
    } else {
      jq(this).parents(".spec").removeClass("expanded");
      jq(this).parents(".spec").find(".spec_content").remove();
    }

    return false;
  });
  
  jq(".section h2").live("click", function(){
    $parent = jq(this).parents(".section");
    if (!$parent.hasClass("collapsed")) {
      $parent.addClass("collapsed");
    } else {
      $parent.removeClass("collapsed");
    }
  });
  
  jq(".status span a.trigger_status").live("click", function(event){
    $parent = jq(this).parents(".status");
    if (!$parent.hasClass("expanded")) {
      $parent.addClass("expanded");
    } else {
      $parent.removeClass("expanded");
    }
    return false;
  });
  
  jq(".statuses_list li").live("click", function(){
    $spec = jq(this).parents(".spec");
    $iteration = $spec.parents(".iteration");
    $parent = jq(this).parents(".status");
    
    formatted_attribute_update_spec_ajaxx($spec.attr("id").substr(5), 'js', 'POST', {'status_id':jq(this).attr("id").substr(7), 'iteration_id':$iteration.attr("id").substr(10)});
    
    $parent.removeClass("expanded");
  });
  
  jq(".dropdown").each(function(){
    widthToFit = jq(this).find(".title_wrap").innerWidth();
    jq(this).width(widthToFit);
    
    if (widthToFit >= 200) {
      jq(this).find(".content").width(widthToFit + 40);
    }    
  });

  jq(".dropdown .title").click(function(){
    dd = jq(this).parents(".dropdown");
    if (dd.hasClass("expanded")) {
      dd.removeClass("expanded");
    } else {
      jq(".dropdown.expanded").removeClass("expanded");
      dd.addClass("expanded");
    }
    
    return false;
  });
  
  jq(".iteration.collapsed").each(function(){
    makeDroppable(jq(this));
  });
	
	jq(document).bind("click", function(){
    jq(".dropdown").removeClass("expanded");
  });
  
  jq(".dropdown .content").bind("click", function(e){
    e.stopPropagation();
  });
  
  jq(".reply_btn").live("click", function(){
    jq(this).parents("li").first().find(".new_comment").bind("submit", function(){
      jq(this).find("textarea").val("");
    });
  });
  
  jq(".new_comment").bind("submit", function(){
    
  });
	
})
//startup

function wysiwyg() {
  jq('.wysiwyg').wysiwyg({controls : {separator04 : { visible : true }, insertOrderedList : { visible : true }, insertUnorderedList : { visible : true }}}); 
}