window.onload = focusFirstField;

/*==============================================================================
  GENERIC FORM MANIPULATION
------------------------------------------------------------------------------*/
// focus the first input with a class of 'firstField' (to be performed onload)
function focusFirstField() {
  var firstField = document.getElementsByClassName('firstField');
  if (firstField && firstField[0]) {
    firstField[0].focus();
  }
}

// Requests a new form from the server
function addNewFormFor(objectType,url) {
  var index = document.getElementsByClassName(objectType + "Form").length;
  new Ajax.Updater(
    objectType + 'List',
    url + "/" + index,
    {
      asynchronous:true,
      evalScripts:true,
      insertion:Insertion.Bottom
    }
  );
}

// Sets the value of the deleted field to 1 if it exists.
// Hides the elem if the deleted field exists.
// Otherwise, removes the elem.
function removeForm(objectType, index) {
  var elem = $(objectType+'Form'+index);
  var delField = document.getElementById(objectType+"_"+index+"_deleted");
  if (delField) {
    delField.value = 1;
    Element.hide(elem);
  } else {
    Element.remove(elem);
  }
}


/*==============================================================================
  PROJECT FORM - saving assets and projects
------------------------------------------------------------------------------*/
function newProject(url) {
  new Ajax.Updater('editProject', url, {onComplete: checkProjectLimit});
}

function editProject(url) {
  new Ajax.Updater('editProject', url);
}

function validateProject() {
  if (!$('project_name').value) {
    $('project_name').focus();
    alert("Please enter a project name first.");
    return false;
  }
  return true;
}

function projectSaved(new_url, list_url) {
  new Ajax.Updater('editProject', new_url, {onComplete: checkProjectLimit} );
  setTimeout(function(){ new Ajax.Updater('projectList', list_url);}, 10);
}

function removeProject(url) {
  new Ajax.Updater('projectList', url, {evalScripts:true});
}

function uploadImage(fileField, url) {
  // find the form to which this field belongs
  var form = $('projectForm');
  
  // set the form's target to the iframe, and temporarily change the action
  form.setAttribute('real_action', form.getAttribute('action'));
  form.setAttribute('action', url);

  form.submit();

  form.setAttribute('action', form.getAttribute('real_action'));

  // clear the contents of the file field (by regenerating it from scratch)
  input = document.createElement('input');
  input.type = 'file';
  input.id = 'asset_uploaded_data';
  input.name = 'asset[uploaded_data]';
  input.size = fileField.getAttribute('size');
  input.onchange = fileField.onchange;
  fileField.parentNode.insertBefore(input, fileField);
  Element.remove(fileField);

  return false;
}

function imageUploaded(url) {
  new Ajax.Updater(
    'projectImages', 
    url,
    {onComplete:checkImageLimit}
  );
}

function deleteImage(url) {
  if (confirm("Delete this image?")) {
    new Ajax.Updater('projectImages', url, {onComplete: checkImageLimit});
  }
}

// count .projectImages in #projectImages -- if greater than 3, 
// hide #projectImageUploader
function checkImageLimit() {
  var images=document.getElementsByClassName('projectImage', $('projectImages'));
  var elem = $('projectImageUploader');
  if (images.length > 3) {
    elem.style.display = 'none';
  } else {
    elem.style.display = 'block';
  }
}

// count inputs in #projectForm -- if none, hide #newProjectLink
function checkProjectLimit() {
  var inputs = $('editProject').getElementsByTagName('input');
  var link = $('newProjectLink');
  if (!inputs || inputs.length < 1) {
    link.style.display = 'none';
  } else {
    link.style.display = 'block';
  }
}

/*==============================================================================
  OFFICE FORM - collapsing and expanding offices
------------------------------------------------------------------------------*/
function collapseOffices(except) {
  var offices = $('officeList').getElementsByTagName('li');
  for (var i=0;i<offices.length;i++) {
    var office = offices[i];
    index = office.id.match(/\d+/);
    if (office != except) {
      var fieldset = office.getElementsByTagName('fieldset')[0];
      Element.hide(fieldset);

      var tbl = office.getElementsByTagName('table')[0];
      Element.show(tbl);

      var address = $('office_'+index+'_address1').value;
      var address2 = $('office_'+index+'_address2').value;
      if (address2) { address += "<br />" + address2; }
      tbl.rows[0].getElementsByTagName("td")[0].innerHTML = 
        address + "<br />" +
        $('office_'+index+'_suburb').value + " " + 
        $('office_'+index+'_postcode').value + "<br />" +
        $('office_'+index+'_state').value + "<br />";
      tbl.rows[1].getElementsByTagName("td")[0].innerHTML = 
        $('office_'+index+'_contact').value;
      tbl.rows[2].getElementsByTagName("td")[0].innerHTML = 
        $('office_'+index+'_phone').value;
      tbl.rows[3].getElementsByTagName("td")[0].innerHTML = 
        $('office_'+index+'_fax').value;
      tbl.rows[4].getElementsByTagName("td")[0].innerHTML = 
        $('office_'+index+'_email').value;
    }
  }
}

function expandOffice(office) {
  collapseOffices();

  var fieldset = office.getElementsByTagName('fieldset')[0];
  Element.show(fieldset);

  var tbl = office.getElementsByTagName('table')[0];
  Element.hide(tbl);
}


/*==============================================================================
  PRACTICE FORM
------------------------------------------------------------------------------*/
function editLogo() {
  var fileField = document.createElement('input');
  fileField.type = "file";
  fileField.name = "practice[logo]";
  fileField.id = "practice_logo";
  fileField.size = 18;
  var savedLogo = document.getElementById('savedLogo');
  savedLogo.parentNode.insertBefore(fileField, savedLogo);
  savedLogo.parentNode.removeChild(savedLogo);
  return false;
}

/*==============================================================================
  LIST PRACTICES - filter
------------------------------------------------------------------------------*/
function filterByCategory(catId) {
  var practices = document.getElementsByClassName('practice');
  for (var i=0;i<practices.length;i++) {
    var practice = practices[i];
    if (!catId) {
      Element.show(practice);
    } else {
      if (typeof practice.categoryArray == "undefined") {
        practice.categoryArray = practice.getAttribute("categories").split(",");
      }
      practice.categoryArray.indexOf(catId) >= 0 ? 
        Element.show(practice) : 
        Element.hide(practice);
    }
  }
}

function filterByLocation(locSlug) {
  var practices = document.getElementsByClassName('practice');
  for (var i=0;i<practices.length;i++) {
    var practice = practices[i];
    if (!locSlug) {
      Element.show(practice);
    } else {
      if (typeof practice.locationArray == "undefined") {
        practice.locationArray = practice.getAttribute("locations").split(",");
      }
      practice.locationArray.indexOf(locSlug) >= 0 ? 
        Element.show(practice) : 
        Element.hide(practice);
    }
  }
}

function filterByBoth() {
  var catId = $('showOnlyCat').value;
  var locSlug = $('showOnlyLoc').value;

  var practices = document.getElementsByClassName('practice');
  for (var i=0;i<practices.length;i++) {
    var practice = practices[i];
    if (!locSlug && !catId) {
      Element.show(practice);
    } else {
      if (typeof practice.locationArray == "undefined") {
        practice.locationArray = practice.getAttribute("locations").split(",");
      }
      if (typeof practice.categoryArray == "undefined") {
        practice.categoryArray = practice.getAttribute("categories").split(",");
      }
      if (!locSlug) {
        practice.categoryArray.indexOf(catId) >= 0 ? 
          Element.show(practice) : 
          Element.hide(practice);
      } else if (!catId) {
        practice.locationArray.indexOf(locSlug) >= 0 ? 
          Element.show(practice) : 
          Element.hide(practice);
      } else {
        practice.locationArray.indexOf(locSlug) >= 0 && 
          practice.categoryArray.indexOf(catId) >= 0 ? 
          Element.show(practice) : 
          Element.hide(practice);
      }
    }
  }
}

/*==============================================================================
  PAYMENT SUBMISSION
  We're going to politely syphon the form submission on its way to Paypal and 
  save the details for our own records.
------------------------------------------------------------------------------*/
function submitToPaypal(form) {
  var i = 1;
  do {
    var paymentMethod = $('payment_method'+i);
    if (paymentMethod && paymentMethod.checked) {break;}
    i += 1;
  } while (paymentMethod);

  if (paymentMethod.value == 'paypal') {
    params = Form.serialize(form);
    new Ajax.Request(
      form.getAttribute('ajax_url'),
      {
        parameters: Form.serialize(form)
      }
    );
  } else {
    form.setAttribute('action', paymentMethod.getAttribute('action'));
  }
  return true;
}
