/*
  JavaScript used by Site Profile and Site Comparison Mashups

  (C) Copyright 2009, Compete Inc.

  The following variables are used by this file:
    site_name
    media_host
    main_site
    member_site
    show_compare
    charted_base_metric
    charted_secondary_metric
    charted_period

  The following window globals have an overriding effect on the behaviour
  of this module.
    CHART_URI_STEM
    PERMALINK_STEM
    CHART_CSV_EXPORT_STEM
*/

function update_chart() {
  // If the chart has not been initialized then do nothing
  if (window.CHART == undefined) { return false; }
  
  var _selected_metric1 = get_selected_metric('select-metric1');
  var _selected_metric2 = get_selected_metric('select-metric2');
  var _metric1_ispro = (_selected_metric1) ? _selected_metric1.is_pro : false;
  var _metric2_ispro = (_selected_metric2) ? _selected_metric2.is_pro : false;
  var chart_uri_stem = window.CHART_URI_STEM || '/metrics/async/charts/';
  var _url = encodeURIComponent(chart_uri_stem + site_name + '/' +
                                charted_base_metric + '+' + charted_secondary_metric + '/' +
                                charted_period + '/')
  var chart = window.CHART;
    
  // If the user is non-pro and they have a permalink for monthly 2y redirect to the login
  if ((charted_period == '2y') && ($j('#chart-upsell').length > 0)) {
    window.location.replace(member_site + '/login/?origin=' + encodeURIComponent(document.URL));
  }
  
  chart.addVariable('settings_file', _url);
  chart.write('chart');
  
  // Disable Embed Link of the metric is a Pro metric or 2y is selected
  if ((_metric1_ispro) || (_metric2_ispro) || (charted_period == '2y')) {
    $j('#embed-graph').addClass('disabled');
  } else {
    $j('#embed-graph').removeClass('disabled');
  }
  
  // update the permalink for this chart
  _update_permalink_url(charted_base_metric, charted_secondary_metric, charted_period)
}

function setup_metrics() {
  //the select boxes
  $j('#select-metric1').bind('change', function() { update_metrics(this.value); });
  $j('#select-metric2').bind('change', function() { update_metrics(charted_base_metric, this.value); });
  
  //hovering and clicking over the metrics
  $j('div.metric').hover(
    function() {
      $j(this).addClass('hovered');
      $j('#' + $j(this)[0].id + '-upsell').removeClass('hidden');
      // IE6 doesn't interpret chained classes, so we need to add a
      // different one if the metric is already selected
      if ($j(this).hasClass('selected')) {$j(this).addClass('hovered-selected')}
    },
    function() {
      $j(this).removeClass('hovered')
      $j('#' + $j(this)[0].id + '-upsell').addClass('hidden');
      // ditto up - IE6 only
      if ($j(this).hasClass('hovered-selected')) {$j(this).removeClass('hovered-selected')}
    }
  );
  
  //attach the proper functions to the metric boxes
  $j('div.metric').bind('click', function() {
    if (!$j(this).hasClass('disabled')) { update_metrics($j(this).attr('id')); }
  });
  
  if (show_compare) {
    //attach to the chart-compare ones
    $j('div.metric-actions > .chart-compare').bind('click', chart_compare_handler);
    
    //attach to the chart-delete ones
    $j('div.metric-actions > .chart-delete').bind('click', chart_delete_handler);
  }
}

function chart_compare_handler(event) {
  metric = $j(this).parent().parent().parent().attr('id')
  $j('#' + metric).unbind('click');
  update_metrics(charted_base_metric, metric);

  //re-binding the change_base_metric function - this is ridiculously hackish
  $j('#' + metric).bind('click', function() {
    $j('#' + metric).unbind('click').bind('click', function() {update_metrics(metric)})
  });
}

function chart_delete_handler(event) {
  metric = $j(this).parent().parent().parent().attr('id')
  $j('#' + metric).unbind('click');
  update_metrics(charted_base_metric);
  $j('#' + metric).removeClass('selected')

  //re-binding the change_base_metric function - this is ridiculously hackish
  $j('#' + metric).bind('click', function() {
    $j('#' + metric).unbind('click').bind('click', function() {update_metrics(metric)})
  });
}

function amGetZoom(chart_id, from, to) {
  // Event raised by amCharts. This is used to get the start date and end date within the graph
  chart_date_from = from;
  chart_date_to = to;
  
  // Disable CSV Exports if a Daily Metric is selected
  var _csv_anchor = $j('#csv-export');
  var _selected_metric1 = get_selected_metric('select-metric1');
  var _metric_type = (_selected_metric1) ? _selected_metric1.type : 'monthly';
  
  _csv_anchor[0].href = 'javascript:void(0);';
  _csv_anchor[0].target = '';
  
  _csv_anchor.removeClass('disabled');
    
  if (authenticated_user) {
    if (window.CHART_CSV_EXPORT_STEM) {
        _csv_anchor[0].href = window.CHART_CSV_EXPORT_STEM + site_name + '/' + charted_base_metric + '+' + charted_secondary_metric + '/' + charted_period + '/?format=csv';
    } else {
        _csv_anchor[0].href = snapshot_site + '/trendcsv/' + site_name + '/' + charted_base_metric + '/?period=' + charted_period;
    }
  } else {
    _csv_anchor[0].href = member_site + '/login/?origin=' + encodeURIComponent(window.location.href);
  }
}

function embed_graph() {
  if ($j(this).hasClass('disabled')) { return false; }
  
  var _selected_metric1 = get_selected_metric('select-metric1');
  var _metric_type = (_selected_metric1) ? _selected_metric1.type : 'monthly';
  
  if (_metric_type == 'daily') {
    var _end_dt = chart_date_to.split('.');
    var _end_dt_date = new Date();
    var _end_yr = '20' + _end_dt[2];
    var _end_mnth = _end_dt[0];
    var _end_day = _end_dt[1];
    _end_dt_date.setFullYear(_end_yr, _end_mnth-1, _end_day);
    var day_diff = 0;
    var month_diff = 0;
    if (charted_period == '1y') {
        day_diff = 365;
    }else if (charted_period == '6m') {
        day_diff = 180;
    }else if (charted_period == '3m') {
        day_diff = 90;
    }else if (charted_period == '30d') {
        day_diff = 30;
    }else if (charted_period == '7d') {
        day_diff = 7;
    }
    var _start_dt_date = new Date()
    _start_dt_date.setFullYear(_end_dt_date.getFullYear(), _end_dt_date.getMonth(), _end_dt_date.getDate() - day_diff);
    var _start_yr = _start_dt_date.getFullYear();
    var _start_month = _start_dt_date.getMonth() + 1;
    var _start_day = _start_dt_date.getDate();
    
    if (_start_month < 10) {
        _start_month = "0"+_start_month;
    }
    if ( _start_day < 10 ) {
        _start_day = "0" + _start_day;
    }
    _start_dt = String(_start_month) + String(_start_day)  + String(_start_yr); 
    _end_dt = String(_end_mnth) + String(_end_day) + String(_end_yr);
    
    var url = snapshot_site + '/embed/?domains=' + site_name + '&metric=' + charted_base_metric + '&start=' + _start_dt + '&end=' + _end_dt;
  } else {
    var url = snapshot_site + '/embed/?domains=' + site_name + '&metric=' + charted_base_metric;
  }
  
  centerX = (screen.availWidth - 710) / 2;
  centerY = (screen.availHeight - 600) / 2;
  
  window.open(url, '_blank', 'location=0,menubar=0,status=0,toolbar=0,scrollbars=1,width=710,height=600,' + 'left=' +  centerX + ',top=' + centerY);

  return false;
}

function setup_permalink_container() {
  /* Creates the permalink container for the profile and comparison pages,
     and attaches it to the #chart-container object. This is called on-load.
  */ 
  var e = $j('#chart-container');
  var container = $j('<div></div>').addClass('permalink-box').hide();
  var close = $j('<img src="/site_media/images/icons/site_profile_delete.gif" alt="close permalink block" />').
                bind('click', function() {container.hide()});
  var input = $j('<input type="text" />') .attr('readonly', 'readonly').bind('focus', function() {$j(this).select()});
  e.append(container.append(input).append(close));
}

function toggle_permalink_container() {
  $j('.permalink-box').toggle();
  $j('.permalink-box > input').focus().select();
}

function hide_permalink_container() {
  $j('.permalink-box').css('display', 'none');
}

function _update_permalink_url(metric1, metric2, period) {
  /* Updates the permalink url on the permalink-box's input box. 
     The url is generated based on the metric(s) and period selected.
     This is mostly called from within update_chart()
  */
  var stem = window.PERMALINK_STEM || snapshot_site;
  var link = stem + '/' + site_name + '/?';
  link += 'metric=' + metric1 + (metric2 != '' ? '+' + metric2 : '');
  if (metric1 == 'attD' || metric1 == 'reachD') {
    link += '&period=' + period;
  }
  else {
  // we gotta jump through hoops here for legacy SEO stuff
    if (period.slice(-1) == 'm') {period = period.slice(0, -1)}
    else if (period == '1y') {period = 12}
    else if (period == '2y') {period = 24}
    else {period = ''}
    link += '&months=' + period
  }
  $j('.permalink-box > input').attr('value', link)
}

function load_zoominfo_box() {
  /*
  */
  $j.getJSON('/s/async/zoominfo/' + site_name + '/', function(json) {
    if (json.description != null && json.description.length > 0) {
      $j('#info-about').
        append($j('<div class="tmp"></div>').
          append($j('<span class="bold">Company: </span>')).
          append($j('<span class="desc"></span>').html(json.name)).
          append($j('<span class="bold"><br/>Location: </span>')).
          append($j('<span class="desc"></span>').html(json.geo))
        ).
        append(json.description)
      $j('#info-about').append('<a href="http://www.zoominfo.com/" target="_blank"><img src="' + media_host + '/site_media/images/partners_zoominfo.jpg" /></a><br/><br/>')
      $j('#info-about').jScrollPane();
      // $j('#about-box div.jScrollPaneContainer').addClass("content-data");
    }
    else {
      $j('#about-box div.box-content').prepend('<div class="title-tab"></div><div class="title-row"></div>')
      $j('#info-about').append('<div class="row"><span class="nodata">No Site Description available</span></div>')
      $j('#info-about').removeClass("content");
      $j('#info-about').addClass("content-data");
      $j('#about-box').append('<a href="http://www.zoominfo.com/" target="_blank" id="zoom-logo"><img src="' + media_host + '/site_media/images/partners_zoominfo.jpg" /></a><br/><br/>')
    }
  });
}


/* TAGS AJAX BOX */

function loadTagsForSite() { 
  /**
   * Loads the tags box for the current site
   * This is called on page load and after every add or remove
   */
  $j.getJSON('/s/load_tags/' + site_name + '/', loadTagsForSiteSuccess); 
}

function loadTagsForSiteSuccess(jsonObject) {
	if (jsonObject.user_is_blacklisted)
	{
		buildBlacklistedTagsBox(jsonObject.all_tags_js_array);
	}
	else
	{
		var all_tags_array = jsonObject.all_tags_js_array;
		buildTagsBox(all_tags_array, jsonObject.user_is_anonymous);
	}
}

function buildBlacklistedTagsBox(arrayOfTags) {
  /**
   * Builds a static tags box for blacklisted users
   * @param {<jsonObject>array} arrayOfTags - array of tag json objects returned from the AJAX request
   */
	var blacklist_msg = '<p>Adding tags has been disabled for your account. For more information, please contact <a href="mailto:membersupport@compete.com">membersupport@compete.com</a>.</p>';

	scroll_wrapper_container = getTagsListWithContainer(arrayOfTags, false, "");
	var tags_content = $j('<div id="blacklisted-tags-content"></div>').append(scroll_wrapper_container);
    
	$j('div#other-tags-ajax-content').html("");
	$j('div#other-tags-ajax-content').append(blacklist_msg).append(tags_content);
	$j('div#other-tags-content').jScrollPane();
}

function buildTagsBox(arrayOfTags, userIsAnonymous)
/**
 * Builds the Tags Box
 * @param {<object>array} arrayOfTags - array of tag json objects returned from the AJAX request
 * @param {boolean} userIsAnonymous - is the user anon or pro/mycompete?
 */
{
	// setup vars that will be used throughout the build process
	var LOGIN_REDIRECT_URL = member_site + '/login?msg=tags&origin=' + main_site + '/m/profiles/site/' + site_name + '/';
	var HAS_ANY_TAGS = arrayOfTags.length > 0;
	var HAS_MY_TAGS = false;
	for (var i in arrayOfTags)
		{ if (arrayOfTags[i].is_tagged) { var HAS_MY_TAGS = true; } }

	// start generating the HTML
	// this first portion will create the the buttons/links to add/filter tags
	var tags_header = $j('<div id="other-tags-header"></div>');
	var add_tag_button = $j('<div class="other-tags-header-icon"></div>').html('Add a New Tag');
	var show_mytags_filter = $j("<h5>").html("Show Only My Tags").addClass("filter-disabled");

	if (userIsAnonymous) // if anonymous, create upsell links
	{
	  add_tag_button.bind('click', function() { 
	    window.location = member_site + '/login/?msg=tags&origin=' + encodeURIComponent(document.URL)
	  });
	}
	else
	{
		if (HAS_ANY_TAGS && HAS_MY_TAGS) { show_mytags_filter.removeClass("filter-disabled").addClass("all-tags-selected"); }
	}
	tags_header.append(add_tag_button);
	tags_header.append(show_mytags_filter);

	// generate the tags list
    // if there are no tags for the site, create a generic msg suggesting them to add
	if (!HAS_ANY_TAGS)
	{
		if (userIsAnonymous)
		{
			$j('div#other-tags-ajax-content').html('<p>There are no tags for this site. <a href="'+LOGIN_REDIRECT_URL+'">Be the first.</a></p>');
		}
		else
		{
			$j('div#other-tags-ajax-content').html('<p>There are no tags for this site. <span id="other-tags-dialog-link">Be the first.</span></p>');
			$j('span#other-tags-dialog-link').bind('click', function() { $j('div#other-tags-dialog').dialog('open'); });
		}
	}
    // else, loop over each tag and create elements for it
	else
	{
		scroll_wrapper_container = getTagsListWithContainer(arrayOfTags, userIsAnonymous, LOGIN_REDIRECT_URL);
		var tags_content = $j('<div id="tags-content"></div>').append(show_mytags_filter).append(scroll_wrapper_container);
        
        $j('div#other-tags-ajax-content').html("");
		$j('div#other-tags-ajax-content').append(tags_header).append(tags_content);
        
		$j('div#other-tags-content').jScrollPane();
		bindTagsBoxEvents(arrayOfTags, userIsAnonymous, HAS_MY_TAGS);
	}
}

function getTagsListWithContainer(arrayOfTags, userIsAnonymous, loginRedirectUrl)
  /**
   * Gets a container (div) with a tags list
   * @param {<jsonObject>array} arrayOfTags
   * @param {boolean} userIsAnonymous - anon or mycompete/pro?
   * @param {string} loginRedirectUrl - where to redirect them to if they're anon and they click plus/minus
   * @return {domElement} - div element
   */
{
	// note: this was originally a UL (instead of a table) but JScrollPane conflicted with the hovering of the LIs
	// in IE7 it would only hover the contents of the text instead of the whole LI (but this did work when JScrollPane was disabled)
	var tags_table = $j("<table>").attr("id", "tag-soup");

	$j.each(arrayOfTags, function(i, tagObj)
	{
		var formatted_tag_name = formatTagName(tagObj.tag_name, tagObj.cloud_step);
		var tag_link = $j("<a>").html(formatted_tag_name).attr("href", main_site + "/s/tag/" + tagObj.tag_name + "/");
		var tag_table_cell = $j("<td>").append(tag_link);
		tag_table_cell.attr("id", "other-tags-" + tagObj.tag_id)

		// if they're anonymous, add a login redirect link
		if (userIsAnonymous)
		{
			var add_remove_button = $j("<a><div></div></a>").attr("href", loginRedirectUrl);
			tag_table_cell.addClass("tc" + tagObj.cloud_step);
		}
		// else, include the add/remove button based on if it's tagged
		else
		{
			if (tagObj.is_tagged)
			{
				var add_remove_button = $j("<div>").attr("id", "other-tags-remove-" + tagObj.tag_id);
				tag_table_cell.addClass("tc" + tagObj.cloud_step + "-mytag");
			}
			else
			{
				var add_remove_button = $j("<div>").attr("id", "other-tags-add-" + tagObj.tag_id);
				tag_table_cell.addClass("tc" + tagObj.cloud_step);
			}
		}

		tag_table_cell.prepend(add_remove_button)
		tags_table.append($j("<tr>").append(tag_table_cell));
	});

	// now append of all of the dom elems and update the box
	var tags_container = $j('<div id="other-tags-content" class="for-jscroll"></div>');
	tags_container.append(tags_table);
	
	var scroll_wrapper_container = $j("<div>").attr("id", "other-tags-jscroll-wrapper");
	scroll_wrapper_container.append(tags_container);

	return scroll_wrapper_container;
}

function formatTagName(tagName, cloudStep)
  /**
   * Formats tag for display, like a template filter would
   * @param {String} tagName - tag to format
   * @param {String} cloudStep - number of cloud group to base how many max chars
   * @return {String} formatted tagName
   */
{
	var max_chars_cloud_map = { "1":14, "2":13, "3":11, "4":9 }; // how many chars can each cloud support
	var max_chars_for_tag = max_chars_cloud_map[cloudStep];

	if (tagName.length > max_chars_for_tag)
	{
		tagName = ellipsify(tagName, max_chars_for_tag);
	}

	return tagName;
}

function bindTagsBoxEvents(arrayOfTags, userIsAnonymous, userHasTags)
  /**
   * After the tags box is created, bind the events to it
   * @param {<jsonObject>array} arrayOfTags
   * @param {boolean} userIsAnonymous - anon or mycompete/pro?
   * @param {boolean} userHasTags - does the user have any tags for this site
   */
{
    // if the user is not anonymous, include the add/remove/filter tag events
	if (!userIsAnonymous)
	{
		$j('div.other-tags-header-icon').bind('click', function() { $j('div#other-tags-dialog').dialog('open'); });
		
		if (userHasTags) { $j('div#other-tags h5').bind('click', filterAllOrMyTags); }

		$j.each(arrayOfTags, function(i, tagObj)
        {
            if (tagObj.is_tagged) // add removeTag/minus event
            {
                $j('div#other-tags-remove-'+tagObj.tag_id).bind('click', function() { removeTag(tagObj.tag_id); });
            }
            else  // add voteUpTag/plus event
            {
				$j('div#other-tags-add-'+tagObj.tag_id).bind('click', function() { voteUpTag(tagObj.tag_name); });
            }
        });
	}

    // add the hover events, which will either add/remove tags or redirect to login
	$j.each(arrayOfTags, function(i, tagObj)
	{
		// used to use a simple toggle for a hover class but ie6 can't handle multiple classes
		// this now string appends/replaces to use the correct hover class
		// e.g. tc3-mytag-hover, tc3-mytag
		var add_hover_class = function(e)
		{
			var old_class = $j(this).attr('class');
			var new_class = old_class + "-hover";
			$j(this).removeClass(old_class);
			$j(this).addClass(new_class);
		}
		var remove_hover_class = function(e)
		{
			var old_class = $j(this).attr('class');
			var new_class = old_class.replace('-hover', '');
			$j(this).removeClass(old_class);
			$j(this).addClass(new_class);
		}
		$j('td#other-tags-'+tagObj.tag_id).bind('mouseover', add_hover_class);
		$j('td#other-tags-'+tagObj.tag_id).bind('mouseout', remove_hover_class);
	});
}

function voteUpTag(tagName) {
  /* Votes up the tag for the current site.
     Called when the plus button is clicked on
     @param {string} tagName - tag entered by the user or voted up
  */
	$j.getJSON('/s/add_tag/' + tagName + '/' + site_name + '/', voteUpTagSuccess);
}

function voteUpTagSuccess(jsonObject)
{
	if (!jsonObject.error_message)
	{
		var all_tags_array = jsonObject.all_tags_js_array;
		buildTagsBox(all_tags_array, jsonObject.user_is_anonymous);
	}
}

function removeTag(tagId) {
  /**
   * Removes the association from the tag with the given ID
   * Called when the minus button is clicked on
   * @param {int} tagId - id of the tag to remove
   */
	$j.getJSON('/s/remove_tag/' + tagId + '/' + site_name + '/', removeTagSuccess);
}

function removeTagSuccess(jsonObject)
{
	// if my tags were selected when tag was removed, go back there after the build
	var my_tags_selected = $j('table#tag-soup').hasClass("my-tags-selected");

	// only go back if they have my tags, otherwase go back to all
	var still_has_my_tags = false;
	var all_tags_array = jsonObject.all_tags_js_array
	for (var i in all_tags_array)
		{ if (all_tags_array[i].is_tagged) { var still_has_my_tags = true; } }

	buildTagsBox(jsonObject.all_tags_js_array, jsonObject.user_is_anonymous);
	// if my tags were selected when tag was removed, go back there after the build
	if (my_tags_selected && still_has_my_tags) { filterAllOrMyTags(); }
}

function filterAllOrMyTags()
  /**
   * Depending on the view, either shows all tags or only my tags
   * and updates the link to reflect that
   */
{
	var show_allormy_tags_link = $j("div#other-tags h5");
	//$j('div#other-tags-content').jScrollPaneRemove();

	$j('table#tag-soup').toggleClass("my-tags-selected");

	if ($j('table#tag-soup').hasClass("my-tags-selected"))
	{
		show_allormy_tags_link.text('Show All Tags');
		show_allormy_tags_link.addClass("my-tags-selected");
		show_allormy_tags_link.removeClass("all-tags-selected");
	}
	else
	{
		show_allormy_tags_link.text('Show Only My Tags');
		show_allormy_tags_link.addClass("all-tags-selected");
		show_allormy_tags_link.removeClass("my-tags-selected");
	}

	$j('div#other-tags-content').jScrollPane();
}

function validateTagFormat()
  /**
   * Called everytime a key is pressed in the add tag field,
   * validates and displays a message if it isn't
   */
{
    var tag_format_regex = /[^a-zA-Z0-9-]/; // anything not alphanumeric or dash "-"
    var tag_name_input_obj = $('id_tag_name');
    if (tag_format_regex.test(tag_name_input_obj.value))
    {
        updateAddRemoveTagStatus("failure", 'Only letters and numbers are allowed, use "-" for spaces');
        $('add_tags_submit').disabled = true;
    }
    else
    {
        updateAddRemoveTagStatus("", "");
        $('add_tags_submit').disabled = false;
    }
}
