function check_max_qty (element, max_qty) {
  window.setTimeout (check_max_qty_action, 50, element, max_qty);
}

function check_max_qty_action (element, max_qty) {
  var val;
  
  val = parseInt (element.value, 10);
  
  if (element.value.length == 0) {
    element.className = 'good_qty';
    
  } else if (isNaN (val)) {
    element.className = 'bad_qty';
    
  } else if (element.value > max_qty) {
    element.className = 'bad_qty';
    
  } else {
    element.className = 'good_qty';
  }
}


/**
* Changes the medium item image to match that of the thumbnail specified
**/
function change_medium_image(thumbnail) {
  if (thumbnail == null) return;
  
  var img_node = document.getElementById ('medium_image');
  if (img_node == null) return;
  
  var link_node = document.getElementById ('medium_link');
  if (link_node == null) return;
  
  var src = thumbnail.getAttribute ('src');
  src = src.replace ('small', 'medium');
  img_node.setAttribute ('src', src);
  
  var alt = thumbnail.getAttribute ('alt');
  img_node.setAttribute ('alt', alt);
  
  var title = thumbnail.getAttribute ('title');
  img_node.setAttribute ('title', title);
  
  var id = src.split(".");
  id = id[3];
  link_node.setAttribute ('href', 'item_image.php?id=' + id);
}

/**
* Copies the value of a shipping address field into its corresponding billing address field
**/
function billing_copy_matching_field (input) {
  matching_name = input.getAttribute ('name').replace ('Billing', 'Shipping');
  matching_input = input.form.elements[matching_name];
  input.value = matching_input.value;
}

/**
* Copies the values of shipping address fields into their corresponding billing address fields
**/
function update_billing_address_fields () {
  // TODO: make region info be copied as well
  var same_box = document.getElementById ('BillingSameAsShipping');
  if (!same_box) return;
  var fields = ['Address1', 'Address2', 'Suburb', 'Postcode'];
  var disable = same_box.checked? true: false;
  var form = same_box.form;
  for (i in fields) {
    input = form.elements['Billing' + fields[i]];
    if (disable) {
      billing_copy_matching_field (input);
    }
    input.disabled = disable;
  }
  var selects = form.getElementsByTagName ('select');
  var i, select;
  for (i = 0; i < selects.length; ++i) {
    select = selects.item (i);
    if (select.name != 'BillingRegion[]') continue;
    select.disabled = disable;
  }
}


function previous_element (node) {
  if (!node) return null;
  if (node.previousSibling) {
    var prev = node.previousSibling;
    // Ignore nodes that aren't of type ELEMENT_NODE
    while (prev && prev.nodeType != 1) {
      prev = prev.previousSibling;
    }
    if (prev) return prev;
  }
  return null;
}


var shipping_regions = {};
function change_region (node) {
  node.disabled = true;
  
  if (node.parentNode.nodeName == 'DIV') {
    var parent = node.parentNode;
    var divs = parent.parentNode.childNodes;
    var i, div;
    for (i = divs.length - 1; i >= 0; --i) {
      div = divs.item (i);
      if (div == parent) break;
      div.parentNode.removeChild (div);
    }
  } else {
    var tr = node.parentNode.parentNode;
    var prev = previous_element (tr);
    var selects;
    while (prev && prev.nodeName == 'TR') {
      selects = prev.getElementsByTagName ('select');
      if (selects.length == 0) break;
      prev.parentNode.removeChild (prev);
      prev = previous_element (tr);
    }
  }
  
  if (shipping_regions[node.value]) {
    show_sub_regions (node);
    show_shipping (node);
  } else if (node.value > 0) {
    // fetch sub-regions
    var url = 'shop/ajax/get_sub_regions.php?id=' + node.value;
    shipping_regions[node.value] = {};
    queue.request ('get', url, new sub_region_handler(node), null, false);
  } else {
    node.disabled = false;
  }
}

function sub_region_handler (node) {
  this.node = node;
  this.process = function (top_node) {
    // update shipping_regions
    shipping_regions[this.node.value] = {'subname': top_node.getAttribute('sub'), 'subs': {}, 'shipping': {}};
    var children = top_node.getElementsByTagName ('region');
    var i, child;
    for (i = 0; i < children.length; ++i) {
      child = children.item (i);
      shipping_regions[this.node.value]['subs'][child.getAttribute ('id')] = child.getAttribute ('name');
    }
    show_sub_regions (this.node);
    
    children = top_node.getElementsByTagName ('type');
    for (i = 0; i < children.length; ++i) {
      child = children.item (i);
      shipping_regions[this.node.value]['shipping'][child.getAttribute ('id')] = child.getAttribute ('name');
    }
    
    show_shipping (this.node);
  }
}

function show_sub_regions (node) {
  var sub_regions = shipping_regions[node.value];
  
  var count = 0, property;
  for (property in sub_regions['subs']) {
    ++count;
    break;
  }
  if (count == 0) {
    node.disabled = false;
    return;
  }
  
  var options = {'': '-- Please select --'};
  var sub;
  for (sub in sub_regions['subs']) {
    options[sub] = sub_regions['subs'][sub];
  }
  var select = create_select ({'name': node.name}, options);
  select.onchange = function () {change_region (select)};
  
  if (node.parentNode.nodeName == 'DIV') {
    var div = document.createElement ('div');
    var text = document.createTextNode (sub_regions['subname'] + ': ');
    div.appendChild (text);
    div.appendChild (select);
    node.parentNode.parentNode.appendChild (div);
  } else {
    var tr = document.createElement ('tr');
    var td = document.createElement ('td');
    var text = document.createTextNode (sub_regions['subname'] + ' ');
    td.appendChild (text);
    var sup = document.createElement ('sup');
    text = document.createTextNode ('*');
    sup.appendChild (text)
    td.appendChild (sup);
    tr.appendChild (td);
    td = document.createElement ('td');
    td.appendChild (select);
    tr.appendChild (td);
    //-> td      -> tr      -> table                          -> td      -> tr
    node.parentNode.parentNode.parentNode.insertBefore (tr, node.parentNode.parentNode);
  }
  node.disabled = false;
}


function show_shipping (node) {
  var selects = document.getElementsByTagName ('select');
  var i, select, val = 0;
  for (i = 0; i < selects.length; ++i) {
    select = selects.item (i);
    if (select.name == 'Region[]') {
      val = select.value;
      break;
    }
  }
  
  if (val > 0) {
    if (!shipping_regions[val]) return;
    if (!shipping_regions[val]['shipping']) return;
    
    var types = shipping_regions[val]['shipping'];
    var options = {};
    var id, count = 0;
    for (id in types) {
      options[id] = types[id];
      ++count;
    }
    var holder = document.getElementById('shipping_type_selection');
    if (count == 0) {
      holder.className = 'hidden';
      holder.getElementsByTagName ('select').item (0).value = 1;
      return;
    }
    
    var select = create_select ({'name': 'shipping_type'}, options);
    
    var div = document.createElement ('div');
    var text = document.createTextNode ('Shipping type: ');
    div.appendChild (text);
    div.appendChild (select);
    holder.replaceChild (div, holder.firstChild);
    holder.className = '';
  }
}


function verify_js () {
  var forms = document.forms;
  var form_id;
  for (form_id in forms) {
    if (forms[form_id].js) {
      forms[form_id].js.value = 1;
    }
  }
}

var print_r_max_depth = 8;
var print_r_indent = 2;
function print_r (obj, depth, indent_self) {
  
  if (depth === undefined) depth = 0;
  if (indent_self === undefined) indent_self = true;
  
  var indent = '';
  for (var i = 0; i < depth; ++i) {
    indent += ' ';
  }
  if (indent_self) {
    self_indent = indent;
  } else {
    self_indent = '';
  }
  
  var type = typeof obj;
  if (type == 'string') {
    return self_indent + "'" + obj + "'";
  }
  if (type == 'number') {
    return self_indent + obj;
  }
  if (type != 'object') {
    return self_indent + type;
  }
  
  if (depth >= print_r_max_depth) {
    return self_indent + 'object[max. depth]';
  }
  
  var val = self_indent + 'object {\n';
  var first = true;
  for (var key in obj) {
    if (first) {
      first = false;
    } else {
      val += ',\n';
    }
    val += indent;
    for (i = 0; i < print_r_indent; ++i) {
      val += ' ';
    }
    val += print_r(key) + ': ' + print_r(obj[key], depth + print_r_indent, false);
  }
  val += '\n' + indent + '}';
  return val;
}

function forgot_pass () {
  var url = 'forgotten_pass.php';
  var val = document.forms.login.email.value;
  var has_var = false;
  if (val != '') {
    url += '?e=' + encodeURIComponent (val);
    has_var = true;
  }
  val = document.forms.login.redirect.value;
  if (val != '') {
    if (has_var) {
      url += '&redirect=';
    } else {
      url += '?redirect=';
    }
    url += encodeURIComponent (val);
  }
  window.location = url;
}

