/*
 * Required helper functions
 */
Array.prototype.array_cut = function(n) {
  if(n>=0 && n<this.length) {
    if(n<this.length) {
      var x = -1;
      while((++x)<this.length) {
        if(x>=n) {
          this[x] = this[x+1];
        }
      }
    }
    this.pop();
  }
};


Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
};


/*
 * Postcode field instructions
 */
Event.observe(window, 'load', function() {
  if(typeof(postcodeSearchUrl) == 'undefined') alert('You must define postcodeSearchUrl');
  if(typeof(postcodeSearchDefault) == 'undefined') alert('You must define postcodeSearchDefault');
  if(typeof(postcodeSearchSpecifyZone) == 'undefined') alert('You must define postcodeSearchSpecifyZone');
  lastRequest = 'startup';

  var postcodeValue = postcodeSearchDefault;
  if($('auction_postcode').value == '' || $('auction_postcode').value == postcodeValue) {
    $('auction_postcode').value = postcodeValue;
    Element.setStyle('auction_postcode', {color:'#888'});
  }
  Event.observe('auction_postcode', 'focus', function(event) {
    if($('auction_postcode').value == postcodeValue) {
      $('auction_postcode').value = '';
      Element.setStyle('auction_postcode', {color:'#000'});
    }
  });
  Event.observe('auction_postcode', 'blur', function(event) {
    if($('auction_postcode').value == '') {
      $('auction_postcode').value = postcodeValue;
      Element.setStyle('auction_postcode', {color:'#888'});
    }
  });
  Event.observe('auction_postcode', 'keyup', function(event) {
    // Hide postcode error from previous request
    Element.update('postcode_error', ''); // hide sometimes made problems, because the error has been shown anyway under certain circumstances
    Element.removeClassName('auction_postcode', 'error');

    checkPostcode();
  });

  // Execute checkPostcode at startup
  checkPostcode();
});


function checkPostcode()
{
  if($('auction_postcode').value.match(/\d{4,6}/)) {
    if($('auction_postcode').value != lastRequest) {
      Element.show('ajax_loading');
      
      lastRequest = $('auction_postcode').value;
      new Ajax.Request(postcodeSearchUrl.replace(/POSTCODE/, $('auction_postcode').value), {method: 'get', onSuccess: function(transport) {
        // Hide loading indicator
        Element.hide('ajax_loading');

        // Not found?
        if(transport.responseText == 'NOT FOUND') {

          // Show error message
          Element.show('postcode_not_found');
          Element.hide('postcode_container');

        } else { // Found

          // Get results
          var results = transport.responseText.evalJSON();

          if(results.length == 1)
          {
            // If only one city has been found, show it as plain text
            var html = results[0]['name'];
            html += '<input type="hidden" id="auction_postcode_id" name="auction[postcode_id]" value="' + results[0]['id'] + '" />';
          }
          else
          {
            // Transform JSON into html-options for dropdown item
            var html = '<select id="auction_postcode_id" name="auction[postcode_id]"';
            if($('auction_postcode_id').hasClassName('error')) html += ' class="error"';
            html += '>';
            html += '<option value="0">' + postcodeSearchSpecifyZone + '</option>';
          
            for(var i = 0 ; i < results.length ; i++) {
              html = html + '<option value="' + results[i]['id'] + '"';
              if(
                (typeof(selectedPostcodeId) != 'undefined' && selectedPostcodeId == results[i]['id']) ||
                (results.length == 1)
              ) {
                html = html + ' selected="selected"';
                selectedCity = null;
              }
              html = html + '>' + results[i]['name'] + '</option>';
            }
            
            html += '</select>';
          }

          // Show things
          Element.update('postcode_container', html);
          Element.hide('postcode_not_found');
          Element.show('postcode_container');

        }
      }});
    }
  }
}



/*
 * CARES
 */

function showCare(url, width, height, sameBox)
{
  fb.start({href: url, rev: "type:ajax;sameBox:" + sameBox + ";width:" + width +";height:" + height});
}

function enableCare(id)
{
  $('iconCare' + id).src = window['image_care_enabled'];
  $('careLink' + id).style.fontWeight = 'bold';
  if(id != 0 && id != 14) // Not "first visit" and "further"
  {
    Element.show('careDisableLink' + id);
  }
}

function disableCare(id)
{
  $('iconCare' + id).src = window['image_care_disabled'];
  $('careLink' + id).style.fontWeight = 'normal';
  if(id != 0 && id != 14) // Not "first visit" and "further"
  {
    Element.hide('careDisableLink' + id);
  }
}


/*
 * SCHEMA
 */

function showTooth(number, types, suffix)
{
  $('toothBoxNumber' + suffix).innerHTML = number;
  fb.start($('toothBoxLink' + suffix));
  
  for(var i = 0 ; i < types.length ; i++)
  {
  if(window['teeth' + types[i] + suffix].contains(number))
  {
      $('tooth_' + types[i] + suffix).setAttribute('checked', 'checked');
      $('tooth_' + types[i] + suffix).setAttribute('defaultChecked', 'defaultChecked'); /* IE workaround */
      $('tooth_' + types[i] + suffix).checked = true;
      $('tooth_' + types[i] + suffix).defaultChecked = true;
  }
  else
  {
      $('tooth_' + types[i] + suffix).removeAttribute('checked');
      $('tooth_' + types[i] + suffix).removeAttribute('defaultChecked'); /* IE workaround */
      $('tooth_' + types[i] + suffix).checked = false;
      $('tooth_' + types[i] + suffix).defaultChecked = false;
  }
  }
}

function saveTooth(number, types, suffix)
{
  for(var i = 0 ; i < types.length ; i++)
  {
  if($('tooth_' + types[i] + suffix).checked)
  {
    addTooth(number, types[i], suffix);
  }
  else
  {
      removeTooth(number, types[i], suffix);
      
      /* Hide tooth marker if tooth is no longer selected */
      Element.hide('tooth' + types[i] + number + suffix);
  }
  }
  
  fb.end();
  generateFormValues(types, suffix);
}

function addTooth(number, type, suffix)
{
  if(!(window['teeth' + type + suffix]).contains(number))
  {
    (window['teeth' + type + suffix]).push(number);
  }
}

function removeTooth(number, type, suffix)
{
  for(var i = 0 ; i < (window['teeth' + type + suffix]).length ; i++)
    {
      if((window['teeth' + type + suffix])[i] == number)
      {
        (window['teeth' + type + suffix]).array_cut(i);
      }
    }
}


function generateFormValues(types, suffix)
{
  for(var i = 0 ; i < types.length ; i++)
  {
  var data = window['teeth' + types[i] + suffix];
  
    var value = '';
    for(var j = 0 ; j < data.length ; j++)
    {
      if(value != '') 
      {
        value += ',';
      }
      value += data[j];
      
      /* Show tooth marker */
      Element.show('tooth' + types[i] + data[j] + suffix);
    }
    
    /* Update hidden input fields */
    $('teeth_to_' + types[i] + suffix).value = value;
  }
}

