var symantec = symantec || {};

symantec.filters = {
  products_without_versions: [],
  product_versions_cache: {},
  filter_wildcard: 'all',
  items_per_page: 50, //default items per page TODO: set this in Drupal.settings on server side
  destination_page: 0,
  filter_update_targets: [],
  filter_update_map: {
    'filter-select-topics' : 'topic',
    'filter-select-ideas-status' : 'ideas_status',
    'filter-select-location-taxonomy': 'location',
    'filter-select-groups': 'groups'
  }
};

$(document).ready(function() {
  symantec.filters.setup_filter_selection();
  symantec.filters.set_filter_context();
  symantec.filters.update_filter_state();
  symantec.lib.setup_tooltips();
});

/**
 * Grabs the version for the selected products
 */
symantec.filters.update_product_versions = function(selected_version_val) {
  var selected_product = $('#filter-select-products').val() || $('input.filter-current-product').val();
  var $product_versions_filter = $('#filter-select-product-versions');
  var grab_versions = true;
  var selected_version_val = selected_version_val || '';

  var default_version_options = '<option value="">All Versions</option>';

  if (selected_product == this.filter_wildcard) {
    grab_versions = false;
    $product_versions_filter.html(default_version_options);
  }

  for (product_id in this.products_without_versions) {
    if (product_id == selected_product) {
      grab_versions = false;
      $product_versions_filter.html(default_version_options);
      break;
    }
  }

  for(product_id in symantec.filters.product_versions_cache) {
    if (product_id == selected_product) {
      grab_versions = false;
      $product_versions_filter.html(symantec.filters.product_versions_cache[product_id]).show();
      break;
    }
  }

  if (grab_versions) {
    var ajax_endpoint = Drupal.settings.basePath + 'product-versions';
    var post_data = {
      product_tid: selected_product,
      content_type: Drupal.settings.symantec.context_content_type
    };
    $.post(ajax_endpoint, post_data, function(response) {
      var response_data = eval('(' + response + ')');
      if (response_data['status']) {
        if (response_data['data']) {
          $product_versions_filter.html(response_data['data']).show();
          symantec.filters.product_versions_cache[selected_product] = response_data['data'];
          if (selected_version_val) {
            $product_versions_filter.val(selected_version_val);
          } else {
            $product_versions_filter.val('');
          }
        } else {
          symantec.filters.products_without_versions.push(selected_product);
          $product_versions_filter.html(default_version_options);
        }
      }
    });
  }
}

/**
 * Sets up change events for filter selection
 */
symantec.filters.setup_filter_selection = function() {
  $('.filter-taxonomy, .sort, #filter-select-authors, #filter-select-ideas-status,.dropdown-language-filter, #filter-select-groups').unbind('change').change(function() {

    symantec.filters.update_filter_state();

    if ($(this).attr('id') == 'filter-select-authors') {
      // update filters downstream of this one
      if ($('#filter-select-location-taxonomy').length) {
        symantec.filters.filter_update_targets.push('location');
      }
      symantec.filters.filter_update_targets.push('product');
      symantec.filters.update_product_versions();
      symantec.filters.filter_update_targets.push('topic');
      if ($('.dropdown-language-filter')) {
        symantec.filters.filter_update_targets.push('language');
      } else if ($('#filter-select-ideas-status')) {
        symantec.filters.filter_update_targets.push('ideas_status');
      }
    } else if ($(this).attr('id') == 'filter-select-products') {
      symantec.filters.update_product_versions();
      symantec.filters.filter_update_targets.push('topic');
      // update filters downstream of this one
      if ($('.dropdown-language-filter')) {
        symantec.filters.filter_update_targets.push('language');
      } else if ($('#filter-select-ideas-status')) {
        symantec.filters.filter_update_targets.push('ideas_status');
      }
      if ($('#filter-select-groups')) {
        symantec.filters.filter_update_targets.push('groups');
      }
    } else if ($(this).attr('id') == 'filter-select-location-taxonomy') {
      // grab all available filters
      var $updated_filter = $(this);
      var collect_filters_flag = false;
      $('.filters select').each(function() {
        if ($updated_filter.attr('id') == $(this).attr('id')) {
          collect_filters_flag = true;
          return;
        }

        if (collect_filters_flag) {
          if (symantec.filters.filter_update_map[$(this).attr('id')]) {
            symantec.filters.filter_update_targets.push(symantec.filters.filter_update_map[$(this).attr('id')]);
          } else {
            // exceptions
            if ($(this).hasClass('dropdown-language-filter')) {
              symantec.filters.filter_update_targets.push('language');
            }
          }
        }
      });
    } else if ($(this).attr('id') == 'filter-select-product-versions') {
      symantec.filters.filter_update_targets.push('topic');
      // update filters downstream of this one
      if ($('.dropdown-language-filter')) {
        symantec.filters.filter_update_targets.push('language');
      } else if ($('#filter-select-ideas-status')) {
        symantec.filters.filter_update_targets.push('ideas_status');
      }

      if ($('#filter-select-groups')) {
        symantec.filters.filter_update_targets.push('groups');
      }
    } else if ($(this).attr('id') == 'filter-select-topics') {
       // update filters downstream of this one
      if ($('.dropdown-language-filter')) {
        symantec.filters.filter_update_targets.push('language');
      } else if ($('#filter-select-ideas-status')) {
        symantec.filters.filter_update_targets.push('ideas_status');
      }
      if ($('#filter-select-groups')) {
        symantec.filters.filter_update_targets.push('groups');
      }

    } else if ($(this).attr('id') == 'filter-select-ideas-status') {
      symantec.filters.refresh_items();

    } else if ($(this).hasClass('dropdown-language-filter')) {
      if ($('#filter-select-groups')) {
        symantec.filters.filter_update_targets.push('groups');
      } else {
        symantec.filters.refresh_items();
      }
    } else if ($(this).hasClass('sort')) {
      symantec.filters.refresh_items();

    } else if ($(this).hasClass('dropdown-filter-groups')) {
      symantec.filters.refresh_items();
    }
    symantec.filters.sync_filter_choices();
  });

  // reset the destination page if change of items per page after pagination
  $('select.items-per-page-selector').unbind('change').change(function() {
    symantec.filters.destination_page = 0;
    symantec.filters.refresh_items();
  });

  $('.result-items-wrapper .pager-control a').click(function() {
     var href = $(this).attr('href');
     var page_part = href.match(/[\\?&]page=(\d+)/);
     if (page_part) {
       var page_number = page_part[1];
       symantec.filters.destination_page = page_number;
     } else {
       symantec.filters.destination_page = 0;
     }
     symantec.filters.refresh_items();
     return false;
   });
}

/**
 * Synchs filter choices based on the last choice made
 */
symantec.filters.sync_filter_choices = function() {

  if (this.filter_update_targets) {

    while (this.filter_update_targets.length) {
      var update_target = this.filter_update_targets.shift();
      var post_data = {
        filter_type: update_target,
        content_type: Drupal.settings.symantec.context_content_type,
        filter_taxonomy: this.filter_taxonomy,
        filter_author: this.filter_author
      }

      if (update_target == 'language' && $('.dropdown-language-filter')) {
        post_data['filter_language'] = $('.dropdown-language-filter').val();
      }


      if (update_target == 'groups' && $('#filter-select-groups')) {
      if ($('.dropdown-language-filter')) {
        post_data['filter_language'] = $('.dropdown-language-filter').val();
      }
        post_data['filter_groups'] = $('#filter-select-groups').val() || 'all';
      }

      var do_refresh = (this.filter_update_targets.length == 0) ? true : false;

      var ajax_endpoint = Drupal.settings.basePath + 'filters-sync';
      $.post(ajax_endpoint, post_data, function(response) {
        var response_data = eval('(' + response + ')');
        if (response_data['status']) {
          if (response_data['topic']) {
            $('#filter-select-topics').html(response_data['topic']).show();
          } else if (response_data['product']) {
            $('#filter-select-products').html(response_data['product']).show();
          } else if (response_data['author']) {
            $('#filter-select-authors').html(response_data['author']).show();
          } else if (response_data['ideas_status']) {
            $('#filter-select-ideas-status').html(response_data['ideas_status']).val('all');
          } else if (response_data['language']) {
            $('.dropdown-language-filter').html(response_data['language']).show();
          } else if (response_data['location']) {
            $('#filter-select-location-taxonomy').html(response_data['location']).val('all');
          } else if (response_data['groups']) {
            $('#filter-select-groups').html(response_data['groups']).val('all');
          }
        }

        if (do_refresh) {
          symantec.filters.refresh_items();
        }
      });
    }
  } else {
    symantec.filters.refresh_items();
  }
}

/**
 * Updates the href on the RSS icon
 */
symantec.filters.update_rss_icon = function() {
  var existing_feed_url = $('.filters-rss-icon').attr('href');
  var url_parts = existing_feed_url.replace(Drupal.settings.basePath, '').split('/');
  var new_feed_url = url_parts[0] + '/' + url_parts[1] + '/' + this.filter_taxonomy + '/' + this.filter_language + '/' + this.filter_author + '/' + (this.filter_groups || 'all');
  $('.filters-rss-icon').attr('href', Drupal.settings.basePath + new_feed_url);
}

/**
 * Updates the filter state data items, based on initial and current choices
 */
symantec.filters.update_filter_state = function() {
  var filters = [];

  var filters_obj = this;

  $('select.filter-taxonomy, input.filter-taxonomy').each(function() {
    if ($(this).val() && $(this).val() != symantec.filters.filter_wildcard) {
      filters.push($(this).val());
    }

    if ($(this).hasClass('dropdown-filter-products') || $(this).hasClass('filter-current-product')) {
      filters_obj.filter_product = $(this).val();
    }

    if ($(this).hasClass('dropdown-filter-version')) {
      filters_obj.filter_product_version = $(this).val();
    }

    if ($(this).attr('id') == 'filter-select-location-taxonomy' || $(this).hasClass('filter-hidden-location')) {
      filters_obj.filter_location = $(this).val();
    }

    if ($(this).hasClass('dropdown-filter-topics')) {
      filters_obj.filter_topic = $(this).val();
      if (filters_obj.filter_topic != 'all') {
        var cookie_value = $("option[@value='" + filters_obj.filter_topic + "']", $('#filter-select-topics')).text();
        filters_obj.last_topic_viewed = cookie_value;
      }
    }

    if ($(this).hasClass('dropdown-filter-ideas-status')) {
      filters_obj.filter_ideas_status = $(this).val();
    }

  });

  if ($('.dropdown-language-filter').length) {
    this.filter_language = $('.dropdown-language-filter').val();
  } else {
    this.filter_language = 'all';
  }

  if ($('#filter-select-authors').length) {
    this.filter_author = $('#filter-select-authors').val();
  } else {
    this.filter_author = 'all';
  }

  if ($('#filter-select-groups')) {
    this.filter_groups = $('#filter-select-groups').val();
   }else {
    this.filter_groups = 'all';
  }

  //do we have a community context?
  var community_context = Drupal.settings.symantec.context_community_tid;
  if (community_context) {
    filters.push(community_context);
  }

  if (filters.length) {
    this.filter_taxonomy = filters.join(',');
  } else {
    this.filter_taxonomy = 'all';
  }

  this.sort_state = $('select.sort').val();

  this.items_per_page = $('.items-per-page-selector').val() || this.items_per_page;

  symantec.filters.update_rss_icon();

  this.set_filter_state_cookie();
}

/**
 * Refreshes the items based on current filter/sorting state
 */
symantec.filters.refresh_items = function() {
  this.update_filter_state();

  var post_data = {
    context_string : this.get_context_string(),
    filter_content_type: Drupal.settings.symantec.context_content_type,
    filter_taxonomy: this.filter_taxonomy,
    sort_state: this.sort_state,
    items_per_page: this.items_per_page,
    filter_author: this.filter_author,
  };

  if ($('.dropdown-language-filter')) {
    post_data['filter_language'] = $('.dropdown-language-filter').val() || 'all';
  }

  if ($('.dropdown-filter-groups')) {
    post_data['filter_groups'] = $('.dropdown-filter-groups').val() || 'all';
  }

  var $destination = $('.result-items-wrapper');

  $destination.html('<h2 class="loading-indicator">Loading</h2>');

  var ajax_endpoint = Drupal.settings.basePath + 'connect-items';

  if (this.destination_page && this.destination_page != 0) {
    ajax_endpoint += '?page=' + this.destination_page;
  }

  $.get(ajax_endpoint, post_data, function(response) {
    var response_data = eval('(' + response + ')');
    $destination.html(response_data['results']);
    symantec.lib.setup_tooltips();
    symantec.filters.setup_filter_selection();

    //bind voting behavior for voting widgets
    if (Drupal.behaviors.voteUpDownAutoAttach) {
      Drupal.behaviors.voteUpDownAutoAttach();
    }

    // bind onclick events for topic tracking cookie setup
    if (symantec.filters.last_topic_viewed) {
      $('.filter-node-link a').click(function() {
        $.cookie('last_topic_viewed', symantec.filters.last_topic_viewed, {path: '/'});
      });
    }

  });

}

/**
 * Stores the filter state to a cookie so it can be returned to later
 */
symantec.filters.set_filter_state_cookie = function() {
  var context_suffix = this.get_context_string();
  //this.destination_page
  var cookie_data = '{"filter_content_type": "' + Drupal.settings.symantec.context_content_type +
    '", "filter_product": "' + this.filter_product
    + '", "filter_product_version": "' + this.filter_product_version
    + '", "filter_topic": "' + this.filter_topic
    + '", "filter_taxonomy": "' + this.filter_taxonomy
    + '", "filter_author": "' + this.filter_author
    + '", "filter_language": "' + (this.filter_language || 'all')
    + '", "filter_groups": "' + (this.filter_groups || 'all')
    + '", "filter_location": "' + (this.filter_location || 'all')
    + '", "sort_state": ' + this.sort_state
    + ', "items_per_page": ' + this.items_per_page
    + ', "current_page": ' + this.destination_page + '}';
  $.cookie('filter_state_' + context_suffix, cookie_data);
}

/**
 * Gets the context string from the context meta tag
 */
symantec.filters.get_context_string = function() {
  var context_string = $('meta[name=connect_context_js]').attr('content');
  return context_string;
}

/**
 * Sets the context of the filter dropdowns based on the cookie context
 */
symantec.filters.set_filter_context = function() {
  var context_string = this.get_context_string();
  var cookie_data = eval('(' + $.cookie('filter_state_' + context_string) + ')');

  if (cookie_data) {
    $('select.dropdown-filter-products').val(cookie_data['filter_product']);
    $('select.dropdown-filter-topics').val(cookie_data['filter_topic']);
    $('select.dropdown-language-filter').val(cookie_data['filter_language']);
    $('select.dropdown-filter-groups').val(cookie_data['filter_groups']);
    $('#filter-select-location-taxonomy').val(cookie_data['filter_location']);
    $('#filter-select-authors').val(cookie_data['filter_author']);
    $('select.sort').val(cookie_data['sort_state']);
    $('select.items-per-page-selector').val(cookie_data['items_per_page']);

    if ($('select.dropdown-filter-products').val() != this.filter_wildcard) {
      var current_product = ($('select.dropdown-filter-products').length) ? $('select.dropdown-filter-products').val() : $('input.filter-current-product').val();
      var selected_version = (cookie_data['filter_product_version']) ? cookie_data['filter_product_version'] : null;
      symantec.filters.update_product_versions(selected_version);
    }

  } else {
    if ($('select.dropdown-filter-products').val() != this.filter_wildcard) {
      //var current_product = ($('select.dropdown-filter-products').length) ? $('select.dropdown-filter-products').val() : $('input.filter-current-product').val();
      symantec.filters.update_product_versions();
    }
  }
}
