Object.extend(Page.prototype, {
  criteria: $A([
    ['.emotitagger_face', 15], 
    ['#topic_additional_detail', 25], 
    ['#topic_subject',0], 
    ['.emotitagger_feeling', 10], 
    ['#topic_keywords', 25],
    ['#product_grid .product_checkbox',25]
    ]),
  
  tag_new_topic: function(clicked_tag, tag_name) {
    this.new_topic_tag_click('topic_keywords', clicked_tag, tag_name);
  },

  new_topic_tag_click: function(field, clicked_tag, tag_name) {
    field = $(field);
    if (field.onfocus) { field.onfocus() };
    if (field.prompter && field.prompter.enabled && field.prompter.set_prompt()) { field.clear(); }
  
    tag_in_field = this.manage_tag_field(field, tag_name);
    Page.manage_tag_state(tag_in_field, clicked_tag);
  },
  
  manage_tag_field: function(field, tag_name) {
    field = $(field);
    tags = Page.split_tags(field.getValue());
    tag_name = String.interpret(tag_name).strip();
    tag_in_field = tags.include(tag_name);
    if (tag_in_field) {
      tags = tags.reject(function(tag) { return tag == tag_name; });
    } else {
      tags.unshift(tag_name);
    }
    field.value = tags.join(', ');
    return tag_in_field;
  },
  
  toggle_more_detail: function() {
    $("private_detail_").toggle();
  },
  
  friendly_style: function(style) {
    switch(style) {
    case 'talk':
      return 'discussion'
      break;
    default:
      return style
    }
  },
  
  update_style: function(style) {
    // Resets
    el = style + "_tab";
    $('topic_style_tabs').select('li').each(function(el) { el.className = ''; });
    $$('label.prompt').each(function(el) {el.hide()});
    // Set prompts
    if($(style+'_prompt')) {
      $(style+'_prompt').show();
    }

    // Show good/bad examples
    $$('div.alert').each(function(el) {el.hide()});
    $$('div.alert.' + style).each(function(el) {el.show()});

    // Set current Style
    this.topic_style = style;
    $(el).addClassName('on');
    $(el).up('form').className = style;
    $('topic_style').value = style;
    $('new_topic_form').select('.dyn_style').each(function(el) {
      el.update(page.friendly_style(style));
    });
  },
  
  generate_score: function(has_emp) {
    score = 0;
    this.criteria.each(function(c) {
      if ($$('#new_topic_form ' + c.first()).length != 0) {
        if(page.has_value(c)) {
          score += c.last();
        }
      }
    });

    this.set_score(score);
  },
  
  has_value: function(c) {
    if(c.first() == '#product_grid .product_checkbox') {
      value = $$(c.first()).pluck('checked').any();
    } else {
      value = $$('#new_topic_form ' + c.first()).first().value != ''
    }
    return value
  },
  
  set_score: function(score) {
    if(score <= 25) {
      rating = "low";
    } else if(score > 25 && score < this.get_top_score()) {
      rating = "medium";
    } else if(score == this.get_top_score()) {
      rating = "high";
    }
    $('likelihood_meter').setAttribute("class", '');
    $('likelihood_meter').style.backgroundImage = 'url(/images/likelihood_'+rating+'.png)'
    this.add_action_items(this.get_action_items())
  },
  
  get_top_score: function() {
    if(this.has_products) {
      return 100
    } else {
      return 75
    }
  },
  
  get_action_items: function() {
    action_items = [];
    $H(Page.action_item_criteria).each(function(pair){
      field_id = pair.first();
      criteria = pair.last();
      
      if(field_id == '#product_grid .product_checkbox') {
        value = field_id;
      } else {
        value = this.get_form_value(field_id);
      }
      criteria.each(function(clause) {
        if (value == field_id && !page.has_products) { 
          // no products
        } else {
          if(clause.first()(value)) { action_items.push(clause.last()); }
        }
      })
    }.bind(this))
    
    return action_items;
  },
  
  get_form_value: function(field_id) {
    return $F($('new_topic_form').down(field_id));
  },
  
  add_action_items: function(action_array) {
    html_to_add = "";
    $A(action_array).each(function(value) {
      html_to_add += "<li>"+value+"</li>"
    })
    $('visibility_suggestion').show();
    if(action_array.length != 0) {
      $('suggestions').update(html_to_add);
      $('visibility_suggestion').down('h3').update("Increase your chances of getting noticed")
    } else {
      $('visibility_suggestion').down('h3').update("Nice job! You're good at this.");
      $('suggestions').update('');
    }
  },
  
  new_topic_validates: function() {
    required = $('topic_subject');
    if($F(required) == '' || $F(required) == "Don't forget to add a great title") {
      Element.scrollTo(required);
      new PromptedField(required, "Don't forget to add a great title", true);
      required.value = "Don't forget to add a great title";
      new Effect.Highlight(required, {delay: 0.1, duration: 2});
      return false
    } else {
      return true
    }
  }
});

Object.extend(Page, { 
  sync_tag_links: function() {
    Page.apply_styles_to_tag_links(this, 'topic_keywords');
  },
  
  apply_styles_to_tag_links: function(prefilled_tags, field) {
    tags = Page.split_tags($F(field));
    $A(prefilled_tags).each(function(tag) {
      el = $(tag.element);
      if (tags.include(tag.name)) {
        el.addClassName('in_use');
      } else {
        el.removeClassName('in_use');
      }
    });
  },
  
  get_toggle_image: function(clicked_el) {
    return $(clicked_el).up('.tag_toggle').down('img');
  },
  
  manage_tag_state: function(tag_found, clicked_link) {
    if (tag_found) {
      $(clicked_link).removeClassName('in_use');
    } else {
      $(clicked_link).addClassName('in_use');
    }
  }
  
});

Object.extend(Page.prototype, {
  initialize_style: function() {
    current_style = $F('topic_style');
    this.update_style(current_style);
  },
  initialize_emotitag: function() {
    ep = EmotionPicker.get_picker($('new_topic_form').down('.emotitagger_face'));
    current_emotitag_face = this.get_form_value('.emotitagger_face');
    current_emotitag_feeling = this.get_form_value('.emotitagger_feeling');
    current_emotitag_intensity = this.get_form_value('.emotitagger_intensity');
    ep.set_face(current_emotitag_face);
    ep.set_punctuation();
  },
  initialize_tips: function(has_employees) {
    this.tips_interval = setInterval(function() {
  	  page.generate_score(has_employees);
  	}, 2000);
  },
  stop_tips: function() {
    clearInterval(this.tips_interval);
  },
  initialize_page: function(has_employees) {
    this.initialize_style();
    this.initialize_emotitag();
    this.initialize_tips(has_employees);
    this.has_products = $$('#product_grid .product_checkbox').length == 0 ? false : true;
  }
});

Object.extend(Page, {
  word_count_less_than: function(number) {
     return function(input) {
       if(input.blank()) return false
        return input.split(/\s+/).length < number
      }
  },
  word_count_greater_than: function(number) {
    return function(input) {
      return input.split(/\s+/).length > number
    }
  },
  regex_check: function(regex) {
    return function(input) {
      return input.match(regex)
    }
  },
  empty_checker: function() {
    return function(input) {
      return input.blank();
    }
  },
  check_caps: function() {
    return function(input) {
      test_string = input.gsub(' ', '');
      return test_string.match(/([A-Z]|\s+){6,}/)
    }
  },
  any_checked: function() {
    return function(inputs) {
      return $$(inputs).pluck('checked').any() ? false : true;
    }
  }
});

Object.extend(Page, {
  action_item_criteria: {
    "#product_grid .product_checkbox":[[Page.any_checked(), "Add at least one product or service."]],
    "#topic_keywords":[[Page.empty_checker(), "Add at least three tags. More tags = more visible."]],
    ".emotitagger_face":[[Page.empty_checker(), "Pick a face to let everybody know how you feel."]],
    ".emotitagger_feeling":[[Page.empty_checker(),"Get emotional! Describe how this topic makes you feel."]],
    "#topic_additional_detail":[
      [Page.word_count_less_than(15), "Add more detail. One or two paragraphs works best."], 
      [Page.empty_checker(), "Add some detail. One or two paragraphs works best."]
    ],
    "#topic_subject":[
      [Page.empty_checker(), "Add a title to your topic."],
      [Page.word_count_greater_than(40), "Tighten up that title. One simple sentence works best."],
      [Page.check_caps(), "EASE UP ON THE ALL CAPS IN YOUR TITLE. It looks like you’re shouting."],
      [Page.regex_check(/\!{3,}/), "Go easy on the exclamation points in your title!!!! One or two ought to be enough."],
      [Page.regex_check(/\?{3,}/), "What's with all the question marks in your title???? One or two ought to be enough."]
    ]
  }
});
page.watch('failed_login', function() {
  page.fixed_message("I'm sorry, but either your email or password was incorrect. Please try again.", "bad")
});
