var accordion_options = 2;
function open_accordion(prefix, id) {
    if ($('#'+prefix+'_'+id).css('height') == '0px') {
        $('#'+prefix+'_'+id).animate({height: '283px'}, 550);
        for (i = 0; i < accordion_options; i++) {
            if (i != id) {
                $('#'+prefix+'_'+i).animate({height: '0px'}, 550);
            }
        }
    }
}

function send_ajax_request(url, data, type, onCompleteCallback) {
  if (type == '') {
    type == 'GET'
  }
  
  if (onCompleteCallback == null || onCompleteCallback == '') {
    onCompleteCallback = function(){};
  }
  
  $.ajax({
    url: url,
    dataType: "script",
    type: type,
    data: data,
    beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
    complete: onCompleteCallback
  });
  
}

function clear_errors_on(obj_type,field_array,obj_id) {
  // Only checking the month and year on the date objects
  // since that is what most of the dates consist of.
  var date_subfields = Array('1i', '2i');

  if (obj_id != null && obj_id != '') {
    dom_prefix = '#edit_'+obj_type+'_'+obj_id;
  } else {
    dom_prefix = '#new_'+obj_type;
  }

  for (field_num in field_array) {
    field = field_array[field_num];
    dom_id = dom_prefix+' #'+obj_type+'_'+field;
    
    if (field.search(/\_at$/) >= 0) {
      // This is a date object, so check each individual piece.
      for (i in date_subfields) {
        var subfield = dom_id+'_'+date_subfields[i];
        $(subfield).removeClass('field_error');
      }
    } else {    
      $(dom_id).removeClass('field_error');
    }

    $(dom_id+'_error').html('').hide();
  }
  return false;
}

function delete_file(file_id) {
  if (!confirm('Are you sure you wish to delete this file?')) {
    return false;
  }

  send_ajax_request('/documents/destroy', {id: file_id});  
  return false;
}

function validate_form_from_array(form, array) {
  var return_val = true;
  //var date_subfields = Array('1i', '2i', '3i', '4i', '5i'); // Only checking the month and year since that is what most of the dates consist of.
  var date_subfields = Array('1i', '2i'); // Only checking the month and year since that is what most of the dates consist of.

  for (field in array) {
    if (field.search(/\_at$/) >= 0) {
      // This is a date object, so check each individual piece.
      for (i in date_subfields) {
        var subfield = field+'_'+date_subfields[i];
        if (!check_field(form, subfield, array)) {
          // Manually set the error message for the containing error field
          $(form).find(field+'_error').html(array[field]);
          return_val = false;
        }
      }      
    } else {
      if (!check_field(form, field, array)) {
        return_val = false;
      }
    }
  }
  return return_val;
}

function check_field(form, field, array) {
  var field_obj = $(form).find(field);
  
  if (field_obj.val() == '') {
    field_obj.addClass('field_error');
    $(form).find(field+'_error').html(array[field]);
    return false;
  } else {
    field_obj.removeClass('field_error');
    $(form).find(field+'_error').html('');
    return true;
  }
}

function toggle_subitems_for_listing(listing_id) {
  $('#show_threads_arrow_up_'+listing_id).toggle();
  $('#show_threads_arrow_down_'+listing_id).toggle();
  $('#job_listing_messages_'+listing_id).slideToggle('fast');
}

function clear_errors_on_form(form) {
  $(form).find("div[id$='_error']").html('');
  $(form).find('.field_error').removeClass('field_error');
}

function update_characters_left(dom_object, counter_id, max_length) {
  var current_length = dom_object.value.length;
  var counter = max_length - current_length;
  
  if (current_length > max_length) {
    dom_object.value = dom_object.value.substring(0,max_length);
    counter = 0;
  }
  
  $('#'+counter_id).html(counter);
}

function disable_button(button_id) {
  $('#'+button_id).attr('disabled','disabled').attr('value','Processing').after("<img src='/images/ajax-loader.gif' border='0' style='margin-left: 10px;' />");
}

function update_search_results(obj,force) {
  var form = obj.form;
  var data_elements = Array();

  var base_field_name = obj.id.replace('_active','');
  var base_field_obj  = $(form).find('#'+base_field_name);

  if (force != true && base_field_obj.val() == '') {
    return;
  }
  
  for (i=0;i<fields.length;i++) {
    var field = fields[i];
    var field_val = $(form).find('#'+field).val();
    
    if (($(form).find('#'+field+'_active').attr('checked') == true) && (field_val != '')) {
      data_elements.push(Array('search['+field+']', field_val));
    }
  }
  
  if (data_elements.length > 0) {
    var data_hash = {};
    for (i=0;i<data_elements.length;i++) {
      data_hash[data_elements[i][0]] = data_elements[i][1]
    }
    $('#search_result_summary').hide();
    $('#search_result_listing').hide();
    $('#search_result_listing_spinner').show();
    send_ajax_request(search_url, data_hash);
  } else {
    $('#search_result_count').html('0');
    $('#search_result_listing').html('');
  }
}

function update_search_results_if_active(form, obj) {
  if ($(form).find('#'+obj.id+'_active').attr('checked') == true) {
    update_search_results(form, true);
  }
}

function spin_save_search_form() {
  $('#save_search_form').css('opacity','0.2');
  $('#save_button').attr('disabled','disabled');
  $('#cancel_button').attr('disabled','disabled');
  $('#save_spinner').show();
}

function update_slider_display(slider_name, e, ui) {
  var left_slider_val = $('#'+slider_name+'-slider').slider('value', 0);
  var right_slider_val = $('#'+slider_name+'-slider').slider('value', 1);

  $('#'+slider_name+'-value-left').html(''+(left_slider_val/10.0).toFixed(1));
  $('#'+slider_name+'-value-right').html(''+(right_slider_val/10.0).toFixed(1));  
}

function update_slider_data(slider_name, e, ui) {
  var left_slider_val = $('#'+slider_name+'-slider').slider('value', 0);
  var right_slider_val = $('#'+slider_name+'-slider').slider('value', 1);
  
  $('#'+slider_name).attr('value',(left_slider_val/10+','+right_slider_val/10));
  
  update_search_results_if_active($('#'+slider_name).get(0).form, $('#gpa').get(0));
}

function debug_object(obj) {
  var tmp = "";
  for (i in obj) {
    tmp += i + ': ' + obj[i] + "\n";
  }
  alert(tmp);
}

String.prototype.trim = function () {
  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");
};

function applyJSONErrorToForm( widgetId, errorMessage, container, showMessage, clearPreviousErrors )
{
    applyJSONErrorsToForm( '{"' + widgetId + '" : "' + errorMessage + '" }', container, showMessage, clearPreviousErrors);
}

function applyJSONGlobalErrorToForm( errorMessage, container, showMessage )
{
     applyJSONErrorToForm( "reserved_id_that_should_not_be_used", errorMessage, container, showMessage );
}

function applyJSONErrorsToForm(errors, container, showMessage, clearPreviousErrors, addAsGlobalErrorWhenCannotFindAttribute)
{
  if(clearPreviousErrors===undefined)
    clearPreviousErrors = true;
  if( undefined === addAsGlobalErrorWhenCannotFindAttribute )
    addAsGlobalErrorWhenCannotFindAttribute = true;  

  var onFocus = function(){
    var password_error_area = ($('#'+container).find(".password_error"));
    if( $(this).hasClass('error')) $(this).removeClass('error');
    if( $(this).attr('type') != 'select-one') $(this).val('');
    if( $(this).attr('type') == 'password' )  password_error_area.fadeOut(300);
    $(this).removeClass('error_msg').unbind( 'focus', onFocus );
  };
 
  // Make sure the page is in editing mode
  editing = true;
  
  // Remove any existing errors
  if(clearPreviousErrors)
    clearErrorsFor(container);

  // Default to showing the error messages, as well
  if (showMessage == null) {showMessage = true;}

  // Add any new errors
  var hash = eval('('+errors+')');
  
  for (label in hash)
  {
    var addAsGlobalError = false;
    var field_obj = $('#'+container).find('#'+label);

    if (field_obj.size() > 0)
    {
      if (showMessage)
      {
        if ( (field_obj.attr('type') == 'text') || (field_obj.attr('type') == 'textarea') ||  (field_obj.attr('type') == 'select-one') )
        {
            if(field_obj.attr('type') != 'select-one')
                 field_obj.val(hash[label]);
            field_obj.addClass('error').trigger('blur').focus( onFocus );
        }
        else if (field_obj.attr('type') == 'password')
        {
          password_error_area = ($('#'+container).find(".password_error"));
          password_error_area.removeClass('hidden').hide().fadeIn(300).html(hash[label]);
          field_obj.addClass('error').trigger('blur').focus( onFocus);
        }
        else if ((field_obj.attr('type') == 'file'))
        {
            if( 0 == $('#'+container+" #file_input").size() )
                $('<span class="error" id="file_input">Please choose a file.</span>').insertAfter(field_obj);
        }
        else
        {
          field_obj.addClass('field_error');
        }
      }
      else
      {
        if ( (field_obj.attr('type') == 'text') || (field_obj.attr('type') == 'textarea') || (field_obj.attr('type') == 'password') || (field_obj.attr('type') == 'select-one') )
          field_obj.addClass('error').trigger('blur').focus( onFocus );
        else if (field_obj.attr('type') == 'checkbox')
          field_obj.addClass('error');
        else
          field_obj.addClass('field_error');
      }
    }
    else
    {
        addAsGlobalError = addAsGlobalErrorWhenCannotFindAttribute || -1 != label.indexOf('_base');
    }

    if( addAsGlobalError && $('#'+container).find('#global_error').size() > 0 )
    {
        if( $('#'+container).find('#global_error').size() > 0 )
        {
            var currentHtml = $('#'+container).find('#global_error').html();
            if( currentHtml.length > 0 )
                currentHtml += '<br>';
            $('#'+container).find('#global_error').html(currentHtml + hash[label]).addClass('error_msg').focus( onFocus );
        }
    }
  }

  $('#'+container).find('.form_buttons').show();
  $('#'+container).find('.submit_spinner').hide();
}


function clearErrorsFor(object_id) {
  $('#'+object_id).find('.field_error').each(function() {
    $(this).removeClass('field_error');
  })

  $('#'+object_id).find('input.error, textarea.error').each(function() {
      if( $(this).hasClass('error') )
        $(this).removeClass('error').val('');
  })

  $('#'+object_id).find('span.error').each(function() {
    $(this).remove();
  })

  $('#'+object_id).find('.error').each(function() {
    $(this).removeClass('error');
  })

  $('#'+object_id).find('#global_error').html('');
}

function clearErrorMessagesFor(objectId) {
  $('#'+objectId).find('input.error').removeClass('error').val('');
  $('#'+objectId).find('textarea.error').removeClass('error').val('');
}

function applyJSONErrorsToFacebox(errors, showMessage) {
  applyJSONErrorsToForm(errors, 'facebox .popup', showMessage);
}

function hideFeedback() {
  $("#feedback_box_container").BlindUp(500);
  $('#feedback_viewer_1').removeAttr('checked');
  $('#feedback_viewer_0').attr('checked', 'checked');
  send_ajax_request('/feedback_comments/hide', {}, 'get', null);
}
function showFeedback() {
  $("#feedback_box_container").BlindDown(500);
  
  send_ajax_request('/feedback_comments/view', {}, 'get', null);
}


function closeWindow() {
  $("#new_applicant_video :input[type='textarea'], #new_applicant_video :text").attr("value", "");
  $.ajax({url:'/applicant/videos/get_updated',dataType:'script'});
  jQuery.facebox('<div class="video_thank_you"><p>Your video has been saved and appears below.  You’ll need to change the settings to let employers see it.</p></div>');
}

function hidePlayer() {
  $('#video_player_container').hide();
}

function showPlayer() {
  if (window.preventPlayerFromShowing === undefined || !(preventPlayerFromShowing === true)) {
    $('#video_message').html('');
    $('#video_player_container').show();
  }
}
  
function activateToolTipsFor(container) {
  $("#"+container+" a.tooltip_show").tooltip({
     bodyHandler: function() { 
     return $(this).next('.tooltip').html(); 
   }, 
   showURL: false
  });
  
}

function disableById(objId) {
  $('#'+objId).attr('disabled', 'disabled');
}

function enableById(objId) {
  $('#'+objId).removeAttr('disabled');
}

function toggleStateSelect(container, objType) {
  if ($('#'+container+' #'+objType+'_country_id').val() != 226) {
    $('#'+container).find('#'+objType+'_state_id').attr('disabled', 'disabled');
  } else {
    $('#'+container).find('#'+objType+'_state_id').removeAttr('disabled');
  }
}

function showSignupErrorMessages(errors, formId) {
  applyJSONErrorsToForm(errors, formId, false); 
  var hash = eval('('+errors+')');
  if (hash.applicant_email == 'This email address is already registered') {
    $('.login_fail').show();
  }
}

function disableSubmitButton(buttonId) {
  $('#'+buttonId).attr('disabled', 'disabled').hide().after($('#'+buttonId).clone().val('Please wait').attr('id', buttonId+'_disabled').show());
  return true;
}

function enableSubmitButton(buttonId) {
  $('#'+buttonId+'_disabled').remove();
  $('#'+buttonId).removeAttr('disabled').show();
  return true;
}

function addHiddenNameValuePairToForm( name, value, form_id  ){
    var hiddenNameValuePair = document.createElement("input");
    hiddenNameValuePair.type = "hidden";
    hiddenNameValuePair.name = name;
    hiddenNameValuePair.id   = value + "_id";
    hiddenNameValuePair.value = value;
    form = document.getElementById(form_id);
    form.appendChild(hiddenNameValuePair);
}

function addItemToList(containingDivId, containingListId, listElement,
                       newListItemHtml) {
  var containing_div = $('#'+containingDivId);
  var containing_list = $('#'+containingDivId + ' ' + '#' + containingListId);
  if (containing_list.size() === 0) {
    new_list_html = 
      "<" + listElement + " id=\"" + containingListId + "\">\n"
      + newListItemHtml + "\n" + "</" + listElement + ">" + "\n";
    containing_div.prepend(new_list_html);
  } else {
    containing_list.append(newListItemHtml);
  }
}

function deleteItemFromList(containingListId,itemToBeRemovedId,listItemTag) {
  $(itemToBeRemovedId).remove();
  var list_items = $('#' + containingListId + ':has(' + listItemTag + ')'); 
  if (list_items.size() === 0) {
    $('#' + containingListId).remove();
  }
}

function showTermsAndConditions()
{
    window.open( "/pages/terms_and_conditions", 'popup','width=830,scrollbars=yes,toolbar=no,directories=yes,location=yes,menubar=yes,status=no,left=0,top=0' );
}
