// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// assumes you never ask for content to be bigger than what exists
// assumes element contains paragraphs
function previewTruncateParagraphs(element, text, length){
  var txt = text.substring(0, length);
  if (txt.count(/<p/) > txt.count(/<\/p>/)){
    txt = txt + '</p>'
  }
  $(element).innerHTML = txt;
}

Object.extend(String.prototype, {
  count: function(regexp){
    return this.split(regexp).length - 1;
  }
});

function updateColorPreview(){
  try{
    // css_page_background
    $$('.layout').invoke('setStyle',{ backgroundColor: $F('career_site_css_page_background') });

    // css_header_background
    $$('.layout_header').invoke('setStyle', { backgroundColor: $F('career_site_css_header_background') });
    // css_header_title_font,
    $$('.layout_header div.title').invoke('setStyle', { color: $F('career_site_css_header_title_font') });

    // css_layout_background
    $$('.layout_content').invoke('setStyle', { backgroundColor: $F('career_site_css_layout_background')  })

    // css_layout_widget_background
    // css_layout_widget_content_font
    $$('.widget_content', '.widget_text', '.widget_link', '.widget_highlight').invoke('setStyle', { 
      backgroundColor: $F('career_site_css_layout_widget_background'),
      color: $F('career_site_css_layout_widget_content_font')
    });

    // css_layout_widget_title_background
    // css_layout_widget_title_font
    $$('.widget_header').invoke('setStyle', {
      backgroundColor: $F('career_site_css_layout_widget_title_background'),
      color: $F('career_site_css_layout_widget_title_font')
    });

    $$('.content_block').invoke('setStyle', {
      border: '1px solid ' + $F('career_site_css_layout_widget_title_background')
    })

    // css_layout_widget_content_headers
    $$('.widget_heading').invoke('setStyle', { color: $F('career_site_css_layout_widget_content_headers') })
    // css_layout_widget_content_links
    $$('.widget_link').invoke('setStyle', { color: $F('career_site_css_layout_widget_content_links') });
  } catch(e){
    throw "Unable to refresh all items on preview.  Selector Mismatch Error."
  }
}

// using a single dom:loaded handler to do multiple things... no point in having 1200 events
// 1. flash notices removed on click
// 2. inheritance handler for widget layout page
$(document).observe('dom:loaded', function(event){
  if ($('inheritance_checkbox')){
    $('inheritance_checkbox').observe('click', toggle_widget_layout_inheritance)
  }
  flash_close_handlers();
  
   // rich text editing
  $$('textarea.editable').each(function(area){
    var editor = new FCKeditor(area.identify());
    editor.ToolbarSet = 'SOJ';
    editor.ReplaceTextarea();
  });
  
  if (Prototype.BrowserFeatures.Flash <= 9){
    $$('div.no_flash').invoke('show');
  }
  
  // flash audio player
  $$('a.audio').each(function(mp3){
    AudioPlayer.embed(mp3.identify(), {soundFile: mp3.href});  
  });
});

function validate_candidate_form(form) {
  return $w('first_name last_name name email cover country postal_code city').all(function(field_name) {
    var field = $(form).select('[name="candidacy[' + field_name + ']"]').first();
    if (field) {
      if (field_name == 'city' && field.value.blank()) {
        alert("You must enter a valid postal code.")
        $('candidacy_postal_code').select();
        return false;
      }
      if (field.value.blank()){
        alert(field_name.capitalize() + " must be present.")
        field.select();
        return false;
      }
      if (field_name == 'name' && !$F(field).match(/.+\s+.+/)){
        alert(field_name.capitalize() + " is incomplete.")
        field.select();
        return false;
      }
      if (field_name == 'email' && !$F(field).match(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)){
        alert(field_name.capitalize() + " must be a valid email address.")
        field.select();
        return false;
      }
    }
    return true;
  });
}

function validate_video_form(form){
  var field = $(form).select('[name="video[title]"]').first();

  if (field.value == ''){
    alert("Please fill in the title field.")
    field.select();
    enable_video_form(form);
    return false;
  }
  
  form.submit();
}

function video_thumbnail(json_response){
  alert(json_response.type);
}

function rjs_validate(type, json_errors){
  var errors = eval(json_errors);
  $$('#' + type + '_' + errors.first().first()).first().select();
  alert(errors.first().first().capitalize() + " " + errors.first().last());
}

function rjs_alert_errors(json_errors) {
  var errors = eval(json_errors);
  errors.each(function(error){
    alert(error.first() + " " + error.last)
  });
}

function enable_video_form(form){
  var commit = $(form).select('[name="commit"]').first();
  commit.update('Add').disabled = false;
}

function toggle_widget_layout_inheritance(event){
  // if unchecked and there are currently widgets there they will be lost
  if ($('inheritance_checkbox').checked && $$('#column_contents .draggable').length){
    if (confirm("Doing so will remove all widgets you selected for this layout. Are you sure you want to continue?")){
      $('inheritance_form').onsubmit();
    }else{
      Event.stop(event);
    }
  }else{
    $('inheritance_form').onsubmit();
  }
}

function flash_close_handlers() {
  $$('div.notice').invoke('stopObserving','click');
  $$('div.notice').each(function(flash){
    flash.title = "Click to close";
    flash.setStyle({cursor: 'pointer'})
    flash.observe('click', function(event){
      new Effect.Fade(flash, {duration: 0.3});
    });
  });
}

function flash(message){
  var page_title = $$('h1').first();
  var flash_div  = '<div class="notice" title="Click to close" style="cursor: pointer">' + message + '</div>';
  
  if (page_title){
    page_title.insert({ after: flash_div });
  }
  flash_close_handlers();
}

Prototype.BrowserFeatures.Flash = (function(){
  try{
   return navigator.plugins["Shockwave Flash"].description.match(/(\d+)/)[1];
  }catch(e){
    try{
      return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version").match(/(\d+)/)[1];
    }catch(e){}
  }
  return false;
})();