// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

document.write = function(str){
  var moz = !window.opera && !/Apple/.test(navigator.vendor);
  
  // Watch for writing out closing tags, we just
  // ignore these (as we auto-generate our own)
  if ( str.match(/^<\//) ) return;

  // Make sure & are formatted properly, but Opera
  // messes this up and just ignores it
  if ( !window.opera )
    str = str.replace(/&(?![#a-z0-9]+;)/g, "&");

  // Watch for when no closing tag is provided
  // (Only does one element, quite weak)
  str = str.replace(/<([a-z]+)(.*[^\/])>$/, "<$1$2></$1>");
  
  // Mozilla assumes that everything in <acronym title="Extensible HyperText Markup Language">XHTML</acronym> innerHTML
  // is actually <acronym title="Extensible HyperText Markup Language">XHTML</acronym> - Opera and Safari assume that it's <acronym title="Extensible Markup Language">XML</acronym>
  if ( !moz )
    str = str.replace(/(<[a-z]+)/g, "$1 xmlns='http://www.w3.org/1999/xhtml'");
   
  // The HTML needs to be within a XHTML element
  var div = document.createElementNS("http://www.w3.org/1999/xhtml","div");
  div.innerHTML = str;
  
  // Find the last element in the document
  var pos;
  
  // Opera and Safari treat getElementsByTagName("*") accurately
  // always including the last element on the page
  if ( !moz ) {
    pos = document.getElementsByTagName("*");
    pos = pos[pos.length - 1];
    
  // Mozilla does not, we have to traverse manually
  } else {
    pos = document;
    while ( pos.lastChild && pos.lastChild.nodeType == 1 )
      pos = pos.lastChild;
  }
  
  // Add all the nodes in that position
  var nodes = div.childNodes;
  while ( nodes.length )
    pos.parentNode.appendChild( nodes[0] );
};


// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;
  // The base Class implementation (does nothing)
  this.Class = function(){};
  
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
    
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
    
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" && 
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
            
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
            
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);        
            this._super = tmp;
            
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
    
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
    
    // Populate our constructed prototype object
    Class.prototype = prototype;
    
    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
    
    return Class;
  };
})();

var MultiCheckboxSelect = $.klass({
  initialize: function() {
    this.last_selected = null;
    this.checkboxes = this.element.find("td.selectable input[type=checkbox]");
  },
  onclick: $.delegate({
    "td.selectable input[type=checkbox]": function(element, event) {
      if (this.last_selected && event.shiftKey) {
        var state = this.last_selected.attr("checked") ? "checked" : undefined;
        var start = this.checkboxes.index(this.last_selected);
        var end = this.checkboxes.index(element);
        var set = this.checkboxes.slice(
            Math.min(start, end),
            Math.max(start, end) + 1);
        $.each(set, function(i, el) { el.checked = state; });
      }
      this.last_selected = element;
    }
  })
});

var TableColumnHider = $.klass({
  initialize: function() {
    this.table = this.element;
    this.column_names = [
      "text",
      "match_type",
      "languages",
      "territories",
      "domain_available",
      "est_ad_position",
      "est_avg_cpc",
      "competition",
      "monthly_searches",
      "est_daily_traffic",
      "max_searches",
      "min_searches",
      "competition_search_ratio",
      "seasonal_trends"];
    this._insertHideIcon();
    this._insertDropdown();
  },
  _insertHideIcon: function() {
    var hide_icon = $('<span class="hide">x</span>');
    $(this.table.find('thead.names th.hideable div')).prepend(hide_icon);
  },
  _insertDropdown: function() {
    var display_dropdown = $('<select><option>---</option></select>');
    display_dropdown.append('<option value="match_type">Match Type</option>');
    display_dropdown.append('<option value="languages">Languages</option>');
    display_dropdown.append('<option value="territories">Territories</option>');
    display_dropdown.append('<option value="domain_available">Domain Available</option>');
    display_dropdown.append('<option value="est_ad_position">Est. Ad. Position</option>');
    display_dropdown.append('<option value="est_avg_cpc">Est. Avg. CPC</option>');
    display_dropdown.append('<option value="competition">Competition</option>');
    display_dropdown.append('<option value="monthly_searches">Local Searches</option>');
    display_dropdown.append('<option value="est_daily_traffic">Est. Daily SEO Traffic</option>');
    display_dropdown.append('<option value="max_searches">Max. Monthly Searches</option>');
    display_dropdown.append('<option value="min_searches">Min. Monthly Searches</option>');
    display_dropdown.append('<option value="competition_search_ratio">Return on Effort Index</option>');
    display_dropdown.append('<option value="seasonal_trends">Seasonal Trends</option>');    
    var table = this.table;
    display_dropdown.change(function(event) {
      table.find("."+event.originalTarget.value).show();
      $.ajax({
        type: "POST",
        url: "/preferences/columns/",
        data: {column: event.originalTarget.value},
        success: function() {          
        },
        error: function() {
        }
      });
      
    });
    var label = $('<label class="display-columns">Show hidden columns:</label>');
    label.append(display_dropdown);
    $(this.table).before(label);
  },
  onclick: $.delegate({
    "th.hideable span.hide": function(element, event) {
      hider = this;
      column_to_hide = $.grep(element.parents('th')[0].className.split(' '), function(elementOfArray, indexInArray) {
        if (hider.column_names.indexOf(elementOfArray) >= 0) {
          return true;
        }
      });
      if (column_to_hide.length > 0) {
        column_to_hide = column_to_hide[0];
        $(this.element.find('.'+column_to_hide)).hide();
        $.ajax({
          type: "DELETE",
          url: "/preferences/columns/",
          data: {column: column_to_hide},
          success: function() {
          },
          error: function() {
          }
        });
      }
    }
  })
});

$(function($) {
  $('table').attach(MultiCheckboxSelect);
	$('th div.filter.domain_available form select').change(function() {
		this.form.submit();
	});
	if ($('th.hideable').length > 0) {
    $($('th.hideable').parents('table')).attach(TableColumnHider);
  }
});
