/*
 * Copyright (c) 2009 by WhitePages, Inc. All Rights Reserved.
 *
 * === Description
 *  Names specific functionality.
 *
 * === Dependencies
 *  jquery
 *
 */


// Namespaces
whitepages.names = function() {}; 


/*
 * toggle_element
 *
 * REQUIRES:    jquery
 * DESCRIPTION: Toggles the display property of a form if form_id exists,
 *              sets the CSS for a given link_id.
 *
 * PARAMETERS:
 *   disable_ele_id  - the id of the element to disable if it already has a
 *                    particular class.
 *   viewable_ele_id - array of ids of elements that will have their display
 *                     toggled.
 *   link_id         - array of link ids
 *   class_name - name of the link's class
 */
whitepages.names.toggle_element = function( disable_ele_id,
                                            viewable_ele_id,
                                            link_id,
                                            class_name )
{
  // If an element has a particular class don't allow the action
  if ( $('#'+disable_ele_id).hasClass(class_name) ) {
    return false;
  }

  // Toggle the elements that we want to toggle the display
  $(viewable_ele_id).each( function() {
    $('#'+this).toggle();
  });

  // Toggle the class on the links
  $(link_id).each( function() {
    $('#'+this).toggleClass( class_name );
  });
}


whitepages.names.popularity = {
  low: 1,
  high: 5
}
whitepages.names.popularity.class_names = [ "popularity_notatall",
                                            "popularity_notvery",
                                            "popularity_fairly",
                                            "popularity_somewhat",
                                            "popularity_extremely" ]
whitepages.names.popularity.filter = function()
{
  classes = []
  for (i = whitepages.names.popularity.low; i < whitepages.names.popularity.high; i++)
    classes[classes.length] = "."+whitepages.names.popularity.class_names[i];

  $(".popularity").hide();  
  $(classes.join(',')).show();
}

whitepages.names.badge = function() {};

whitepages.names.badge.template = function() {};
whitepages.names.badge.init = function( init )
{
  this._init = init;
}
whitepages.names.badge.single_name = function()
{
  return this._init.name_type != '';
}

whitepages.names.badge.generate = function() 
{
  var template = whitepages.names.badge.template;
  template._base = $(
    "<div style=\"text-align:center; color:#7D6A55; font-size:11px; font-family:arial,sans-serif;\" />"
  );
  template._base.append(
    "<a href=\"http://www." + this._init.hostname + "/\" style=\"float:right;\"><img \
    src=\"http://names." + this._init.hostname + "/common/images/names/wp_logo_badge.png\" \
    style=\"border: 0;\" alt=\"WhitePages Logo\" /></a>"
  );
  template._base.append(
    "<a href=\"http://names." + this._init.hostname + "/\" style=\"float:left; \
    padding-top:5px;\"><img style=\"border: 0 none;\" src=\"http://names." 
    + this._init.hostname + "/common/images/names/namebadge-hdr.gif\" \
    alt=\"Name Information\"/></a>"
  );
  template.content = this.single_name() ? [this._init.name_type] : ['first', 'last'];
}

/* generate_twitter
 *
 *
 * REQUIRES:    jquery
 * DESCRIPTION: Generates the Twitter badge
 *
 * PARAMETERS:
 *   badge_id - the id of the element to disable if it already has a
 *                    particular class.
 *
 * RETURNS:
 *   template - Returns the HTML code that generates the badge.
 */
whitepages.names.badge.render_twitter = function(badge_id)
{
  // Set current_badge to know which badge code to update when the twitter
  // username is modified
  this._init.current_badge = badge_id;

  var clear_img = this._init.hostname + '/common/images/spacer.gif';

  var template = '<div style="' + this._init.badge_style +
    this._init[badge_id].wrapper + '"><div style="' +
    this._init[badge_id].twitter_url + '"><a style="' +
    this._init.anchor_style + '" href="' +
    this._init.follow_url + '"><img style="' +
    this._init[badge_id].clear_img + '" src="' + clear_img +
    '" /></a></div><div style="' + this._init[badge_id].content +
    '"><span style="' + this._init[badge_id].name  + '">' +
    this._init.name_url + '</span>' +
    '<br/> <span style="' + this._init[badge_id].last_updated_style + '">' +
    this._init.last_updated + '</span></div><div style="' +
    this._init[badge_id].wp_logo + '">' + this._init.logo_url +
    '</div></div>';

  return template;
}


whitepages.names.badge.wrap_with_border = function(base)
{
  var border_image = "http://names." + this._init.hostname + "/common/images/names/badgeborder-";

  /* Wrap the content with right border. */
  base.css({
    "padding": "0 18px 0 16px",
    "background-color":    "transparent",
    "background-image":    "url(" + border_image + "rightmid.gif)",
    "background-repeat":   "repeat-y",
    "background-position": "right top"
  });
  /* Wrap the right border with the left border. */
  var body = $(
    "<div style=\"background-color: white; background-image: url(" + border_image + "leftmid.gif); background-repeat: repeat-y; float: left;\" />"
  ).append(base);
  /* Wrap the entire thing in a single div. */
  var template = $(
    "<div style=\"width: 240px;\" />"
  ).append(body);

  /* Add top border. */
  template.prepend(
    "<div style=\"background-color: transparent; height: 12px; font-size: 1px;\"> \
      <div style=\"background-image: url(" + border_image + "topleft.gif); width: 12px; height: 12px; float: left;\"> </div> \
      <div style=\"background-image: url(" + border_image + "topright.gif); width: 12px; height: 12px; float: right;\"> </div> \
      <div style=\"background-color: white; background-image: url(" + border_image + "topmid.gif); background-repeat: repeat-x; width: 216px; height: 12px; float: left; \"> </div> \
      <p style=\"margin:0\"></p> \
    </div>"
  );
  /* Add bottom border. */
  template.append(
    "<div style=\"background-color: transparent; height: 12px; font-size: 1px; clear: both;\"> \
      <div style=\"background-image: url(" + border_image + "bottomleft.gif); width: 12px; height: 12px; float: left;\"> </div> \
      <div style=\"background-image: url(" + border_image + "bottomright.gif); width: 12px; height: 12px; float: right;\"> </div> \
      <div style=\"background-color: white; background-image: url(" + border_image + "bottommid.gif); background-repeat: repeat-x; background-position: bottom; width: 216px; height: 12px; float: left; \"> </div> \
      <p style=\"background-image:none;margin:0\"></p> \
    </div>"
  );
  return template;
}
whitepages.names.badge.get_namelink_with_state = function(key)
{
  var current_state = $("#state").val();
  var namelink_with_state = ""
  if (current_state != "the US") namelink_with_state += "/"+current_state;
  namelink_with_state += this._init.name_url[key || 'full']

  return namelink_with_state;
}
whitepages.names.badge.set_current_state = function()
{
  var current_state = $("#state").val();
  var namelink_with_state = this.get_namelink_with_state();

  whitepages.names.badge.template._name_link_head = $(
    "<div style=\"clear:both; height:1px; line-height:1;\"> </div> <p style=\"clear:both; \
    padding-top:8px; padding-bottom:5px; margin:0; font-size:16px; font-weight:bold;\"><a \
    style=\"text-decoration:underline; color:#54B948;\" href=\"http://names." 
    + this._init.hostname+namelink_with_state + "\">" + this._init.name[this._init.name_type] + 
    "</a></p>"
  );
  whitepages.names.badge.template._name_link_foot = $(
    "<div style=\"clear:both; height:1px; line-height:1px;\"> </div> <p style=\"clear:both; \
    font-style: italic; padding-top:8px; padding-bottom:5px; margin:0; font-size:12px;\"><a \
    style=\"text-decoration:underline; color:#7D6A55;\" href=\"http://names." + 
    this._init.hostname+namelink_with_state + "\">" + this._init.name['first'] + " " + 
    this._init.name['last'] + "</a><span style=\"font-size: 11px;\"> on WhitePages</span></p>"
  );

  /*
  whitepages.names.badge.template._embed_tag_src = "http://names." + this._init.hostname + 
    "/common/images/names/name_badge.swf?urlNames=http://names." + this._init.hostname+
    "/badge_api" + this._init.name_url['full'];
  whitepages.names.badge.template._embed_tag = $(
    "<embed style=\"margin-top: 8px;\" width=\"200\" align=\"center\"></embed>"
  );
  */

  whitepages.names.badge.template.content = $.map(whitepages.names.badge.template.content, function(key, index) {
    var badge = whitepages.names.badge;
    var namelink_with_state = badge.get_namelink_with_state(key);
    var content = function() {};
    if (badge._init.meaning[key] != '') {
      content._name_meaning = $(
        "<b style=\"margin-bottom: 7px; display: block;\">Meaning</b>" +
        "<p style=\"margin: 0;\">" + badge._init.meaning[key]
          .replace(/&lt;p&gt;/g, '&lt;p style=\"margin-top: 0; line-height: normal;\"&gt;')
          .replace(/&lt;b&gt;/g, '&lt;b style=\"font-weight: normal;\"&gt;')
          .replace(/&lt;a/g, '&lt;a style=\"color: #7d6a55;\"')
          .replace(/&lt;span class=&quot;name&quot;&gt;(.*?)&lt;\/span&gt;/g, '&lt;span style=&quot;font-style: italic;&quot;&gt;$1&lt;/span&gt; ')
        + "</p>"
      );
    }
    content._name_rank = $(
      "<li style=\"line-height: normal;\"><img style=\"vertical-align:bottom; border: 0; padding: 0; margin: 0; line-height: 1;\" alt=\"*\" src=\"http://names."
      + badge._init.hostname + "/images/name_rank"+namelink_with_state+".png\" /> most \
      popular " + badge._init.name_type + " name in "+current_state.replace(/_/,' ')+".</li>"
     );
    content._search_history = $(
      "<li style=\"line-height: normal;\"> has been searched for over <img style=\"vertical-align:bottom; border: 0; padding: 0; margin: 0; line-height: 1;\" alt=\"*\" src=\"http://names."
      + badge._init.hostname + "/images/search_history" + badge._init.name_url[key] + ".png\" /> \
      times on WhitePages.</p>"
    );
    return content;
  });
}
whitepages.names.badge.name_meaning_checked = function()
{
  return whitepages.names.badge.name_meaning = $("#name_meaning").attr("checked");
}
whitepages.names.badge.name_rank_checked = function()
{
  return whitepages.names.badge.name_rank = $("#name_rank").attr("checked");
}
whitepages.names.badge.search_history_checked = function()
{
  return whitepages.names.badge.search_history = $("#search_history").attr("checked");
}
whitepages.names.badge.build_content = function()
{
  var content_wrap;
  if (this.single_name()) { 
    content_wrap = $("<div style=\"text-align: left; width: 194px; height: 205px; overflow: auto; padding: 5px; border: solid 1px #efe9e5;\" />");
  } else {
    content_wrap = $("<div style=\"text-align: left; width: 184px; height: 205px; overflow: auto; padding: 5px 7px;\" />");
  }

  var template = this.template.content;
  for ( i = 0; i < template.length; i++ )
  {
    var content;
    if (this.single_name()) {
      content = content_wrap;
    } else {
      content = $("<div />");
      if (i == 1) content.css("display", "none");
    }
    if (this.name_meaning_checked()) content.append(template[i]._name_meaning);
    this.name_rank_checked();
    this.search_history_checked();
    if (this.name_rank || this.search_history)
    {
      content.append("<b style=\"margin-top: 7px; display: block;\">Popularity</b>");
      var popularity_block = $("<ul style=\"padding-left: 15px; margin: 0; margin-top: 7px;\" />");
      if (this.name_rank) popularity_block.append(template[i]._name_rank);
      if (this.search_history) popularity_block.append(template[i]._search_history);
      content.append(popularity_block);
    }
    if (!this.single_name()) content_wrap.append(content);
  }
  return content_wrap;
}
whitepages.names.badge.build_embed_tag = function()
{
  var src = this.template._embed_tag_src;

  this.name_rank_checked();
  this.name_meaning_checked();
  this.search_history_checked();

  if (!(this.name_rank && this.name_meaning && this.search_history))
  {
    var fieldset = [];
    if (this.name_rank) fieldset[fieldset.length] = "rank";
    if (this.name_meaning) fieldset[fieldset.length] = "meaning";
    if (this.search_history) fieldset[fieldset.length] = "searches";

    src += "?fields=" + fieldset.join(',');
  }

  return this.template._embed_tag.attr("src", src);
}
whitepages.names.badge.render = function()
{
  var template = whitepages.names.badge.template._base;
  whitepages.names.badge.set_current_state();

  /* if ( this._init.flash_badge) { */
  /*
    if ( this.single_name() ) {
      template.append(this.template._name_link_head);
      template.append(this.build_embed_tag());
    } else {
      template.append(this.build_embed_tag());
      template.append(this.template._name_link_foot);
    }
  } else {
  */
    if ( this.single_name() ) {
      template.append(this.template._name_link_head);
      template.append(this.build_content());
    } else {
      var javascript = "var a;var tabs=this.parentNode.childNodes;for(i=0;i<2;i++){if(tabs[i]!=this){tabs[i].style.color='#7D6A55';tabs[i].style.backgroundColor='#efe9e5';tabs[i].style.textDecoration='underline';}else{tabs[i].style.color='#54B948';tabs[i].style.backgroundColor='white';tabs[i].style.textDecoration='none';a=i;}}var content=this.parentNode.parentNode.childNodes[1].childNodes;content[1-a].style.display='none';content[a].style.display='block';";
      template.append(
        "<div style=\"clear: both;\" />"
      ).append(
        $("<div style=\"border: solid 4px #efe9e5; clear: both; width: 198px; margin-top: 8px;\" />").append($(
          "<div style=\"background-color: #efe9e5; height: 32px; margin-bottom: 7px;\">" +
          "<div style=\"cursor: pointer; float: left; font-size: 15px; font-weight: bold; padding: 7px 7px 7px 4px; background-color: white; color: #54B948;\"" +
          " onclick=\"" + javascript + "\">" +
          this._init.name['first'] + "</div>" +
          "<div style=\"cursor: pointer; float: left; font-size: 15px; font-weight: bold; padding: 7px 7px 7px 4px; text-decoration: underline;\"" +
          " onclick=\"" + javascript + "\">" +
          this._init.name['last'] + "</div>" +
          "</div>"
        )).append(this.build_content())
      );
      template.append(this.template._name_link_foot);
    }
  /*}*/

  return $("<div />").append(
                        this.wrap_with_border(template)
                      )
                     .html()
                     .replace(/&lt;/g   , '<')
                     .replace(/&gt;/g   , '>')
                     .replace(/&amp;/g  , '&')
                     .replace(/  +/g    , ' ')
                     .replace(/\>[\r\n]+\</g  , '><');
};

whitepages.names.report_twitterer = function(twitterer) {

  var twitterer = $(twitterer);

  var link = twitterer.find("a").attr("href");
  var userid = link.substr(link.lastIndexOf('/', 23)+1);

  var linktext = twitterer.find("a").text();
  //var name = linktext.substr(0, linktext.indexOf('(')-1);

  var comments = "Referrer:        " + document.location + "\n" +
                 "Twitter ID:      " + userid + "\n" +
                 "Name / Location: " + linktext + "\n" +
                 "Image:           " + twitterer.find("img").attr("src") + "\n" +
                 "Bio:             " + twitterer.find("p").attr("title") + "\n" +
                 "Followers:       " + twitterer.find("span.followers").text()

  $.ajax({
    type: "POST",
    url: "/mail/report_twitterer",
    data: "comments=" + comments,
    success: function(msg) {
      $('.flag_twitterer', twitterer).attr({'style': 'block'});
      $('.report', twitterer).attr({'style': 'display:none;'});
      //$('.report', twitterer).html('');
    }
  });
}
