/* Accompanying javascript for the Search Analytics application
*/


if (!search) {
  var search = {}
}

$j(function () {
  if (search != undefined) {
    search.CHART_REPORTS = Array('site_referrals', 'site_comparison');
  }
});

search.initialize_page = function() {
  /* Runs as soon as the page finishes loading
  */
  
  // add hovering styles @ anchor-like elements for ie
  $j('.anchor-like').each(function(i) {
    var obj = $j(this);
    obj.hover(function() {obj.addClass('underline')}, 
              function() {obj.removeClass('underline')});
  });

  $j('form#search-referrals').submit(search.submit_form);
  $j('form#search-analytics-form').submit(search.submit_form);
  
  // show the popup, or just put the grid up?
  if (search.show_interstitial_popup) {
    search._show_deduct_credit_popup();
  } else {
    referrals.initialize_grid(search.data_url);
    
    if (!window.IS_TEASER && window.authorized_user) {
      $j('div#pvn-trend-upsell').hide();
      $j('div#chart-container').removeClass('hidden');
    }
    if (!window.IS_TEASER && window.GRID_ACCESS) {
      $j('div#teaser-cover').hide();
      $j('#filters-upsell-block').hide();
    }    
    // Initialize the chart/range picker/metric dropdowns for site/compare
    // referral reports
    if ($j.inArray(window.REPORT_TYPE, search.CHART_REPORTS) > -1) {
      search.initialize_chart();
      search.init_metric_box_hook();
    }
  }
};


/*
 * Install an empty hook function here.  This function gets run when we've burned
 * credits, determined authentication etc  and are now ready to show the user a
 * chart.  Its semantic purpose is to go ahead and initialize data in metric boxes,
 * although of course it actually does nothing unless a calling template installs
 * something here.
 */
search.init_metric_box_hook = $j.e;


search.lazily_load_metric_box = function (id, mb) {
    /*
     * Populate the contents of a metric box on the page based on some
     * supplied arguments:
     *
     *   id : the dom_id of the containing metric div
     *   mb : an object containing properties for the metric box, specifically:
     *      -> 'value': a formatted string representation of the metric's value
     *      -> 'growth': a formatted string representation of the metric's growth
     *      -> 'no_data': a boolean indicating whether the entire trend has no
     *                    data within the scope of Compete's knowledge
     *
     * The DOM contents of the metric id on the page will be updated with
     * appropriate values and classes.
     *
     * Note that:
     *   - The original mb object is left unchanged by this method.
     *   - This method is formatted to allow you to iterate over an object
     *     which maps dom ids to metrics definitions, thusly:
     *
     *        $j.each(suchAnObject, search.lazily_load_metric_box);
     *
    */
    
    // Do nothing if this is a teaser
    if (window.IS_TEASER) { return false; }
    
    var val_str = mb.value,                      
        num_val = $j.parseNumber(val_str),      
        growth_str = mb.growth,                
        dv_class,                             
        growth_class,                        
        wrap_el = $j('#' + id);             
    
    if (mb.growth == null) {
        growth_class = 'delta-zero';
        growth_str = 'N/A';
    } else if (mb.growth == 0) {
        growth_class = 'delta-zero';
        growth_str += '%';         
    } else if (mb.growth > 0) {   
        growth_class = 'delta-positive';
        growth_str = '+' + growth_str + '%';
    } else {                               
        growth_class = 'delta-negative';
        growth_str += '%';
    }

    if (isNaN(num_val)) {
        dv_class = 'no-data';
        val_str = 'Historical data only.';
        growth_str = '';
    } else if (num_val > 0) { 
        dv_class = 'value';
    } else {         
        dv_class = 'no-data';
        val_str = 'Historical data only.';
        growth_str = '';      
    }                        
                            
    if (mb.no_data) {      
        dv_class = 'no-data';
        val_str = 'No Data Available';
        growth_str = ''; 
    } 
     
    wrap_el.find('div.data-value').html(val_str).addClass(dv_class);
    wrap_el.find('div.growth').html(growth_str).addClass(growth_class);
};

search.initialize_chart = function () {
  if (!window.IS_TEASER && window.authorized_user) {
    window.CHART = new SWFObject('/site_media/charts/amline.swf', 'main-chart', '699', '250', '8', '#ffffff');
    update_chart();
    
    // Initialize the monthly metric data for comparison only
    if (window.REPORT_TYPE == 'site_comparison') {
      search.setup_metric_comparison();
    }
  }
}

search._metric_compare_handler = function (json) {
  /*
   * Handler function that processes the returned JSON data from
   * get_metric_compare_data
   *
   */
  
  // Setup the title
  // <span>Total Referrals</span><span class="popup-help q5"/>
  var title_help = $j('<span></span>').addClass('popup-help').addClass(json.title_help);
  var title = $j('<span></span>').html(json.metric_title);
  $j('#metric-title').empty().append(title).append(title_help);
  
  // Setup metric values
  // <div class="value">-</div>
  var s1_metric_value = $j('<div></div>').addClass('value').html(commify(json.site1_metric_value));
  var s2_metric_value = $j('<div></div>').addClass('value').html(commify(json.site2_metric_value));
  $j('#s1-metric-value').empty().append(s1_metric_value);
  $j('#s2-metric-value').empty().append(s2_metric_value);
  
  // Setup monthly change values
  var s1_month_value = search._make_delta_div(json.site1_monthly_change);
  var s2_month_value = search._make_delta_div(json.site2_monthly_change);

  $j('#s1-metric-month-change').empty().append(s1_month_value);
  $j('#s2-metric-month-change').empty().append(s2_month_value);
  
  // Setup yearly change values
  var s1_year_value = search._make_delta_div(json.site1_yearly_change);
  var s2_year_value = search._make_delta_div(json.site2_yearly_change);
  
  $j('#s1-metric-year-change').empty().append(s1_year_value);
  $j('#s2-metric-year-change').empty().append(s2_year_value);
};


search._make_delta_div = function (value) {
    /* Utility function: Make a new delta div and return it ready for insertion into the DOM. */
    var prefix = value > 0 ? '+' : '',
        formatted = percentify(value),
        delta_div = $j('<div></div>').addClass('delta').html(prefix + formatted);

    if (value < 0) {
        delta_div.addClass('delta-negative');
    } else if (value > 0) {
        delta_div.addClass('delta-positive');
    }

    return delta_div;
};


search._metric_selected_handler = function(event, dropbox, metric) {
  /*
   * Handler for metric selection
   */
  
  // If this is not the metric selector we want or the metric is already
  // selected, do nothing
  if ((dropbox != 'select-metric1') ||
      (search.current_selected_metric == charted_base_metric)) {
    return false;
  }
  
  $j.getJSON('/data/metric_compare_data/' + site_name + '/' + 
             charted_base_metric + '/', search._metric_compare_handler);
  search.current_selected_metric = charted_base_metric;
}

search.setup_metric_comparison = function() {
  /*
   * Used by the site comparison report to make an async call to get metric
   * comparison data and render it into the page frame. Will also "hook" into
   * metric_selected events raised by the metric selector.
   *
   */
  $j.getJSON('/data/metric_compare_data/' + site_name + '/' + 
             charted_base_metric + '/', search._metric_compare_handler);
  
  // Set the selected metric so that we don't double up on events
  search.current_selected_metric = charted_base_metric;
  
  // Bind the event handler
  $j(document).bind('metric_selected', search._metric_selected_handler);
}

search.submit_form = function() {
  /* Handles the search analytics submission form
  */
  var this_ = $j(this)
  var form_id = this_.attr('id');
    
  // now do your thing
  var t_ = $j("form#" + form_id + " input[name='t']")
  var report_type = t_.attr('value');
  // the broad/exact match special case
  if (t_.hasClass('term_')) {
    report_type = $j("form#" + form_id + " input[name='t']:checked").attr('value');
  }
  
  var site1 = $j("form#" + form_id + " input[name='s1']").attr('value');
  var site2 = $j("form#" + form_id + " input[name='s2']").attr('value');
  
  // if we only get site2, then put it into site1
  if ((!site1 || site1.slice(0, 4) == 'e.g.') && 
     !(!site2 || site2.slice(0, 4) == 'e.g.')) {
    site1 = site2;
    site2 = undefined;
  }
    
  // form is empty
  if (!site1 || site1.slice(0, 4) == 'e.g.') {
    return false;
  }
  
  if (!site2 || site2.slice(0, 4) == 'e.g.') {
    site2 = undefined;
  }

  // set the loading background
  $j("form#" + form_id + " input:first").addClass('loading')
  
  // form is good, do your magic
  var params = {'t': report_type, 's1': site1};
  if (site2) {params.s2 = site2;}
  // use form values to make up a url /_search/ will like
  $j.ajax({'url': this_.attr('action'),
           'data': $j.param(params), 
           'success': function(data) {
             $j("form#" + form_id + " input:first").removeClass('loading');
             _search_success_callback(data);
            }
  });
  return false;
}

search.site_compare_handler = function (e) {
  /*
   * Handles the display of an additional input box if the user wants to
   * "compare" to another site.
   *
   */
  var inputobj = $j('<input type="text" name="s2" value="e.g. amazon.com" tabindex="2"/>');
  $j(this).replaceWith(inputobj);
  $j("form input[name='t']").attr('value', 'search_site_comparison');
  inputobj.bind('focus', utils.handle_input_focus);
  inputobj.bind('blur', referrals.input_blur_handler);
  inputobj.focus();
};

search.report_data_url = function (report_type, target) {
  /*
   * Return the URL of the datasource for a particular report.
   */
  return '/data/' + report_type + '/' + target + '/';
}


// landing page functions here
search.initialize_landing_page = function() {  
  // the category dropdowns
  var filters = cat_dropdown.create_filter('{}','category_filters.search_cat_filtration');
  cat_dropdown.initialize('referrals-category', true, undefined, '', filters);
  
  // all the input handlers
  $j('input').addClass('virgin')
  $j('input').click(function() {$j(this).removeClass('virgin')})
  $j('input').bind('blur', referrals.input_blur_handler)
  
  // the tab selectors
  $j('li.selector').click(function() {
    var link_name = $j(this).attr('id').split('-')[1]; // i.e. referrals_comp_refs
    // grab a section_name (i.e. referrals), and a tab_name (i.e. comp_refs)
    var _ = link_name.split('_')
    var section_name = _[0]
    var tab_name = _.slice(1).join('_')
    referrals.select_tab(section_name, tab_name)
  });
  
  // the forms
  $j('form:not(.category)').submit(search.submit_form);
  $j("form.category").submit(function() {
    // the category id
    var cat_id = cat_dropdown.get_category_id(this.id.replace('_', '-'))
    if (cat_id) {window.location = '/category_referrals/category/' + cat_id + '/';}
    return false;
  });
}


// internal helpers
search._show_deduct_credit_popup = function () {
  /* The interstitial "We'll deduct a credit for this report" popup box
  */
  
  // we jump through a little hoop to make the teaser run when the user
  // *closes* the popup box
  var clicked_ok = false;

  // set-up and display the dialog
  var dialog = $j('<div></div>').addClass('dialog-search');
  dialog.append('<h1>Report Deduction</h1>').
    append('\
      <p>The report you have asked for will deduct from your monthly report \
        allowance and will be automatically deducted from your account when your \
        results are returned. Is this OK? \
      </p>'
    ).
    append('<div class="w"><div class="left">report:</div><div class="right">' + REPORT_TYPE.replace('_', ' ') + '</div></div>')
  if (search.site_name != '') {
    dialog.append('<div class="w"><div class="left">site:</div><div class="right">' + ellipsify(search.site_name, 30).html() + '</div></div>')
  }
  else if (search.category_name != '') {
    dialog.append('<div class="w"><div class="left">category:</div><div class="right">' + search.category_name + '</div></div>');
  }
  else {
    dialog.append('<div class="w"><div class="left">term:</div><div class="right">' + search.term + '</div></div>');
  }
  
  dialog.append('<div class="w"><div class="left">max. results:</div><div class="right">' + commify(search.raw_dataset_size) + '</div></div>');
  dialog.dialog( { 
    bgiframe:true,
    draggable:false,
    modal:true,
    resizable:false,
    width:450,
    height:280,
    zIndex:'9999',
    buttons: {
      "OK": function() {
        clicked_ok = true;
        $j(this).dialog("close");},
      "Cancel": function() {
        $j(this).dialog("close");
      }
    },
    open: function() {$j(this).focus()},
    close: function() {
      if (!clicked_ok) {
        $j('.filters-block').toggle();
        if (window.spin) {
            window.spin.disable();
        }
        if (search.data_url.search(/\?/) > 0) {
          search.data_url += '&is_teaser=1';
        } else {
          search.data_url += '?is_teaser=1';
        }
        window.IS_TEASER = true;
      } else {
        window.IS_TEASER = false;
      }
      referrals.initialize_grid(search.data_url);

      if (!window.IS_TEASER && window.authorized_user) {
        $j('div#pvn-trend-upsell').hide();
        $j('div#chart-container').removeClass('hidden');
      }
      if (!window.IS_TEASER && window.GRID_ACCESS) {
        $j('div#teaser-cover').hide();
        $j('#filters-upsell-block').hide();
      } else {
        $j('#filters-upsell-block').show();
      }
      
      // Initialize the chart/range picker/metric dropdowns for site/compare
      // referral reports
      if ($j.inArray(window.REPORT_TYPE, search.CHART_REPORTS) > -1) {
        search.initialize_chart();
        search.init_metric_box_hook();   
      }
    }
  });
  return false;
}


