// This is a library of generally useful Javascript functions
// which build upon Prototype.js


// REQUIRES Prototype.js
// Get all <tr>s in table_id with class 'class_name'
// Useful for doing dynamic table generation with specific row-ids
// i.e. you have a rows with an id 'row-1', 'row-2', 'row-3'
// and add an additional row if the rows have a class
// you can do var row = document.createElement('tr')
// row.id = 'row-' + (getTableRowsWithClass('table-id', 'classname').length + 1).toString();
function getTableRowsWithClass(table_id, class_name) {
    var table = $(table_id);
    var rows = table.getElementsByTagName('tr');
    var answerRows = [];
    for (var i=0; i<rows.length; i++) {
        if (Element.hasClassName(rows[i], class_name)) {
            answerRows.push(rows[i]);
        }
    }
    return answerRows;
};


// REQUIRES Prototype.js
// Returns a valid row_id of the form 'row-idcount'
// Useful when building table-rows dynamically
function findValidRowId(row_id) {
    var count = 0;
    var element_id = row_id + '-' + count.toString();
    while ($(element_id)) {
        count++;
        element_id = row_id + '-' + count.toString();
    }
    return element_id;
};

// REQUIRES Prototype.js
// SelectionWatcher takes four parameters:
// - selector
// - url
// - formname
// - update_element
// It watches for "change" events on the <select> element 
//  with id "selector" and then serialises the form variables
// in the form with id "fornmame", it then makes a GET "Ajax"
// request using the supplied  "url", and when this request
// returns, updates the contents of element "update_element"
var SelectionWatcher = Class.create();
SelectionWatcher.prototype = {
    initialize: function(selector, url, formname, update_element) {
        this.selector = $(selector);
        this.url = url;
        this.formname = formname;
        this.update_element = update_element;
        //assigning our method to the event
        this.selector.onchange = this.handle_change.bindAsEventListener(this);
    },
    handle_change: function(evt) {
        element = $(this.update_element);
        var pars = Form.serialize(this.formname);
        var request = new Ajax.Updater(element, this.url, { method: 'get', parameters: pars, onComplete: sortTable }); 
    }
};

var RadioWatcher = Class.create();
RadioWatcher.prototype = {
    initialize: function(selector, url, formname, update_element, on_complete) {
        this.selector = $(selector);
        this.url = url;
        this.formname = formname;
        this.update_element = $(update_element);
        this.selector.onclick = this.handle_change.bindAsEventListener(this);
        this.oncomplete = on_complete;
    },

    handle_change: function(evt) {
        var pars = Form.serialize(this.formname);
        var country = $(this.formname).serialize(true)['country'];
        var request = new Ajax.Updater(this.update_element, this.url, { 
                            method: 'get', 
                            parameters: pars,
                            onComplete: this.oncomplete(this.selector.value, this.url, country)
                          }); 
    }
};

function toggleInvoice(type, url, country){
  var response = new Ajax.Request(url, {
      method: 'get',
      parameters: { customer_type: type, return_html: '', country: country },
      onSuccess: function(transport){
          var cost = parseFloat(transport.responseText);
          var radio = $('payment_method2')
          if(cost>50){
            radio.enable();
          }else if(cost<50){
            if(radio.checked){
              radio.checked = false;
            }
            radio.disable();
          }
      }
  });
}

function sortTable(){
    sortables_init();
};

// simple function to place in the onclick of an object
// will delete element 'element_id' after prompting the user
// 'description' is used in the confirmation dialog
// "Are you sure you want to delete this 'description'?"
// Always returns false
// e.g. <a href="#" onclick="return confirmDeleteElement('an-element', 'element')">delete</a?
function confirmDeleteElement(element_id, description) {
    if (confirm("Are you sure you want to delete this " + description + "?")) {
        var element_to_delete = $(element_id);
        element_to_delete.parentNode.removeChild(element_to_delete);
    }
    return false;
};


// function for checking text inputs that need to be disabled by checkboxes
// needs prototype
// Watches checkbox and alters the state of element input accordingly
function watchCheckbox(checkbox, input){
    element = $(input);
    check = $(checkbox);
    if(check.checked && check.value == 'on'){
        element.disabled = '';
    }else{
        element.disabled = 'disabled';
    }
};

// Display the Attached URL in a popup
function popUp(url) {
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(url, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=600,left = 450,top = 250');");
};

// Creates a Link with a trashcan icon and a "Remove" link, with an onclick
// handler which confirms the delete of the element
function createTrashcanLink(element_id, description) {
    var trashcan_img = document.createElement('img');
    trashcan_img.setAttribute('src','/trashcan.gif');
    trashcan_img.width = 12;
    trashcan_img.height = 12;
    trashcan_img.border = 0;
    var trashcan_link = document.createElement('a');
    trashcan_link.href='#';
    trashcan_link.onclick = function(){return confirmDeleteElement(element_id, description)};
    var trashcan_link_text = document.createTextNode(' Remove');
    trashcan_link.appendChild(trashcan_img);
    trashcan_link.appendChild(trashcan_link_text);
    return trashcan_link;
};

function createPaperclick() {
    var paperclick_img = document.createElement('img');
    paperclick_img.setAttribute('src','/paperclip.gif');
    paperclick_img.width = 15;
    paperclick_img.height = 15;
    paperclick_img.border = 0;
    return paperclick_img;
};

// Requires prototype
// Hides branches of the tree
// and sets the onlclick functions
function setupTree() {
  //Hide the tree branches
  $$('.branch_level1').each(function(e){
    Element.hide(e);
  });
  $$('.branch_level2').each(function(e){
    Element.hide(e);
  });

  $$('.expand_link_level0').each(function(e){
    Event.observe(e, 'click', function(et){
      toggleChildren(this, 'branch_level1');
    });
  });

  $$('.expand_link_level1').each(function(e){
    Event.observe(e, 'click', function(et){
      toggleChildren(this, 'branch_level2');
    });
  });

}

function toggleChildren(element, klass){
  if(element.innerHTML == '+'){
    element.innerHTML = '-';
  }else if(element.innerHTML == '-'){
    element.innerHTML = '+';
  }

  next_level = element.up().select('ul.'+klass);
  for(x=0;x<next_level.length;x++){
    next_level[x].toggle();
  }
}

