
var jq = jQuery.noConflict();;


/***********************/
/* Custom JS Functions */
/***********************/

function handle_alias(skill,alias) {
  // Define Ajax call components
  var action = '/manage/'+ (alias == '' ? 'remove' : 'add') +'_skill_alias'; // If alias is empty, call remove. Otherwise, add.
  var data = { alias_key: jq('.skill-name', skill).attr('title'), alias_value: alias }
  var callback = function (json) { update_skill_name(skill,json); update_project_container(); } // Update the skill name and project container
  var type = 'json';

  //if (jq('.skill-name', skill).text() != alias) { // If the alias is different from the current skill name
    jq('input', skill).attr('readonly',''); // Disable the input field
    jq.post( action, data, callback, type ); // Make Ajax call
 // } else {
  //  cancel_alias(skill);
  //}
}

function update_skill_name(skill,json) {
  var skill_name = jq('.skill-name', skill);

  // Update text in skill pill
  //console.log('removing alias');
  jq('input', skill).remove();
  skill_name.text((json.alias ? json.alias : json.origin)).show();
  skill.removeClass('alias-pill');
 // console.log('alias removed');
  
  // Revert titles for skill pill controls
  change_pill_control_titles(skill);

  // Populate and show flash message for 5 seconds
  jq('.flash_notice').text(json.message).fadeIn('fast');
  setTimeout("jq('.flash_notice').fadeOut('slow')", 5000);
}

function cancel_alias(skill) {
  jq('input', skill).remove();
  jq('.skill-name', skill).show();
  skill.removeClass('alias-pill');
  change_pill_control_titles(skill);
}

function change_pill_control_titles(skill) {
  if (skill.hasClass('alias-pill')) {
    titles = { 'positive': 'Save alias', 'negative': 'Delete alias' };
  } else {
    titles = { 'positive': 'Rename', 'negative': 'Remove' };
  }

  jq('.positive',skill).attr('title', titles['positive']);
  jq('.negative',skill).attr('title', titles['negative']);
}

/* Draggable/Droppable Elements */



/* Admin Portal: Editing Items */

function create_item(form, type) {
  formatted_type = type.replace(/_(\w)/g, function (m) { return m[1].toUpperCase(); });
  var container = jq(formatted_type+'List .active ul')
  var clone = jq('li', container).clone();
  var parent = jq('#' + ('emp_' + type).replace(/_(\w)/g, function (m, $1) { return $1.toUpperCase(); })+'s');
  jq.ajax({
    type: 'post',
    url: jq(form).attr('action'),
    data: jq(form).serialize(),
    success: function(data){
      jq('.module-notice', parent).text('New '+type.replace('_',' ')+' added').show();
      window["refresh_" + type + "s"]();
      setTimeout( function(){ jq('.module-notice', parent).fadeOut('slow') }, 5000 );
    },
    error: function(data){
      jq('.module-error', parent).text('This appears to be a duplicate '+type.replace('_',' ')+'.').show();
      setTimeout( function(){ jq('.module-error', parent).fadeOut('slow') }, 5000 );
    }
  });
}

function edit_item(form, type) {
  jq.post( jq(form).attr('action'),
    jq(form).serialize(),
    function(data){
      jq('#titleStatus').text('Edited '+type);
      window["refresh_" + type + "s"]();
    }
  );
}

function cancel_edit(item) {
  var parent = jq(item);
  var name = parent.find('.item-name');
  var edit_link = parent.find('.edit');
  var form = parent.find('form');

  form.hide();
  form.find('.edit-item').empty();
  edit_link.show();
  name.show();
}

function update_item_name(item, name){
  jq(item).text('name');
}

function change_item_status(item, status) {
  var active = ( status == 'active' ? true : false );
  var type = jq(item).closest('.module-content').attr('id').replace(/[s]$/, '');
  var item_name = jq('.item-name', item).text();
  var item_id = jq('.item-id', item).val();
  var formatted_type = type.replace(/_(\w)/g, function (m, $1) { return $1.toUpperCase(); });
  var destination = jq('#'+formatted_type+'List').find('.'+status+' ul');
  var object = '';

  if (type == 'location' || type == 'admin_task') {
    object = to_id(item);
  } else if (type == 'title' || type == 'division' || type == 'role') {
    object = item_id;
  } 

  jq.post('/admin/set_object_status', { 'object': object, 'type': type, 'status': active });
  jq(item).appendTo(destination);
}

function init_default_values() {
  jq('.label').each(function(){
    jq(this).val(this.defaultValue);
  });
}

function refresh_locations() {
  var list_element = jq('#locationList');
  var list_partial = '/admin/location_list';
  var form_element = jq('#addLocationContainer');
  var form_partial = '/admin/edit_location';

  list_element.load(list_partial);
  form_element.load(form_partial);
}

function refresh_admin_tasks() {
  var list_element = jq('#adminTaskList');
  var list_partial = '/admin/admin_task_list';
  var form_element = jq('#addAdminTaskContainer');
  var form_partial = '/admin/edit_admin_task';

  list_element.load(list_partial);
  form_element.load(form_partial);
}

function refresh_titles() {
  var list_element = jq('#titleList');
  var list_partial = '/admin/title_list';

  list_element.load(list_partial);
}

function refresh_divisions() {
  var list_element = jq('#divisionList');
  var list_partial = '/admin/division_list';

  list_element.load(list_partial);
}

function toggle_utilization() {
  var utilization_value = jq('#current_utilization');
  var form = jq('#utilization_form');
  var input = form.find('#target_setting_full_time_utilization');
  var edit_link = jq('#utilization .edit')

  if (utilization_value.is(':visible')) {
    utilization_value.hide();
    form.css('display','inline');
    edit_link.text('save');
  } else {
    form.hide();
    utilization_value.text(input.val());
    utilization_value.show();
    edit_link.text('edit');
  }
}

// Set skill importance
function set_skill_importance(skill, weight){  
  if (weight == 0 || weight == 10 || weight == 33 || weight == 66 || weight == 100) {

    var project = skill.closest('.project');
    var project_id;
    try{
      project_id = project.attr('id').split("_")[1];
    } catch (exc){
      project_id = jQuery('#task_profile_id').text();
    }

    jq.post( '/manage/update_req_usage',
      { 'id': project_id, 'skill_req_id': to_id(skill), 'skill_weight': weight }
    );
    //update the skill pill display
    
    var star_count = "";    
    switch (weight){
      case "10":
        star_count = "1";
        break;
      case "33":
        star_count = "2";
        break;
      case "66":
        star_count = "3";
        break;
      case "100":
        star_count = "4";
        break;
      default:
        star_count = "0";
        break;
    }        
    var div_to_update = skill.children(".importance");
    skill.removeClass('unimportant');
    div_to_update.removeClass("dropdown");
    div_to_update.removeClass("stars-0");
    div_to_update.removeClass("stars-1");
    div_to_update.removeClass("stars-2");
    div_to_update.removeClass("stars-3");
    div_to_update.removeClass("stars-4");

    div_to_update.addClass("stars-"+star_count);
  }
}



/////////////////////
// EXTRA UTILITIES

// Extracts digits from the end of a string
function to_id(s){
  string = jq(s).attr('id');
  var regex = /[0-9]+$/;
  return string.match(regex)[0];
}



/**********************************/
/* After the DOM has fully loaded */
/**********************************/

jq(document).ready(function(){

  jq('.module .inactive li').livequery(function(){
    jq(this).draggable({
      appendTo: '#dragging_skill',
      helper: 'clone',
      revert: 'invalid',
      scroll: false
    });
  });

  jq('.module .active').livequery(function(){
    jq(this).droppable({
      accept: '.inactive li',
      hoverClass: 'droppable-hover',
      drop: function(event, ui) {
        change_item_status(ui.draggable, 'active');
      }
    });
  });

  // Active items
  jq('.module .active li').livequery(function(){
    jq(this).draggable({
      appendTo: '#dragging_skill',
      helper: 'clone',
      revert: 'invalid',
      scroll: false
    });
  });

  jq('.module .inactive').livequery(function(){
    jq(this).droppable({
      accept: '.active li',
      hoverClass: 'droppable-hover',
      drop: function(event, ui) {
        change_item_status(ui.draggable, 'inactive');
      }
    });
  });

  // Initialize default values
  init_default_values();

  // Add rounded corners to all .round buttons
  DD_roundies.addRule('.button-input', '9px', true);
  DD_roundies.addRule('.round', '9px', true);

  // Use a text field's default value as label
  jq('.label').live('focus', function(){
    var def = this.defaultValue;
    var val = jq(this).val();

    jq(this).removeClass('default_value');

    if (val == def) {
      jq(this).val('');
    } else {
      jq(this).select();
    }
  });

  jq('.label').live('blur', function(){
    var def = this.defaultValue;
    var val = jq(this).val();

    if (val == def || val == '') {
      jq(this).addClass('default_value');
      jq(this).val(def);
    }
  });

  // Positive project control button is clicked
  // Temporary controls until transition
  jq('.project-details').live('click', function(){
    var project = jq(this).closest('li');
    var details = project.find('.details');

    if (details.is(':hidden')) {
      details.fadeIn('fast');
    } else {
      details.fadeOut('fast');
    }
    return false;
  });

  jq('.project_details').click(function(){
    var project = jq(this).closest('li');
    var project_id = project.attr('id').replace('project_', '');
    jq('li.project').removeClass('selected');
    project.addClass('selected');

    jq.get('/ep/get_project_details_obw/' + project_id);
  });

  // Negative project control button is clicked
  jq('.projects .negative').live('click', function(){
    var project = jq(this).closest('li');
  });

  // Admin Portal: Company Settings
  jq('h3, .inactive li, .active li', '.module').disableSelection();

  jq('#event_alerts h3').click(function(){
    jq('#event_alerts_content').slideToggle('fast', function(){
      jq('#toggle_alerts').text((jq('#event_alerts_content').is(':visible') ? 'hide' : 'show') + ' alerts');
    });
  });

  jq('.module h3').toggle(function(){
    jq(this).closest('.module').find('.module-content').hide();
    jq(this).closest('.module').addClass('module-collapsed');
  }, function(){
    jq(this).closest('.module').find('.module-content').show();
    jq(this).closest('.module').removeClass('module-collapsed');
  });



  /////////////////////
  // CREATE NEW ITEM

  // Click: Submit new item
  jq('.create-new-item').live('click', function(){
    var parent = jq(this).closest('div:not(.header)');
    var list = parent.find('.list');
    var type = jq(this).closest('.module-content').attr('id').replace(/[s]$/, '');
    var form = jq(this).closest('.header').find('form');
    // console.log(form);
    create_item(form, type);
  });

  // KeyUp: Submit new item
  jq('.new-item').live('keyup', function(event){
    var parent = jq(this).closest('div:not(.header)');
    var list = parent.find('.list');
    var type = jq(this).closest('.module-content').attr('id').replace(/[s]$/, '');
    var form = jq(this).closest('form');
    var key = event.keyCode;
    switch (key) {
      case 13: // Enter key - call save_item()
        // console.log(form);
        create_item(form, type);
      break;
    }
  });

  ///////////////
  // EDIT ITEM

  // Click: edit item link
  jq('.module .edit-inline').live('click', function(){
    var parent = jq(this).closest('li');
    var name = parent.find('.item-name');
    var edit_link = parent.find('.edit');
    var form = parent.find('form');

    name.hide();
    edit_link.hide();
    form.find('.edit-item').val(name.text());
    form.find('.edit-item').focus();
    form.show();
    // 'edit', :url => { :action => 'edit_title', :id => title }, :html => { :class => 'edit edit_inline' }, :update => 'addTitleContainer', :complete => "$('addTitleContainer').show()"
    return false;
  });

  // Click: submit inline edit
  jq('.module .submit-item').live('click', function(){
    var parent = jq(this).closest('li');
    var type = jq(this).closest('.module-content').attr('id').replace(/[s]$/, '');
    var form = parent.find('form');

    edit_item(form, type);
    return false;
  });

  // KeyUp: Escape key in edit item
  jq('.edit-item').live('keyup', function(event){
    var parent = jq(this).closest('li');
    var type = jq(this).closest('.module-content').attr('id').replace(/[s]$/, '');
    var form = parent.find('form');
    var key = event.keyCode;

    switch (key) {
      case 13:
        edit_item(form, type);
      break;
      case 27:
        cancel_edit(parent);
      break;
    }
    return false;
  });

  jq('#utilization .edit').live('click', function(){
    if (jq(this).text() == 'save') {
      jq.post( this.action, jq(this).serialize(), function(){ toggle_utilization(); } );
    } else if (jq(this).text() == 'edit') {
      toggle_utilization();
    }
    return false;
  });

  // Submit: Utilization field
  jq('#utilization_form').live('submit', function(){
    jq.post( this.action, jq(this).serialize(), function(){ toggle_utilization(); } );
  });

  // Browser incompatibility warning
  jq('#hide_browser_warning').click(function(){
    jq.cookie('browser_warning_given', true, { path: '/' });
    jq('#browser_warning').hide();
    return false;
  });

  //////////////////
  // MANAGER PORTAL

  // Submit: Resource Search form (/manage/resource_search)
  jq('#resource_search_page #resource_search').submit(function() {
    jq.ajax({
      type: 'GET',
      url: this.action,
      data: Form.serialize(this),
      success: function(data){
        jq('#resource_search_results').html(data);
      },
      dataType: 'html'
    });
    return false;
  });

  // Submit: Resource Search form (/manage/task_overview/:id)
  jq('#taskColumns #resource_search').submit(function() {
    jq.ajax({
      type: 'GET',
      url: '/manage/search_for_resource',
      data: Form.serialize(this),
      success: function(response_data){
        //alert("response data is" + response_data);
        var str =  '<div class=\'tablewrap_newSkin\'  id=\'task_matches_wrapper\'>' + response_data + '</div>';
        
        var el = jq('#task_matches_wrapper')
        
        el.replaceWith(str);
        
        replaceText('Now');
        
      },
      dataType: 'html'
    });
    return false;
  });

  // Click: Skill importance selection
  jq('#reqTask_table li .star-rating').live('click', function(){
    skill = jq(this).closest('li');
    weight = jq(this).find('a').text();
    set_skill_importance(skill, weight);
  });

  // Click: Cancel skill importance selection
  jq('#reqTask_table li .rating-cancel').live('click', function(){
    skill = jq(this).closest('li');
    set_skill_importance(skill, 0);
  });


});
