String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
String.prototype.trimNumber = function () {
   return this.replace(/^0+/, "");
} 

/** Limit input in textarea */
function limitText(limitField, limitCount, limitNum) {
  if (limitField.value.length >= limitNum) {
    limitField.value = limitField.value.substring(0, limitNum-1);
   }
   else {
     if (limitCount) {
      limitCount.value = limitNum - limitField.value.length;
    }
  }
}

/** Validate that the uploaded file has the correct extension */
function checkUpload(filename, lang)
{
  /* validate uploaded file */
  if ( filename.toLowerCase().lastIndexOf('.jpg') == -1 &&
       filename.toLowerCase().lastIndexOf('.jpeg') == -1) {
    if ( lang == 'fr' ) {
      alert("Seulement les images au format jpeg sont acceptées (extensions .jpg ou .jpeg)");
    }
    else {
      alert('Please, submit only jpeg images (.jpg or .jpeg extensions)');
    }
    return false;
  }
  return true;
}

/** Validate the form before submission */
function validateForm(lang)
{
  /* validate text input */
  var required = {'input_email': { 'label': 'label_email', 'help': 'Email invalid.' },
                  'input_title': { 'label': 'label_title' },
                  'input_director': { 'label': 'label_director' },
                  'input_length_min' : { 'label': 'label_length', 'help': 'Length (min.) invalid.' },
                  'year' : {'label': 'label_year'},
                  'input_genre': {'label': 'label_genre'},
                  'input_country': {'label': 'label_country'},
                  'input_summary': {'label': 'label_summary'},
                  'input_picture_file' : {'label': 'label_picture_file' }};

  var missings = false;
  
  for (var req in required) {
    var missing = false;
    var val = document.forms['submission'].elements[req].value.trim();

    if ( val != null  && val != '' ) {
      if ( req == 'input_length_min' || req == 'input_length_sec' ) {
	
        if ( isNaN(Number(val)) ) {
          missing = true;
          alert(required[req]['help']);
          document.forms['submission'].elements[req].value = 0;
        }        
       document.forms['submission'].elements[req].value = val.trimNumber();
      }
      if ( req == 'input_email' ) {
        apos=val.indexOf("@");
        dotpos=val.lastIndexOf(".");
        if (apos<1||dotpos-apos<2) {
          alert(required[req]['help']);
          missing = true;
          document.forms['submission'].elements[req].value = '';
        }
      }
    }
    else {
     missing = true;
    }
    if ( missing ) {
      missings = true;
      document.getElementById(required[req]['label']).className = 'required';
    }
    else {
      document.getElementById(required[req]['label']).className = '';
    }
    missing = false;
  }

  /* validate radio */
  var radioToCheck = ['uk_premiere', 'world_premiere', 'szeged'];
  var radioLabel = ['label_uk', 'label_world', 'label_szeged'];
  for (i=0;i<radioToCheck.length; i++) {
    if ( ! getRadioCheckedValue(radioToCheck[i]) ) {
      missings = true;
      document.getElementById(radioLabel[i]).className = 'required';
    }
    else {
      document.getElementById(radioLabel[i]).className = '';
    }
  }

  /* Warn the user */
  if (missings) {
      alert('Some required fields are missing.');
    return false;
  }

  /* Check the upload file is ok */
  if ( ! checkUpload(document.forms['submission'].picture_file.value) ) {
    return false;
  }
  
  
  /* Check the disclaimer */
  if ( ! document.forms['submission'].elements['disclaimer'].checked ) {
      alert('You must agree to the Festival Rules and check the box and the end of the form before submitting your registration.');
      document.getElementById("disclaimer_text").className = 'required';
    return false;
  }
  
  /* Check the summary */
  if (document.forms['submission'].elements['input_summary'].value.length > 250) {
    alert('The summary is too long. Only 255 characters are allowed.');
    return false;
  }
  
    /* Check the summary */
  if (document.forms['submission'].elements['input_main_festivals'].value.length > 250) {
    alert('The main festival section is too long. Only 255 characters are allowed.');
    return false;
  }

  return true;
}

/** Return the value of a set of radio inputs */
function getRadioCheckedValue(radio_name) {
  var oRadio = document.forms['submission'].elements[radio_name];

  for(var i = 0; i < oRadio.length; i++) {
    if(oRadio[i].checked) {
      return oRadio[i].value;
    }
  }
  return '';
}

/** Remove a director input */
function removeDirector(form, id) {
   var dir_area = document.getElementById('directors');
   var toremove = document.getElementById(id);
   dir_area.removeChild(toremove);
 }

 /** Add a new director input (up to three) */
function addDirector(form,json){
 var dir_area = document.getElementById('directors');
 var dir_count = dir_area.getElementsByTagName('tr').length + 1;

 if ( dir_count > 10 ) {
   alert('You can only enter 10 directors');
   return;
 }

 var newLine = document.createElement('tr');
 newLine.id = 'div_director_' + dir_count;
 var newLabel = document.createElement('td');
 newLabel.innerHTML = 'Director #' + dir_count ;
 newLabel.className = 'label';
 var newInput = document.createElement('input');
 newInput.name = 'directors[]';
 newInput.type = 'text';
 newInput.className = 'long';
 newLine.appendChild(newLabel);
 var newCell = document.createElement('td');
 newCell.appendChild(newInput);
 var newRemove = document.createElement('input');
 newRemove.type = 'button';
 newRemove.value = '-';
 newRemove.onclick = function() {removeDirector(form, newLine.id);}
 newCell.appendChild(newRemove);
 newLine.appendChild(newCell);
 dir_area.appendChild(newLine);
 
 
}
