/*
  JavaScript used by Site Comparison Mashup

  (C) Copyright 2009, Compete Inc.
*/


function handle_comparison_form_clear() {
  $j('form#comparison input[name=q]').val('').removeClass('no-data').removeClass('invalid')
  $j('form#comparison input[name=q]')[0].focus()
}

function handle_comparison_form_submit() {
  inputs = $j('form#comparison input[name=q]')
  filled_inputs = 0
  for (i = 0; i < inputs.length; i = i + 1) {
    if (inputs[i].value != '') {
      filled_inputs += 1
    }
  }
  if (filled_inputs == 0) {
    return false
  }
  else if (filled_inputs == 1) {
    // treat it as a site-wide search (ajax and calls master._search_success_callback)
    var q = $j.trim($j('form#comparison input[name=q]').attr('value'))
    
    // form is good, do your magic
    var form = $j('form#comparison')
    $j.ajax({'url': form.attr('action'),
             'data': form.serialize(), 
             'success': _search_success_callback
      })
    return false  
  }
  else {
    return
  }
}

function load_content(sites, metric, user_is_anonymous, user_metrics, urls) {
  /* Given a list of sites, and a metric, it will asynchronously query for the
     metric data, parse the incoming json, and load the html into (already 
     existing) blocks identifying the domain names.
     
      sites           - a string containing the site that will be queried
      metric          - the metric to be queried for
      user_is_anonymous - optional, if given subdomains boxes will be checked 
                        before being displayed on the page
      user_metrics    - optional - a list of the metrics the user has access to
                      if metric is not in this list, we won't even query.
      urls            - optional - an object containing url prefixes for the 
                      .bottom links
  */
  
  // clean (potentially) existing low-sample stuff
  $j('#low-sample-comparison > span:not(.tmp)').remove()
  low_sample_container = $j('#low-sample-comparison').hide()
  
  data_desc = $j('#data-description')
  data_container = $j('#data-container')
  
  // hide the bottom part of the screen if the user has no access to the selected metric
  if (user_metrics && !contains(user_metrics, metric)) {
    data_desc.hide(); data_container.hide();
    return
  }
  else {
    data_desc.show(); data_container.show();
  }  
  
  // blank the blocks, and put the loading image on each one while the query runs
  $j('.domain-info').html('')
  $j('.domain-info').addClass('loading')
  
  
  $j.each(sites, function(i, site) {
    $j.getJSON('/metrics/async/metricinfo/' + escape(site) + '/' + metric + '/', function(json) {
      
      // generate the header block - *only* on the first pass
      if (i == 0) {_generate_header_block(json.data_date, json.metric)}
      
      var container = $j('#info-' + json.site_html_safe);
      container.removeClass('loading') //overwrite the loading img
      
      // there's no data for the given domain
      if (json.status == '3') {
        msg = 'We do not have any data for this site. \
               Please visit our <a href="'+main_site+'/resources/methodology/">Data Methodology</a> page to learn more about how we get our data.';
        container.css('border-color', '#fb9440')
        container.append($j('<div></div>').addClass('no-data').
          append($j('<div></div>').addClass('site-name').html(ellipsify(json.site, 20))).
          append($j('<div></div>').addClass('text').html(msg))
        )
        return
      }
      
      // the given domain is invalid
      if (json.status == '4') {
        msg = 'Your entry includes invalid characters. Please remove any invalid characters and try again.'
        container.css('border-color', '#fb5d65')
        container.append($j('<div></div>').addClass('invalid').
          append($j('<div></div>').addClass('site-name').html(ellipsify(json.site, 20))).
          append($j('<div></div>').addClass('text').html(msg))
        )
        return
      }
      
      // the given domain is a subdomain, and the user is anonymous
      if (json.site != json.domain && user_is_anonymous == true) {
        msg = 'Please <a href="' + member_site + '/login/">login</a> or <a href="/plans/">register</a> to access subdomains data.'
        container.append($j('<div></div>').addClass('anon-subdomain').
          append($j('<div></div>').addClass('site-name').html(ellipsify(json.site, 20))).
          addClass('sitelink').attr('site',site).attr('domain',json.domain).hover(siteHover, siteUnHover).
          append($j('<div></div>').addClass('text').html(msg))
        )
        return
      }
      // is low sample?
      if (json.status == '2') {
        low_sample_container.append($j('<span></span>').html(ellipsify(json.site, 23)));
        low_sample_container.show();
      }
      
      // the given domain is valid - proceed w/ the blocks
      var top = $j('<div></div>').addClass('top')
      var bottom = $j('<div></div>').addClass('bottom')
  
      // append the site name and the categories
      top.append(_generate_site_name_block(json.site, json.category, json.domain))
      
      // append the metric value
      top.append(_generate_metric_value_block(json.metric.value, metric))
  
      // append the change % values (both of them)
      top.append(_generate_change_block(json.metric.change_latest_value, metric))
      top.append(_generate_change_block(json.metric.change_overall_value, 
                                        metric, 
                                        is_last_section = true, 
                                        meta_block = bottom ))
  
      // append the top search terms
      bottom.append(_generate_meta_block(
              title = 'Top Search Terms',
              href_title = searchtools_site + '/site_referrals/' + json.site + '/', 
              items_count = json.search_terms_count,
              values = json.search_terms,
              href_values = searchtools_site + '/keyword_destination/',
              is_subdomain = json.site != json.domain ? true : false ))

      // append the top referral sites
      bottom.append(_generate_meta_block(
              title = 'Top Referral Sites',
              href_title = reftools_site + '/referrals/' + json.site + '/', 
              items_count = json.referral_sites_count,
              values = json.referral_sites,
              href_values = snapshot_site + '/',
              is_subdomain = json.site != json.domain ? true : false ))
            
      // append the top destination sites
      bottom.append(_generate_meta_block(
              title = 'Top Destination Sites',
              href_title = reftools_site + '/destinations/' + json.site + '/', 
              items_count = json.destination_sites_count,
              values = json.destination_sites,
              href_values = snapshot_site + '/',
              is_subdomain = json.site != json.domain ? true : false ))
      
      // append the top tags block
      bottom.append(_generate_tags_block(json.site, json.tags, user_is_anonymous))
      
      // append the top and the bottom to the container
      container.append(top).append(bottom)
      
      // react to the _comparison_info_blocks cookie
      __set_bottoms()
      
      // bind the click handlers for popup help
      bind_click_handlers();
      
      // Convert PNGs to transparent
      $j('div#content').supersleight({ shim: '/site_media/images/transparent.gif' });
    })
  })
}

function _generate_header_block(data_date, metric) {
  /* Populates the #data-description block, already existing on the page
      data_date       - json.data_date
      metric          - is the metric dictionary that comes via json
  */
  if (metric.is_daily == true) {
    $j('#data-description .calendar').css('background-position', '0')
    $j('#data-description .title').html('Daily Share Metrics /')
  }
  else {
    $j('#data-description .calendar').css('background-position', '-20px')
    $j('#data-description .title').html('Monthly Normalized Metrics /')
  }
  
  $j('#data-description .data-date').html(' ' + data_date);
  $j('#data-description img.popup-help').replaceWith('<img class="popup-help q' + ((metric.is_daily) ? 88 : 87) + '" src="/site_media/images/icons/helpicon.png" width="13" height="13" />');
  
  // write the columns descriptions and a show-all/hide-all toggle
  $j('#header-block').html('')
  $j('#header-block').
    append($j('<div></div>').addClass('section').html('&nbsp&nbsp')).
    append($j('<div></div>').addClass('section').append($j('<span></span>').html(metric.label)).append('<span class="popup-help ' + metric.help_index + '"></span>')).
    append($j('<div></div>').addClass('section').append($j('<span></span>').html(metric.change_latest_label))).
    append($j('<div></div>').addClass('section').addClass('last-section').
      append($j('<span></span>').html(metric.change_overall_label)).
      append($j('<div></div>').
        attr('id', 'domain-toggle-all').
        addClass('domain-toggle').
        bind('click', function() {_toggle_bottoms()})
    )            
  )
}

function _generate_site_name_block(site, category, domain) {
  /* Generates the top-left block, containing the site name and the category 
     to which the site belongs
      site            - the site name
      category        - array w/ the categories breadcrumb
  */
  var s = $j('<div></div>').addClass('section')
  var a = $j('<a></a>').addClass('site-name').attr('href', '/' + site + '/').html(ellipsify(site, 22)).
  attr('site',site).addClass('sitelink').hover(siteHover, siteUnHover).attr('domain',domain);
  var category_id = category != null ? category.shift() : null;

  if (! category_id ) {
    s.append(a).
      append($j('<div></div>').
        addClass('category').
        html( category != null ? 
          ellipsify(category.join('>'),35) : 'Uncategorized'
        )
      );
  } else {
    s.append(a).
      append($j('<div></div>').
        addClass('category').
        html( category != null ? $j('<a></a>').
             attr('href',main_site + '/m/profiles/category/' + category_id + '/').
             html(ellipsify(category.join('>'),35)) : 'Uncategorized'
        )
      );
  }
  return s
}

function _generate_metric_value_block(value, metric) {
  /* Generates the block where the metric value is displayed
      value           - the value to display
      metric          - the name of the metric we are generating a block for
  */
  var s = $j('<div></div>').addClass('section')
    
  if (value == null || value == '') {
    var v = $j('<div></div>').addClass('value').addClass('no-data')
    v.html('Historical data only')
  }
  else {
    var v = $j('<div></div>').addClass('value')
    if (metric == 'vpp' || metric == 'ppv') {
      v.html(commify(value.toFixed(2)))
    }
    else if (metric == 'att' || metric == 'attD' || metric == 'reachD') {
      v.html(commify(value.toFixed(8)) + '%')
    }
    else if (metric == 'avgStay') {
      reminder = parseInt(value) % 60
      v.html(parseInt(value / 60) + ':' + (reminder > 9 ? reminder : '0' + reminder))
    }
    else {
      v.html(commify(value.toFixed(0)))
    }
  }
  return s.append(v)
}

function _generate_change_block(value, metric, is_last_section, meta_block) {
  /* Generates the Monthly and Yearly/Overall change blocks. Returns the 
     generated block
      value           - the value to display
      metric          - the name of the metric we are generating a block for
      is_last_section - boolean, "is it the foremost right block?"
      meta_block      - is the block (jquery obj) that the plus sign toggles
  */
  s = $j('<div></div>').addClass('section')
  v = $j('<div></div>').addClass('delta')

  if (value == null || value == '') {
    v.html('N/A')
  }
  else {
    if (metric != 'rank') {v.html((value > 0 ? '+' : '') + commify(value.toFixed(2)) + '%')} 
    else {v.html(commify((value > 0 ? '+' : '') + value))}
    if (value < 0) {v.addClass('delta-negative')} 
    else {v.addClass('delta-positive')}
  }
  if (is_last_section != null) {
    s.addClass('last-section')
    s.append($j('<div></div>').addClass('domain-toggle').bind('click', function() {_toggle_bottom($j(this), meta_block)}))
  }
  
  return s.append(v)
}

function _generate_meta_block(title, href_title, items_count, values, href_values, is_subdomain) {
  /* Generates the Meta information that's displayed on the bottom part of each
     block (Top Search Terms, Top Referrals, Top Destinations). For the Top 
     Tags block see _generate_tags_block()
     
      title           - the title of the block (i.e. Top Search Terms)
      ref_title       - href tag of where the (123,456 Terms) links to
      items_count     - the 123,456 in Top Search Terms (123,456 Terms)
      values          - the list of values to linkify
      href_values     - the place the linkified values will link to
      is_subdomain    - boolean
  */
  var sitelink = false
  var desc = title.split(' ').slice(-1)[0] // terms/sites string
  var linkstr = '<a href="' + href_title + '">' + commify(items_count) + ' ' + (items_count == 1 ? desc.slice(0, -1) : desc) + '</a>'
  var s = $j('<div></div>')
  
  if (desc == 'Sites') {sitelink = true}
  
  s.addClass('section').
    append($j('<div></div>').
      addClass('desc').
      html(items_count == null || items_count == 0 ? title + ':' : title + ' (' + linkstr + '):')).
    append(items_count == null || items_count == 0 ? 
           '<ul><li>' + title.slice(4) + ' are unavailable for ' + (is_subdomain == true ? 'subdomains' : 'this site') + '.</li></ul>':
           _linkyfy_array(values, sitelink, href_values)
          )
  return s
}

function _generate_tags_block(site, tags, user_is_anonymous) {
  /* Generates the Top Tags block
      tags            - an array of tags
  */
  var s = $j('<div></div>').addClass('section').addClass('last-section')
  s.append($j('<div></div>').addClass('desc').html('Top Tags:'))
           
  if (tags == '') {
    if (user_is_anonymous) {
      var a = $j('<a href="#" class="no-tags-link"></a>').html(' Be the first')
      a.attr('href', member_site + '/login/?msg=tags&origin=' + encodeURIComponent(document.URL))
    }
    else {
      var a = $j('<span class="no-tags-link"> Be the first</span>')
      a.bind('click', function() {
        site_name = site                            // make the site_name just this domain
        $j('#other-tags-dialog').children().remove()// remove any existing dialog
        loadAddTagDialogBox()                       // make up the html for the dialog box
        $j('div#other-tags-dialog').dialog('open')  // open the dialog box
      })
    }
    s.append($j('<ul></ul>').append($j('<li>There are no tags for this site. </li>').append(a)))
  }
  else {
    s.append(_linkyfy_array(tags, false,'/s/tag/'))
  }

  return s
}

function _linkyfy_array(array, sitelink, url_prefix, url_suffix) {
  /* Given an array of elements and a url prefix/suffix, it will return a list (ul)
     of all the links i.e. <li><a>array[i]</a></li>
     TODO: why are we creating all of these jquery elements? Shouldn't we just do html?
  */
  if (sitelink == null) {sitelink = false}
  if (url_suffix == null) {url_suffix = '/'}
  
  ul = $j('<ul></ul>')
  $j.each(array, function(i, site) {
    li = $j('<li></li>');
    if (sitelink) {li.addClass('sitelink').attr('site',site).hover(siteHover, siteUnHover)}
    li.append($j('<a></a>').attr('href', url_prefix + site + url_suffix).html(site))
    if (array.length != i + 1) {li.append($j('<span></span>').html(',&nbsp'))}
    ul.append(li)
  })
  return ul
}

function _toggle_bottom(this_element, element) {
  /* Toggles a .section.bottom block. I have no idea why I cannot call $(this)
     from within this block, so I am passing $(this) as an argument
  */
  if (element.css('display') == 'none') {
    this_element.css('background-position', '0 0')
  }
  else {
    this_element.css('background-position', '19px 0')
  }
  element.toggle()
}

function _toggle_bottoms() {
  /* Shows/Hides all of the .section.bottom blocks, and adds a cookie
  containing information as to the last action of the user
  */
  e = $j('#domain-toggle-all')
  if (e.hasClass('on')) {
    $j('.domain-info .bottom').css('display', 'none')
    $j('.domain-info .domain-toggle').css('background-position', '19px 0')
    e.css('background-position', '19px 19px')
    e.removeClass('on')
    $j.cookie('_comparison_info_blocks', 'display:none', {expires: 7, path: '/'})
  }
  else {
    $j('.domain-info .bottom').css('display', 'block')
    $j('.domain-info .domain-toggle').css('background-position', '0 0')
    e.css('background-position', '0 19px')
    e.addClass('on')
    $j.cookie('_comparison_info_blocks', 'display:block', {expires: 7, path: '/'})    
  }
}

function __set_bottoms() {
  /* Sets each domain-info block according to the value of the 
  _comparison_info_blocks cookie
  */
  if ($j.cookie('_comparison_info_blocks') == 'display:none') {
    return
  }
  
  e = $j('#domain-toggle-all')
  if (!e.hasClass('on')) {
    e.css('background-position', '0 19px')
    e.addClass('on')
  }
  $j('.domain-info .bottom').css('display', 'block')
  $j('.domain-info .domain-toggle').css('background-position', '0 0')
}
