// to enable.disable submit button based on tnc check during signup
function enable_submit()
  {      
    tnc = $('#account_tnc_accepted')[0];
    if(tnc.checked == true)       
      $('#sign_up')[0].disabled = false;
    else  
      $('#sign_up')[0].disabled = true;
  }
  
function add_error_class()
  {
    $('div.fieldWithErrors').each(function(index, ele){ if(ele.parentNode.tagName == "DIV") ele.parentNode.className += ' error' });
  }
  
function toggle_all_checks(klass, state)  
{
  $('.'+klass).each(function(index,ele){ele.checked = state})
}
  
function not_valid_email(email)
{
  return !(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email));
}

// this needs to removed and replaced with check_list
function add_to_list(check_box)
{ 
  if(check_box.checked)
    temp_recipients.push(parseInt(check_box.value));
  else  
    temp_recipients.splice(temp_recipients.indexOf(parseInt(check_box.value)), 1);
 
  //get_list();
}
function get_list()
{ 
  $('#recipients_list').html("")
  
  $.each(temp_recipients, function(i, n) { $('#recipients_list').html($('#recipients_list').html() + recruits[two_d_array_index(recruits, n)][1] + ", ") })
  
  $('#recipients').val(temp_recipients);
  $('#recruit_ids').val(temp_recipients);
}

function select_all_recruits(check_box)
{
  $('.check_boxes').each(function(index, ele) { ele.checked = check_box.checked; add_to_list(ele)});
}

function two_d_array_index(arr, match)
{  
  $.each(arr, function(i, n) { if(n.indexOf(match) != -1) index = i })
  return index;
}

function load_email(email)
{
  $('#interaction_to').val(email);
}

// return search url appending id to it
function get_search_page(url, select_box_id)
{ 
  url += "?user_id=" + selected_element(select_box_id);
  return url;
}

// get selected element from the select options
function selected_element(select_box_id)
{
  select_box = $("#"+select_box_id)[0];
  return select_box.options[select_box.selectedIndex].value;
}

function toggle_ratings()
{
  if(only_ratings)
    {
    $("tr.historyrow").show();
    only_ratings = false;
    }  
  else  
    {  
    $("tr.non_rating").hide();
    only_ratings = true;
    }
}

function check_list(check_box)
{ 
  if(check_box.checked)
    temp_recipients.push(parseInt(check_box.value));
  else  
    temp_recipients.splice(temp_recipients.indexOf(parseInt(check_box.value)), 1);
 
  $('#recipients_list').html("");
  
  if($('#recipients_list').length > 0)
  $.each(temp_recipients, function(i, n) { $('#recipients_list')[0].innerHTML +=  collection[two_d_array_index(recruits, n)][1] + ", "; })
  
  $('#selected_ids').val(temp_recipients);  
}

function toggle_all_check_boxes(check_box) 
{
  if(check_box.checked)
    temp_recipients = collection_ids;
  else
    temp_recipients = [];    
  $('.check_boxes').each(function(index, ele) {ele.checked = check_box.checked ? 1 : 0});
  $('#selected_ids').val(temp_recipients);
}


function atleast_one_selected(check_box_class) 
{ 
  selected = []; 
  $('.' + check_box_class).each(function(index, checkbox) { if(checkbox.checked) selected.push(checkbox.checked); });  
  return(selected.length > 0);
}

function mass_assign_checks(ele)
{
  if(!atleast_one_selected('check_boxes'))
    push_error_message('mass_assign_msg', 'You must select atleast one recruit.');
  else if(!atleast_one_selected('user_id_check_box'))  
    push_error_message('mass_assign_msg', 'You must select atleast one Coach');
  else  	
  	return true;    
  return false;  
}

function assign_checks(ele)
{	
  push_ok_message('assign_msg', 'Looks like everything went OK! Yay!')
}

function push_error_message(id, msg)
{
  $("#" + id).html("<div id='errorMsg'><h3>Ooops! something wasn't right</h3><p>" + msg + "</p></div>")
}

function clear_message(id)
{
  $("#" + id).html('')
}

function push_ok_message(id, msg)
{
  $("#" + id).html("<div class='OKMsg'><p>" + msg + "</p></div>")
  
}

function after_mass_assign_submit(remove_dialog_after_highlight)
{
  clear_message('mass_assign_msg');   
  if(remove_dialog_after_highlight) {    
    push_ok_message('mass_assign_msg', 'Assigned successfully');
    $('#mass_assign_dialog').effect("highlight", {}, 3000, 
    function() { 
      clear_message('mass_assign_msg'); ;
      $('#mass_assign_dialog').dialog('close');       
    });}
  else  
    $('#mass_assign_dialog').dialog('close');
}

function show_flash_msg_and_close_dialog_box()
{
    $('.selector').effect("highlight", {}, 3000, 
    function() {$('.selector').dialog('close');});
}

function add_date_picker(ele)
{
  $("#" + ele).datepicker({ dateFormat: 'yy-mm-dd' });  
}

function preserve_sort_order()
{  
  if($('.headerSortUp').length == 0){
    order='ASC'; 
    sorted_row = $('.headerSortDown')[0]     
  } 
  else {
    order='DESC'; 
    sorted_row = $('.headerSortUp')[0]     
  }    
  if(sorted_row)
  return [sorted_row.getAttribute('name'), sorted_row.id, order]
}

function open_dialog(id)
{	
  $('.selector').dialog('close');  
  $("#" + id).dialog('open')
}

function state_school(){
  switch($('select#recruit_institution_state').val()){
    case '':
      $('input#recruit_institution_name').attr('disabled', true);
      $('#recruit_institution_id').val(null);
      $('#recruit_institution_name').val('');
      break;
    default:
      $('input#recruit_institution_name').attr('disabled', false);
  }
}

function toggletext(showlink, hidelink, block){
  if($("#Scheduleblock").css("display") == "none"){
    $('#'+showlink).hide();
    $('#'+hidelink).show();
    $('#'+block).show();
  }
  else{
    $('#'+showlink).show();
    $('#'+hidelink).hide();
    $('#'+block).hide();
  }
}

function toggle_recruit_school_block(){
  if($("#recruit_link_recruit_to_a_school_true").attr('checked')){
    $("#recruit_school_block").show();
  }
  else{
    $("#recruit_school_block").hide();
    $("#recruit_institution_id").val(null);
    $("#recruit_institution_name").val('');
  }
}

function mass_destroy_conditions(){
  if(!atleast_one_selected('check_boxes')) { 
    alert('Select atleast one recruit'); 
    return false; } 
  else {
    return(confirm('Are you sure?'));
  }    
}

function edit_tags(){
	$('#edit_tags_link').hide();
	$('.trash_tags').show();
	$('#edit_tag_form').show();
	$('#edit_tag_form')[0].reset();	
	$('.tag').addClass('edit_form');
	$('#tag_img').hide();
}

function close_edit_tags(){	
	$('#edit_tag_form').hide();
	$('.trash_tags').hide();
	$('#edit_tags_link').show();
	$('.tag').removeClass('edit_form');
	$('#tag_img').show();
}

// Display templates on email popin
function display_template() {	
	$('.template_icons').hide();
	selected_op = $('#interaction_template_id')[0].options[$('#interaction_template_id')[0].selectedIndex];
	$('#template_'+selected_op.value).show();
	if(selected_op.value != ''){		
		$('#preview_link').show();		
		template_link = 'http://' + document.domain + '/interactions/preview?mass_email=' + mass_email + '&template=' + selected_op.value;		
		$('#preview_link').attr('href', template_link);
	}	
	else
		$('#preview_link').hide();
}

// generate link to preview the mail
function preview_mail() {	
	tinyMCE.triggerSave(true,true);
	$('#preview_link').attr('href', template_link + '&content=' + escape($('.notes')[0].value));
}


// method to push text to tinymce current editor
// Used in mass email for adding [First Name]
function push_text(text) { 	
  //el = document.getElementsByTagName('iframe')[0].contentWindow.document.getElementById('tinymce');
  //el.innerHTML = "<p>" + text + "</p>" + el.innerHTML;  
  // IE need to determine the cursor position and move bookmark there
  if(navigator.userAgent.toLowerCase().indexOf("msie") != -1){  	
		tinyMCE.selectedInstance.selection.moveToBookmark(editorCursorPosition);		
	}
	tinyMCE.execInstanceCommand(tinyMCE.selectedInstance.id, "mceInsertContent", false, text); 
}

// The function should be used with on "blur" only but not working as expected so calling it for all events
function myHandleEvent(e) {	
  // Aparently this is only needed for IE, and seems to give bugs when used if FF
  if(navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
    editorCursorPosition = tinyMCE.selectedInstance.selection.getBookmark(false);
  }
}

function copy_data(source, destination_id) {	
	$('#'+destination_id).val(source.value);
}

// called when "Send mail" interaction get submitted from recruits profile
function copy_mail_content() {
	tinyMCE.triggerSave(true,true); 
	if($('#interaction_template_id')[0]!=undefined)
		copy_data($('#interaction_template_id')[0], 'file_uploader_template'); 
	copy_data($('#notes')[0], 'file_uploader_notes')
}

// called when "Mass mail" interaction get submitted
function copy_mass_mail_content() {
	tinyMCE.triggerSave(true,true); 
	if($('#interaction_template_id')[0]!=undefined)
		copy_data($('#interaction_template_id')[0], 'file_uploader_template'); 
	copy_data($('#notes')[0], 'file_uploader_notes');
	copy_data($('#recipients')[0], 'file_uploader_recipients');
	copy_data($('#user_id')[0], 'file_uploader_user_id');
	copy_data($('#cc')[0], 'file_uploader_cc');
	copy_data($('#bcc')[0], 'file_uploader_bcc');
	copy_data($('#subject')[0], 'file_uploader_subject');
}

function sortRecruits(selector) {
  $.ajax({data:$(selector).sortable('serialize', {key:'sortable_list[]'}), dataType:'script', type:'post', url:'/recruits/sort'});
}

ScoutForce = {
  handleHockeyPosition: function(sel, pos) {
    switch(pos) {
      case "G":
        $(sel).find('.item .regular').hide();
        $(sel).find('.item .goalie').show();
        break;
      default:
        $(sel).find('.item .regular').show();
        $(sel).find('.item .goalie').hide();
    } 
  }
}

$(document).ready(function() {
  $.fn.attachDeleteHandler = function() {
  $(this).click(function(e) {
    e.preventDefault();

    $(this).closest('.item').hide();
    $(this).closest('.item').children('.delete-field').attr('value', 'true');
    });
  }

 $.fn.addSportInfo = function() {
  sport = $(this);

  $(sport.find('.addmore a')).click(function(e) {
    e.preventDefault();
    var addlink = this;

    $.ajax({
      url: $(this).attr('href'),
      type: "GET",
      dataType: "html", 
      success: function(data) {
        $(addlink).closest('.addmore').before(data);
        $('#sport_projected_position').each(function() {
          ScoutForce.handleHockeyPosition(sport, $(this).attr('value'));
          $(sport.find('a.delete-item')).attachDeleteHandler();
        });
      },
    
      error: function() {
        alert("Sorry, an error occurred.  Please try again.");
      }
    });
    return false;
  });

  $(sport.find('a.delete-item')).attachDeleteHandler();

  $('#sport_projected_position').change(function() {
    ScoutForce.handleHockeyPosition(sport, $(this).attr('value'));
  });

  $('#sport_projected_position').each(function() {
    ScoutForce.handleHockeyPosition(sport, $(this).attr('value'));
  });
}

 // interaction autofiltering
  $('#interaction_filter_form').ajaxForm({
    success: function(data) {
      $('#recruit_history').replaceWith(data);
    }
  });
  
  $('#interaction_filter').change(function() {
    $(this).closest('form').submit();
  });
});

