String.prototype.urlEncode = function(){ return encodeURIComponent(this); }

// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function getSelectionId(text, li) {
  re = /auto_complete_product_id_/
  product_id = li.id.replace(re, "");
  document.getElementById("auto_complete_product_id").value = product_id;
}

function change_action(form, new_action) {
  form.action = new_action;
}


// ----------------------------------------------------------------------------
// Filters
// ----------------------------------------------------------------------------

// Called when the filter attribute is changed. +filter_type+ is the type of
// filter. Like 'product' for ProductFilter. +element+ is the select box element.
function filter_attribute_changed(filter_type, element, options) {
  var options = options ? options : {};
  var selected       = element.options[element.selectedIndex];
  var attribute_name = selected.value;
  var quantifier     = get_sibling_with_attribute(element, "section", "quantifier");

  // update the quantifier
  var update_url = "/predicates/update_predicate_options/" + filter_type + "/" + encodeURIComponent(attribute_name);

  new Ajax.Updater(quantifier.getAttribute("id"), update_url, { 
                          asynchronous:true, 
                          evalScripts:true, 
                          parameters: { selected_quantifier: options.selected_quantifier,
                                        set_matching_value:  options.set_matching_value },
                          insertion: Element.replace
                          });

  filter_quantifier_changed(filter_type, quantifier, options); 
}

// Called when the filter quantifier is changed. +element+ is the select box
// for the quantifier
function filter_quantifier_changed(filter_type, element, options) {
  var options = options ? options : {};

  // get the quantifier name
  var selected          = element.options[element.selectedIndex]
  var quantifier_name   = selected.value;

  // get the selected attribute
  var attribute_selector = get_sibling_with_attribute(element, "section", "attribute");
  var selected       = attribute_selector.options[attribute_selector.selectedIndex]
  var attribute_name = selected.value;

  // get the attribute wrapper - we will replace the contents of this element
  var attribute_wrapper = get_sibling_with_attribute(element, "section", "attribute_value_wrapper");

  // replace the content of the attribute wrapper with the result of # /predicates/update_attribute_value_input/product/is_new%3F/is
  var update_url = "/predicates/update_attribute_value_input/" + filter_type + "/" + encodeURIComponent(attribute_name) + "/" + encodeURIComponent(quantifier_name);

  new Ajax.Updater(attribute_wrapper.getAttribute("id"), update_url, { 
                          asynchronous:true, 
                          parameters: { set_matching_value: options.set_matching_value },
                          evalScripts:true 
                          });
}

function get_sibling_with_attribute(element, attribute_key, attribute_value) {
  var siblings = element.siblings();
  var sibling_wanted = false;
  siblings.each(
    function(sibling) {
    if( sibling.getAttribute(attribute_key) == attribute_value){
      sibling_wanted = sibling
    }
  });
  return sibling_wanted;
}


// ----------------------------------------------------------------------------
// Ruled Table
// http://www.alistapart.com/articles/tableruler/
// its pretty ugly
// ----------------------------------------------------------------------------


function tableruler()
{
 if (document.getElementById && document.createTextNode)
  {
   var tables=document.getElementsByTagName('table');
   for (var i=0;i<tables.length;i++)
   {
    if(tables[i].getAttribute("ruler")=='true')
    {
     var trs=tables[i].getElementsByTagName('tr');
     for(var j=0;j<trs.length;j++)
     {
      if(trs[j].parentNode.nodeName=='TBODY' && trs[j].parentNode.nodeName!='TFOOT')
       {
       trs[j].onmouseover=function(){this.className='ruled';return false}
       trs[j].onmouseout=function(){this.className='';return false}
     }
    }
   }
  }
 }
}

new Event.observe(window, 'load', function(){tableruler();});

// ----------------------------------------------------------------------------
// Product Listing and Reporting
// ----------------------------------------------------------------------------


// todo, toggle implies that you can switch back. add in that functionality.
function toggle_select_input(object_name, object_attribute)
{
  wrapper_name = object_name + "_" + object_attribute + "_select_input_wrapper";
  input_html   = "<input id='"+ object_name + "_" + object_attribute + "' name='" + object_name + "[" + object_attribute + "]' type='text' />";
  $(wrapper_name).replace(input_html); 
}

// ----------------------------------------------------------------------------
// Product Facts
// ----------------------------------------------------------------------------

function update_sales_channel_names(element, fact_number) 
{
  var selected           = element.options[element.selectedIndex];
  var sales_channel_type = selected.value;

  // product_fact_sales_channel_id_for_fact_0
  new Ajax.Updater("product_fact_sales_channel_id_for_fact_" + fact_number, "/product_facts/sales_channel_names", { 
                        asynchronous: true, 
                         evalScripts: true, 
                         parameters: { sales_channel_type: sales_channel_type,
                                       fact_number: fact_number
                                     },
                         insertion: Element.replace
                        });
}

function add_empty_product_fact() 
{
  new Ajax.Updater("product_facts_table", "/product_facts/add_an_empty_fact", { 
                        asynchronous: true, 
                         evalScripts: true, 
                         parameters: { fact_number: Math.floor(Math.random()*100000) },
                         insertion: Insertion.Bottom
                        });
}

function sales_channel_type_changed(element, update_id, options) 
{
  var options = options ? options : {};
  var selected           = element.options[element.selectedIndex];
  var sales_channel_type = selected.value;
  var subject_name = options['subject_name'] || "predicates[]";

  new Ajax.Updater(update_id, "/predicates/update_sales_channel_ids", { 
                        asynchronous: true, 
                         evalScripts: true, 
                         parameters: { selected_channel_type: sales_channel_type,
                                       select_id_key: update_id,
                                       subject_name: subject_name
                                     },
                         insertion: Element.replace
                        });
}


function showHide(elementid){
  if (document.getElementById(elementid).style.display == 'none'){
	document.getElementById(elementid).style.display = '';
	} 
  else {
	document.getElementById(elementid).style.display = 'none';
   }
 }
  
// ----------------------------------------------------------------------------
// DHTMLX Grid - Amazon Reports
// ----------------------------------------------------------------------------

/*
 * params;
 *  parent: containing HTML element, such as a div
 *  imagePath: top-level path to Grid images
 *  colHeaders: csv string of column heading names
 *  colWidths: csv string of column widths
 *  colAlignments: csv string of column allignments
 *  colTypes: csv string of column types
 *  colSortings: csv string of column sorting types
 *  skin: CSS id of the skin to use
 */
function createGrid(params) {
  var grid = new dhtmlXGridObject(params.parent);
  grid.setIconPath(params.imagePath);
  grid.setImagePath(params.imagePath);

  grid.setHeader(params.colHeaders);
  grid.setInitWidths(params.colWidths);
  grid.setColAlign(params.colAlignments);
  grid.setColTypes(params.colTypes);
  grid.setColSorting(params.colSortings);

  grid.enableMultiline(true);
  grid.enableMultiselect(true);
  grid.enableBlockSelection(true);

  grid.init();
  grid.setSkin(params.skin);

  return grid;
}
